Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ All notable changes to Agrippa are documented here. The format follows
- **The compose stack's volumes were named `infra_*`** — with no `name:` key the project name defaulted to the compose file's directory, so `pgdata`/`artifacts`/`workspaces` were created under an `infra` prefix: surprising when restoring a backup, and liable to collide with any other stack living in an `infra/` directory. Now pinned to `agrippa`. **Upgrading from `v0.2.0` or earlier requires a one-time volume migration** — otherwise `docker compose up -d` builds a second, empty stack beside the old one and collides on the published port. The documented procedure guards both ends. It refuses to copy into a non-empty target, because `docker volume create` succeeds silently on an existing volume and `cp -a` leaves destination-only files in place, so copying onto a started-then-abandoned stack would merge two Postgres clusters. And it preflights the sources, because Docker creates a missing named volume on the fly — a mistyped name would otherwise mount an empty one, copy nothing, and leave a fresh empty database that passes `/healthz` while the real data sits elsewhere. Step-by-step procedure: [Operations → Upgrading from a deployment created before the compose project was named](docs/manual/en/06-operations.md#upgrades--scaling).
- **`AGRIPPA_PORT` exposed the plain-HTTP API on `0.0.0.0`** — it is the left side of the compose port mapping, so it can carry an interface. Documented as `127.0.0.1:3000` for the reverse-proxy topology, which is the only supported way to run it publicly.
- **The worker could be SIGKILLed mid-drain** — it handles SIGTERM by awaiting pg-boss's graceful stop, but compose's default `stop_grace_period` is 10s. Raised to 60s.
- **A thorough review report could kill its run at the review gate** — checkpoint-driving artifacts (review reports, questions) had to fit the store's general 64 KB inline threshold, but the interaction schemas admit a valid report of ~248K characters (up to ~1.5 MB as escaped JSON), so a schema-valid report of a large change failed the run with `contract_violation` instead of opening the gate. Interaction artifacts now get their own inline allowance (`INTERACTION_ARTIFACT_MAX_BYTES`, 2 MiB), sized to dominate any schema-valid payload — so only genuinely invalid (or padded) content can still trip the distinct too-large error. Both previously-untested failure paths (store-time and the resume-time legacy-row backstop) are now covered by the engine compliance suite.
- **A working diff over 64 KB could no longer be published** — the `git.push` evidence check compared the fresh snapshot against `artifactValues`, which holds `""` for any patch artifact past the inline threshold, so every run whose reviewed diff exceeded 64 KB died at publish with a phantom "workspace changed after the reviewed evidence". Every stored artifact row now carries a store-time `sha256` (migration `0013`), and the check verifies a larger-than-inline patch against that digest — deliberately never against the spilled disk bytes, which live on a volume agent subprocesses can write to (same container, same user, no inner sandbox under Docker) and could be rewritten after review. File-kind artifacts hash the exact byte stream being written (single pass, size counted and capped mid-stream), not a re-read of the mutable source. Genuinely drifted workspaces still fail, and a spilled patch without a digest fails the push with a distinct `contract_violation` instead of publishing unverified. The digest is tamper-resistance within the documented deployment posture, not a boundary — an agent that recovers worker credentials (possible under compose, see the sandboxing residual in design 08) can forge database state wholesale; per-run isolation remains the M2 work. This was the remaining follow-up from PR #5's review rounds.
- **Deploy verification now proves each worker replica actually consumes, not just that one registered** (closes #15) — `worker_ok()` accepted a fresh `executor_registrations` row, which the worker writes *before* starting its pg-boss consumers, so a worker that registered and then wedged inside consumer setup read as a successful deploy while nothing consumed the queue. Workers now upsert a per-container row into the new `worker_heartbeats` table (migration `0012`) — hostname inside compose is the container id — where boot start clears `consumers_ready_at`, only the return of `boss.work()` for every consumer re-sets it (so a restart that wedges cannot coast on the previous boot's stamp), and the sweeper bumps a 60 s liveness heartbeat (rows silent for a week are pruned). `deploy.sh` requires one ready-and-alive row per expected `WORKER_REPLICAS`, scoped to the hostnames of this fleet's running containers (`docker inspect {{.Config.Hostname}}`) so a foreign container pointed at the same database — a debug `docker run`, an out-of-band scale leftover, a second stack — can never supply the count; aliveness uses a sliding 90 s window on the sweeper heartbeat (a fixed post-deploy stamp would let one beat mask a later wedge, and would fail rollbacks/same-commit redeploys that reuse unchanged healthy containers), the sweeper beats first in its tick so sweep errors cannot skip it, and `WORKER_REPLICAS` below 1 is rejected up front (0 made the check vacuous). The replica-count and RestartCount checks stay, each still catching what the row count cannot (out-of-band scaling; crash loops that get past consumer setup). The compose worker now also gates its start on api health (`depends_on: service_healthy`, mirroring the VM unit's `/healthz` gate) so its boot-time DB writes cannot race the migration that ships this table and trip the RestartCount check on the very deploy that introduces it; `up -d` is bounded by `timeout 600` since it now waits on api health.

- **Dead clicks after confirming a retry, and sidebar collapse quirks** — Radix modal layers lock `<body>` with `pointer-events: none` while open; the retry confirm dialog navigating to the new run could unmount it mid-exit-animation and leave the lock behind, after which every click (the sidebar toggle included) silently did nothing:
- *Stale body locks are cleared when a navigation settles* — a router subscription resets the lock, covering every dialog/dropdown that a route change can unmount mid-close.
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export async function postgresAvailable(): Promise<boolean> {
/** Fresh schema per test run: drop everything, migrate, seed builtins. */
export async function freshTestDb(): Promise<Db> {
const db = testDb();
await db.execute(sql`drop schema public cascade`);
await db.execute(sql`drop schema if exists public cascade`);
await db.execute(sql`create schema public`);
// the migrator journals into its own "drizzle" schema — reset it too,
// or migrations silently no-op on the second run
Expand Down
80 changes: 80 additions & 0 deletions apps/worker/src/deps/artifacts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,86 @@ describe("DiskArtifactStore path containment", () => {
}
});

it("inlines past 64 KB when the caller raises the inline limit", async () => {
const ws = freshWorkspace();
await mkdir(path.join(ws, ".agrippa/artifacts"), { recursive: true });
const content = "r".repeat(100 * 1024); // 100 KB — over the default threshold
writeFileSync(path.join(ws, ".agrippa/artifacts/report.json"), content);

// without the override, the same file goes to disk
const onDisk = await store.store(
"run-1",
"report",
"json",
{ path: ".agrippa/artifacts/report.json" },
ws,
);
expect(onDisk.inline).toBeNull();
expect(onDisk.storageRef).not.toBeNull();

// with it (the engine's interaction-artifact path), it inlines whole
const inlined = await store.store(
"run-2",
"report",
"json",
{ path: ".agrippa/artifacts/report.json" },
ws,
{ inlineLimitBytes: 2 * 1024 * 1024 },
);
expect(inlined.inline).toBe(content);
expect(inlined.storageRef).toBeNull();

// engine-provided inline sources honor the same override
const inlineSource = await store.store("run-3", "report", "json", { inline: content }, ws, {
inlineLimitBytes: 2 * 1024 * 1024,
});
expect(inlineSource.inline).toBe(content);
expect(inlineSource.storageRef).toBeNull();
});

it("spills to disk when content exceeds even a raised inline limit", async () => {
const ws = freshWorkspace();
const content = "x".repeat(200 * 1024);
const stored = await store.store("run-1", "report", "json", { inline: content }, ws, {
inlineLimitBytes: 128 * 1024,
});
expect(stored.inline).toBeNull();
expect(stored.storageRef).not.toBeNull();
expect(stored.size).toBe(200 * 1024);
});

it("stamps every store with the content's sha256 — the push-time evidence anchor", async () => {
const ws = freshWorkspace();
const content = "p".repeat(100 * 1024); // over the 64 KB threshold → disk
const expected = new Bun.CryptoHasher("sha256").update(content).digest("hex");

const spilled = await store.store("run-hash", "changes", "patch", { inline: content }, ws);
expect(spilled.inline).toBeNull();
expect(spilled.sha256).toBe(expected);

const inlined = await store.store("run-hash", "small", "patch", { inline: "tiny diff" }, ws);
expect(inlined.sha256).toBe(new Bun.CryptoHasher("sha256").update("tiny diff").digest("hex"));

// file-kind artifacts stream to disk; the digest must describe the bytes
// actually WRITTEN (hashed in the same pass), not a re-read of the
// agent-mutable source
await mkdir(path.join(ws, ".agrippa/artifacts"), { recursive: true });
writeFileSync(path.join(ws, ".agrippa/artifacts/blob"), content);
const streamed = await store.store(
"run-hash",
"blob",
"file",
{ path: ".agrippa/artifacts/blob" },
ws,
);
expect(streamed.sha256).toBe(expected);
const storedBytes = new Uint8Array(await Bun.file(streamed.storageRef as string).arrayBuffer());
expect(new Bun.CryptoHasher("sha256").update(storedBytes).digest("hex")).toBe(
streamed.sha256 as string,
);
expect(streamed.size).toBe(storedBytes.byteLength);
});

it("falls back to the default cap when the size env is not a valid number", async () => {
const ws = freshWorkspace();
await mkdir(path.join(ws, ".agrippa/artifacts"), { recursive: true });
Expand Down
69 changes: 54 additions & 15 deletions apps/worker/src/deps/artifacts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdir, realpath } from "node:fs/promises";
import { mkdir, realpath, unlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { ArtifactKind } from "@agrippa/core";
Expand All @@ -24,7 +24,10 @@ class ArtifactTooLargeError extends Error {
}
}

const EMPTY: StoredArtifact = { inline: null, storageRef: null, size: 0, mime: null };
const EMPTY: StoredArtifact = { inline: null, storageRef: null, size: 0, mime: null, sha256: null };

const sha256Hex = (content: string | Uint8Array): string =>
new Bun.CryptoHasher("sha256").update(content).digest("hex");

/**
* Resolve a workspace-relative artifact source to a real path that is provably
Expand All @@ -47,21 +50,27 @@ async function resolveContainedPath(workspaceDir: string, rel: string): Promise<
return real;
}

/** ≤64 KB inline in Postgres; larger content on the artifacts volume. */
/**
* ≤64 KB inline in Postgres; larger content on the artifacts volume. The
* engine raises the inline threshold per call (opts.inlineLimitBytes) for
* checkpoint-driving artifacts, which must inline whole to survive resume.
*/
export class DiskArtifactStore implements ArtifactStore {
async store(
runId: string,
key: string,
kind: ArtifactKind,
source: { inline?: unknown; path?: string },
workspaceDir: string,
opts?: { inlineLimitBytes?: number },
): Promise<StoredArtifact> {
const inlineLimit = opts?.inlineLimitBytes ?? INLINE_LIMIT;
// engine-provided inline content (patch diffs, links) is always text
if (source.inline !== undefined) {
const content =
typeof source.inline === "string" ? source.inline : JSON.stringify(source.inline);
const mime = kind === "json" ? "application/json" : "text/markdown";
return this.storeText(runId, key, content, mime);
return this.storeText(runId, key, content, mime, inlineLimit);
}
if (!source.path) return EMPTY;

Expand All @@ -78,32 +87,62 @@ export class DiskArtifactStore implements ArtifactStore {

// small text can inline in Postgres; `file`-kind (possibly binary) and any
// large artifact stream straight to disk byte-exact, never fully buffered
if (kind !== "file" && size <= INLINE_LIMIT) {
return this.storeText(runId, key, await file.text(), mime);
if (kind !== "file" && size <= inlineLimit) {
return this.storeText(runId, key, await file.text(), mime, inlineLimit);
}
const storageRef = await this.writeToDisk(runId, key, file);
return { inline: null, storageRef, size, mime };
return { inline: null, mime, ...(await this.streamToDisk(runId, key, file)) };
}

/**
* Single-pass spill: hash and count exactly the bytes being written — the
* source lives in the (agent-mutable) workspace, so re-reading it to hash
* after the copy could describe different content than what was stored, and
* a file growing mid-copy must trip the size cap, not land oversized.
*/
private async streamToDisk(
runId: string,
key: string,
file: ReturnType<typeof Bun.file>,
): Promise<{ storageRef: string; size: number; sha256: string }> {
const dir = path.join(STORAGE_ROOT, runId);
await mkdir(dir, { recursive: true });
const storageRef = path.join(dir, key);
const hasher = new Bun.CryptoHasher("sha256");
const writer = Bun.file(storageRef).writer();
let written = 0;
try {
for await (const chunk of file.stream()) {
written += chunk.byteLength;
if (written > maxArtifactSize()) throw new ArtifactTooLargeError(key, written);
hasher.update(chunk);
writer.write(chunk);
}
await writer.end();
} catch (err) {
await Promise.resolve(writer.end()).catch(() => {});
await unlink(storageRef).catch(() => {});
throw err;
}
return { storageRef, size: written, sha256: hasher.digest("hex") };
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

private async storeText(
runId: string,
key: string,
content: string,
mime: string | null,
inlineLimit: number,
): Promise<StoredArtifact> {
const size = Buffer.byteLength(content);
if (size === 0) return EMPTY;
if (size > maxArtifactSize()) throw new ArtifactTooLargeError(key, size);
if (size <= INLINE_LIMIT) return { inline: content, storageRef: null, size, mime };
const sha256 = sha256Hex(content);
if (size <= inlineLimit) return { inline: content, storageRef: null, size, mime, sha256 };
const storageRef = await this.writeToDisk(runId, key, content);
return { inline: null, storageRef, size, mime };
return { inline: null, storageRef, size, mime, sha256 };
}

private async writeToDisk(
runId: string,
key: string,
data: string | Uint8Array | Blob,
): Promise<string> {
private async writeToDisk(runId: string, key: string, data: string): Promise<string> {
const dir = path.join(STORAGE_ROOT, runId);
await mkdir(dir, { recursive: true });
const storageRef = path.join(dir, key);
Expand Down
Loading
Loading