diff --git a/deploy/cloudflare-memory/runLedger.test.ts b/deploy/cloudflare-memory/runLedger.test.ts index 3ece8d77d..9d2402971 100644 --- a/deploy/cloudflare-memory/runLedger.test.ts +++ b/deploy/cloudflare-memory/runLedger.test.ts @@ -1,7 +1,14 @@ import { testSourceObligationJob } from "../../src/core/testing/sourceObligations.ts"; import { sourceObligationHolder } from "../../src/core/runLedger/sourceObligations.ts"; import type { SourceEventReceipt } from "../../src/core/runLedger/sourceEvents.ts"; -import { testSourceInput, testSourceInputIntent, seedSourceInputIntent } from "../../src/core/testing/sourceInputs.ts"; +import { unreadInbox } from "../../src/core/runLedger/decisions.ts"; +import type { StepRecord } from "../../src/core/runLedger/types.ts"; +import { + testSourceInput, + testSourceInputIntent, + seedSourceInputIntent, + seedSourceInputCheckpoints, +} from "../../src/core/testing/sourceInputs.ts"; import { captureSourceTaskSnapshot } from "../../src/core/references/sourceTaskSnapshot.ts"; import { checkStateFixture } from "../../src/core/testing/checkState.ts"; import { captureCheckArchive } from "../../src/core/checkInspection.ts"; @@ -105,6 +112,9 @@ import type { ToolContext } from "../../src/tools/runnableTool.ts"; import { InMemoryGithubApi } from "../../src/execution/githubApi.ts"; import { mergeContextDependencies } from "../../src/core/references/contextDependencies.ts"; import { sourceSeedOriginalKey } from "../../src/core/runLedger/seedVerification.ts"; +import { checkpointPiSourceInput } from "../../src/core/harness/pi/sourceInputCheckpoint.ts"; +import { createHash } from "node:crypto"; +import { readSourceInputProof } from "../../src/core/references/sourceInputProof.ts"; const unreadOrigin = { version: 1 as const, @@ -22233,3 +22243,423 @@ describe("reader-first source obligation compatibility in SQLite", () => { }); }); }); + +describe("canonical native input checkpoint in SQLite", () => { + async function fixture(renderedText?: string) { + const key = storeKey(); + const options = { + baseUrl: BASE, + token: "test-token", + storeKey: key, + fetch: (input: RequestInfo | URL, init?: RequestInit) => fetchMemoryTest(String(input), init), + }; + const ledger = new WorkerRunLedger(options), + store = new WorkerRunStore(options); + return { + key, + ledger, + store, + ...(await seedSourceInputCheckpoints( + ledger, + renderedText === undefined ? undefined : createHash("sha256").update(renderedText).digest("hex"), + )), + }; + } + async function unread(ledger: WorkerRunLedger, id: string, gen = "g1") { + const peek = await ledger.peekInbox(id, gen, 0); + if (!peek.ok) throw new Error("missing checkpoint fixture"); + return peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq); + } + it.each(["commit", "ack"] as const)( + "reconciles a saved Pi fixture through the host and SQLite after a lost %s response without repeating it", + async (lostOperation) => { + const text = "Synthetic source input."; + const { key, ledger, id, gen, thread, intents } = await fixture(text); + const entry = intents.entries[0]!; + const file = { + path: entry.native.sessionId, + content: + [ + { type: "session", version: 3, id: "native-session-uuid" }, + { + type: "custom_message", + id: "native-entry-one", + parentId: null, + customType: "switchboard-source-input", + content: text, + display: false, + details: { version: 1, intent: entry }, + }, + ] + .map((record) => JSON.stringify(record)) + .join("\n") + "\n", + }; + const mutations: string[] = []; + let dropResponse = true, + holdReadback = false; + const wire = new WorkerRunLedger({ + baseUrl: BASE, + token: "test-token", + storeKey: key, + fetch: async (input, init) => { + if (String(input).endsWith("/runs/source-input/checkpoint")) { + const body = JSON.parse(String(init?.body)) as { request: { operation: string } }; + const operation = body.request.operation; + if (operation === "read" && holdReadback) return new Response("fixture read held", { status: 503 }); + if (operation !== "read") { + mutations.push(operation); + if (operation === lostOperation && dropResponse) { + dropResponse = false; + await fetchMemoryTest(String(input), init, (response) => response.json()); + holdReadback = true; + throw new TypeError("fixture original response lost"); + } + } + } + return fetchMemoryTest(String(input), init); + }, + }); + const writer = createLedgerWriteThrough({ + ledger: wire, + gen, + warn() {}, + fallback: { put: async () => {}, abandoned() {} }, + setInterval: () => ({ unref() {} }), + clearInterval() {}, + schedule: () => ({ cancel() {} }), + }); + const row = (await ledger.listLive()).find((candidate) => candidate.runId === id); + if (!row) throw new Error("missing original live row"); + const run = writer.adopt({ + runId: id, + threadKey: thread, + state: row.state, + meta: row.meta, + startedAt: row.startedAt, + lastStep: 0, + lastSeq: 0, + }); + const validate = async (context: ContextDependencies) => { + for (const reference of context.sourceInputs ?? []) { + const proof = await readSourceInputProof(reference, { ledger, checkAccess: async () => true }); + if (proof.kind !== "consistent") return { ok: false as const, code: "saved-context-unproved" as const }; + } + return { ok: true as const }; + }; + try { + expect(await checkpointPiSourceInput(entry, { ...file, path: file.path + ".copy" }, run, validate)).toBe(false); + expect(mutations).toEqual([]); + expect(await checkpointPiSourceInput(entry, file, run, validate)).toBe(false); + expect(mutations).toEqual(lostOperation === "commit" ? ["commit"] : ["commit", "ack"]); + expect(await unread(ledger, id)).toEqual(lostOperation === "commit" ? [1, 2, 3, 4] : [1, 3, 4]); + expect(await run.commitState({ fixtureAfterUnknown: true })).toBe("unavailable"); + const held = await ledger.peekInbox(id, gen, 0); + expect(held.ok && held.boundary.state).not.toHaveProperty("fixtureAfterUnknown"); + holdReadback = false; + const saved = await run.sourceInputCheckpoint({ operation: "read", inputId: entry.id }, validate); + expect(saved).toMatchObject({ + ok: true, + checkpoint: { + acknowledged: lostOperation === "ack", + receipt: { + inputId: "source-input-one", + native: { + sessionId: "original-native-session", + sessionIdentity: "native-session-uuid", + entryId: "native-entry-one", + }, + }, + }, + }); + if (!saved.ok || !saved.checkpoint) throw new Error("missing original checkpoint readback"); + if (!saved.checkpoint.acknowledged) + expect( + await run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + validate, + ), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + expect(mutations).toEqual(["commit", "ack"]); + expect(run.writeBoundaryFailure).toBeUndefined(); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: entry.id })).toMatchObject({ + ok: true, + checkpoint: { acknowledged: true, receipt: { inputId: "source-input-one" } }, + }); + } finally { + holdReadback = false; + await run.close(); + } + }, + ); + it("reports only safe checkpoint refusal fields and keeps successful requests silent", async () => { + const { key, ledger, id, gen, receipt } = await fixture(); + const logs: unknown[][] = []; + const log = vi.spyOn(console, "log").mockImplementation((...fields) => logs.push(fields)); + try { + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId })).toEqual({ + ok: true, + checkpoint: null, + }); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt })).toMatchObject({ ok: true }); + const refusals = () => logs.filter((fields) => fields[0] === "[runs/source-input/checkpoint] refused"); + expect(refusals()).toEqual([]); + for (const request of [ + { operation: "read", inputId: receipt.inputId }, + { operation: "commit", receipt }, + { operation: "ack", inputId: receipt.inputId, receiptHash: "b".repeat(64) }, + ]) + expect( + await post("/runs/source-input/checkpoint", { storeKey: key, runId: id, gen: "stale", request }), + ).toEqual({ status: 409, data: { ok: false, reason: "fenced" } }); + expect( + await post("/runs/source-input/checkpoint", { + storeKey: key, + runId: "missing-consumer", + gen, + request: { operation: "read", inputId: "PRIVATE_INPUT_IDENTIFIER" }, + }), + ).toEqual({ status: 409, data: { ok: false, reason: "unknown-run" } }); + expect(refusals()).toEqual([ + ["[runs/source-input/checkpoint] refused", { runId: id, operation: "read", reason: "fenced" }], + ["[runs/source-input/checkpoint] refused", { runId: id, operation: "commit", reason: "fenced" }], + ["[runs/source-input/checkpoint] refused", { runId: id, operation: "ack", reason: "fenced" }], + [ + "[runs/source-input/checkpoint] refused", + { runId: "missing-consumer", operation: "read", reason: "unknown-run" }, + ], + ]); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + } finally { + log.mockRestore(); + } + }); + + it("reports source-protection step refusal once without native or input details", async () => { + const { key, ledger, id, gen, step } = await fixture(); + const peek = await ledger.peekInbox(id, gen, 0); + if (!peek.ok) throw new Error("missing original inbox"); + const witness = peek.items[0]!.witness; + const observed = await runInDurableObject( + env.RUNS.get(env.RUNS.idFromName(key)), + async (owner: RunHistoryDO, state) => { + const logs: unknown[][] = []; + const warn = console.warn; + console.warn = (...fields: unknown[]) => { + logs.push(fields); + }; + try { + const success = await owner.recordStep(id, gen, { ...step, step: 1, inboxAcknowledgedRows: [witness] }); + const quiet = logs.length; + const raw = state.storage.sql + .exec<{ state_json: string }>("SELECT state_json FROM live_runs WHERE run_id=?", id) + .toArray()[0]!; + const saved = JSON.parse(raw.state_json); + saved.sourceInputIntents = { + version: 999, + native: "PRIVATE_NATIVE_SESSION", + input: "PRIVATE_INPUT_IDENTIFIER", + }; + state.storage.sql.exec("UPDATE live_runs SET state_json=? WHERE run_id=?", JSON.stringify(saved), id); + const refused = await owner.recordStep(id, gen, { ...step, step: 2, inboxAcknowledgedRows: [witness] }); + return { success, quiet, refused, logs }; + } finally { + console.warn = warn; + } + }, + ); + expect(observed).toEqual({ + success: { ok: true }, + quiet: 0, + refused: { ok: false, reason: "fenced" }, + logs: [["[runs/step] source input protection refused", { runId: id, ownerGen: gen, step: 2, acknowledged: 1 }]], + }); + const after = await ledger.peekInbox(id, gen, 0); + expect(after.ok && after.boundary.lastStep).toMatchObject({ step: 1, inboxConsumedSeq: 1 }); + expect(await unread(ledger, id)).toEqual([2, 3, 4]); + }); + + it("commits the original before ACK and keeps exact proof private through terminal retention", async () => { + const { key, ledger, store, id, gen, receipt, step, thread, session } = await fixture(); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + expect(committed).toEqual({ + ok: true, + checkpoint: { + receipt, + receiptHash: await sourceHash(sourceSnapshot(receipt)), + taskHash: await sourceHash(null), + acknowledged: false, + }, + }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + const read = await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId }); + expect(read).toEqual(committed); + if (!read.ok || !read.checkpoint) throw new Error("missing native checkpoint"); + const ack = { operation: "ack", inputId: receipt.inputId, receiptHash: read.checkpoint.receiptHash } as const; + expect(await ledger.sourceInputCheckpoint(id, gen, ack)).toMatchObject({ + ok: true, + checkpoint: { acknowledged: true }, + }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + expect(await ledger.step(id, gen, { ...step, step: 1 }, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + expect(await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 4 }, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 4]); + const live = (await ledger.listLive()).find((row) => row.runId === id)!; + const original = live.state.sourceInputIntents; + const terminal = { + ...record(id, thread), + agent: "orchestrator", + userId: "cli:alice", + channelId: "cli:main", + startedAt: live.startedAt, + finishedAt: live.startedAt + 1, + events: [], + eventCount: 0, + storedEventCount: 0, + }; + expect(await ledger.finish(id, gen, terminal)).toMatchObject({ ok: true, stored: true }); + expect((await store.get(id))?.sourceInputIntents).toEqual(original); + expect(await store.getSummary(id)).not.toHaveProperty("sourceInputIntents"); + expect(await store.put({ ...terminal, label: "later presentation" })).toMatchObject({ stored: true }); + expect((await store.get(id))?.sourceInputIntents).toEqual(original); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (owner: RunHistoryDO, state) => { + state.storage.sql.exec("UPDATE runs SET finished_at=1 WHERE run_id=?", id); + (owner as unknown as { trim(policy: Record, now: number, fence: undefined): unknown }).trim( + { retentionDays: 1, maxRuns: 0, maxBytes: 0 }, + Date.now(), + undefined, + ); + expect(state.storage.sql.exec("SELECT run_id FROM runs WHERE run_id=?", id).toArray()).toEqual([{ run_id: id }]); + }); + expect((await store.get(id))?.sourceInputIntents).toEqual(original); + }); + it("rolls back both receipt ACK and cursor when the SQLite step write fails", async () => { + const { key, ledger, id, gen, receipt } = await fixture(); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing native checkpoint"); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (_owner, state) => { + state.storage.sql.exec( + "CREATE TRIGGER refuse_native_ack BEFORE UPDATE OF json ON run_steps BEGIN SELECT RAISE(ABORT, 'fixture checkpoint failure'); END", + ); + }); + await expect( + ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).rejects.toThrow(); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (_owner, state) => { + state.storage.sql.exec("DROP TRIGGER refuse_native_ack"); + }); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId })).toEqual( + committed, + ); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + }); + it("settles the exact normal row through HTTP and never resurrects it after stale reports", async () => { + const { ledger, id, gen, receipt, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + const witness = observed.items[0]!.witness; + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing checkpoint"); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).toMatchObject({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + const confirmed = { + ...step, + step: 1, + inboxConsumedSeq: 4, + inboxDeferredSeqs: [3, 4], + inboxAcknowledgedRows: [witness], + }; + expect(await ledger.step(id, gen, confirmed, [], session)).toEqual({ ok: true }); + expect(await ledger.step(id, gen, confirmed, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([3, 4]); + expect(await ledger.step(id, gen, { ...confirmed, inboxAcknowledgedRows: [] }, [], session)).toEqual({ + ok: false, + reason: "fenced", + }); + expect( + await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 0, inboxDeferredSeqs: [1] }, [], session), + ).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([3, 4]); + expect( + await ledger.step( + id, + gen, + { ...step, step: 3, inboxAcknowledgedRows: [observed.items[1]!.witness] }, + [], + session, + ), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([3, 4]); + }); + + it("keeps the normal row unread when its SQLite step insert fails", async () => { + const { key, ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (_owner, state) => { + state.storage.sql.exec( + "CREATE TRIGGER refuse_normal_ack BEFORE INSERT ON run_steps BEGIN SELECT RAISE(ABORT, 'fixture normal confirmation failure'); END", + ); + }); + await expect( + ledger.step(id, gen, { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, [], session), + ).rejects.toThrow(); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (_owner, state) => { + state.storage.sql.exec("DROP TRIGGER refuse_normal_ack"); + }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + const after = await ledger.peekInbox(id, gen, 0); + expect(after.ok && after.boundary.lastStep).toMatchObject({ step: 0, inboxConsumedSeq: 0 }); + expect(after.ok && after.boundary.lastStep).not.toHaveProperty("inboxAcknowledgedRows"); + }); + + it("refuses a changed normal row while retaining the original confirmation identity", async () => { + const { key, ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + await runInDurableObject(env.RUNS.get(env.RUNS.idFromName(key)), (_owner, state) => { + state.storage.sql.exec( + "UPDATE run_inbox SET json=? WHERE run_id=? AND seq=1", + JSON.stringify({ text: "replacement normal row" }), + id, + ); + }); + expect( + await ledger.step( + id, + gen, + { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, + [], + session, + ), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + }); + it("fences old owners and retains the original receipt and unread rows after reclaim", async () => { + const { ledger, id, gen, receipt } = await fixture(); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + expect(committed).toMatchObject({ ok: true, checkpoint: { acknowledged: false } }); + expect(await ledger.handoff(gen, [id])).toEqual({ marked: [id] }); + expect((await ledger.reclaim("g2", Date.now() + 20000, 10000))[0]?.row.ownerGen).toBe("g2"); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId })).toEqual({ + ok: false, + reason: "fenced", + }); + expect(await ledger.sourceInputCheckpoint(id, "g2", { operation: "read", inputId: receipt.inputId })).toEqual( + committed, + ); + expect(await unread(ledger, id, "g2")).toEqual([1, 2, 3, 4]); + }); +}); diff --git a/deploy/cloudflare-memory/worker.ts b/deploy/cloudflare-memory/worker.ts index 6e374ceb1..ecab0e05c 100644 --- a/deploy/cloudflare-memory/worker.ts +++ b/deploy/cloudflare-memory/worker.ts @@ -4,6 +4,18 @@ import { sourceObligationJobOf, retainSourceObligationRangeHolders, } from "../../src/core/runLedger/sourceObligations.js"; +import { + inboxAcknowledgedRowsOf, + prepareInboxAcknowledgments, + inboxAcknowledgmentRowsUnchanged, +} from "../../src/core/runLedger/inboxAcknowledgments.js"; +import { + prepareSourceInputCheckpoint, + protectSourceInputStep, + sourceInputCheckpointRequestOf, + type SourceInputCheckpointRequest, + type SourceInputCheckpointResult, +} from "../../src/core/runLedger/sourceInputIntent.js"; import { observeWorkerRequest } from "../../src/core/trace/workerCorrelation.js"; import { bindingFetch, installHttpTransport } from "../../src/core/trace/httpTransport.js"; import { WriteReceipts } from "./writeReceipts.js"; @@ -76,6 +88,7 @@ import { } from "../../src/core/runLedger/inboxDelivery.ts"; import { EXECUTION_PROTOCOL_HEADER, NATIVE_REVIEW_STOP_HEADER } from "../../src/core/runLedger/types.js"; import { + sourceSnapshot, sourceRelevanceRequestOf, type SourceRelevanceSaveResult, isSourceEventKey, @@ -2717,6 +2730,7 @@ export class RunHistoryDO extends DurableObject { | "readContextCheckpoint" | "normalizeContextOrigins" | "setState" + | "sourceInputCheckpoint" | "constructor" | "replaceInstance" | "withRangePins" @@ -2832,7 +2846,8 @@ export class RunHistoryDO extends DurableObject { /** A source refusal rejects after gate release, without resetting sibling runs. */ private async withInputGate( - operation: "archiveCheckpoint" | "readContextCheckpoint" | "normalizeContextOrigins" | "setState", + operation: + "archiveCheckpoint" | "readContextCheckpoint" | "normalizeContextOrigins" | "setState" | "sourceInputCheckpoint", runId: string, action: (observe: ObserveCheckpointStage) => Promise, correlation?: CheckpointGateCorrelation, @@ -8793,18 +8808,78 @@ export class RunHistoryDO extends DurableObject { /** The step record (item 31), written by the client AFTER the transcript turns. Fenced. */ async recordStep(runId: string, gen: string, record: StepRecord): Promise { if (!Number.isSafeInteger(record.step) || record.step < 0) throw new Error("invalid public step key"); - let out: FenceResult = { ok: true }; + const normal = + record.inboxAcknowledgedRows === undefined ? undefined : inboxAcknowledgedRowsOf(record.inboxAcknowledgedRows); + if (record.inboxAcknowledgedRows !== undefined && !normal) return { ok: false, reason: "fenced" }; + record = { ...record, ...(normal ? { inboxAcknowledgedRows: normal } : {}) }; + const capture = () => ({ + row: this.liveRow(runId), + archive: this.inboxSegmentArchive(runId), + base: workspaceDurabilityArchiveOf(this.allocationArchive(runId))?.promotionStepBase ?? 0, + prior: this.sql + .exec<{ json: string }>( + "SELECT json FROM run_steps WHERE run_id=? AND step>=0 ORDER BY step DESC LIMIT 1", + runId, + ) + .toArray()[0]?.json, + }); + const initial = capture(); + const fence = checkFence(initial.row, gen); + if (!fence.ok) return fence; + if (!initial.row) return { ok: false, reason: "unknown-run" }; + if (normal?.length && initial.row.phase !== "live") return { ok: false, reason: "fenced" }; + const index = initial.base + record.step; + const existingJson = this.sql + .exec<{ json: string }>("SELECT json FROM run_steps WHERE run_id=? AND step=?", runId, index) + .toArray()[0]?.json; + const existing = existingJson ? (parseStoredJson(existingJson) as StepRecord) : undefined; + if (existing?.inboxAcknowledgedRows?.length) + return JSON.stringify(sourceSnapshot(existing)) === JSON.stringify(sourceSnapshot(record)) + ? { ok: true } + : { ok: false, reason: "fenced" }; + const prior = initial.prior ? (parseStoredJson(initial.prior) as StepRecord) : undefined; + if (normal?.length && prior && record.step <= prior.step) return { ok: false, reason: "fenced" }; + const floor = inboxSegmentFloor(initial.archive, initial.row); + if (floor === undefined) throw new Error("retained inbox segment boundary is unreadable"); + const readInbox = () => + this.sql + .exec<{ seq: number; json: string }>( + "SELECT seq,json FROM run_inbox WHERE run_id=? AND seq>? ORDER BY seq", + runId, + floor, + ) + .toArray() + .map((item) => ({ seq: item.seq, message: parseStoredJson(item.json) as Record })); + const before = JSON.stringify(initial); + const prepared = normal?.length + ? await prepareInboxAcknowledgments(runId, record, readInbox()) + : { witnesses: [], rows: [] }; + let out: FenceResult = { ok: false, reason: "fenced" }; this.ctx.storage.transactionSync(() => { - out = checkFence(this.liveRow(runId), gen); - if (!out.ok) return; - if (inboxSegmentFloor(this.inboxSegmentArchive(runId), this.liveRow(runId)!) === undefined) - throw new Error("retained inbox segment boundary is unreadable"); + const currentInbox = readInbox(); + if ( + !prepared || + before !== JSON.stringify(capture()) || + !inboxAcknowledgmentRowsUnchanged(prepared.rows, (seq) => currentInbox.find((item) => item.seq === seq)) + ) + return; + const protectedStep = protectSourceInputStep(initial.row!.state, record, currentInbox, prior, prepared.witnesses); + if (!protectedStep) { + console.warn("[runs/step] source input protection refused", { + runId, + ownerGen: gen, + step: record.step, + acknowledged: normal?.length ?? 0, + }); + return; + } this.sql.exec( - `INSERT OR REPLACE INTO run_steps (run_id, step, json) VALUES (?, ?, ?)`, + "INSERT OR REPLACE INTO run_steps (run_id, step, json) VALUES (?, ?, ?)", runId, - (workspaceDurabilityArchiveOf(this.allocationArchive(runId))?.promotionStepBase ?? 0) + record.step, - JSON.stringify(record), + index, + JSON.stringify(protectedStep), ); + out = { ok: true }; }); return out; } @@ -9008,6 +9083,67 @@ export class RunHistoryDO extends DurableObject { } } + async sourceInputCheckpoint( + runId: string, + gen: string, + request: SourceInputCheckpointRequest, + ): Promise { + const parsed = sourceInputCheckpointRequestOf(request); + if (!parsed) return { ok: false, reason: "fenced" }; + return this.withInputGate("sourceInputCheckpoint", runId, async () => { + const capture = () => ({ + row: this.liveRow(runId), + archive: this.inboxSegmentArchive(runId), + step: this.sql + .exec<{ step: number; json: string }>( + "SELECT step,json FROM run_steps WHERE run_id=? AND step>=0 ORDER BY step DESC LIMIT 1", + runId, + ) + .toArray()[0], + inbox: this.sql + .exec<{ seq: number; json: string }>("SELECT seq,json FROM run_inbox WHERE run_id=? ORDER BY seq", runId) + .toArray(), + }); + const initial = capture(); + const fence = checkFence(initial.row, gen); + if (!fence.ok) return fence; + if (!initial.row) return { ok: false, reason: "unknown-run" }; + if (parsed.operation !== "read" && this.promotionHeld(runId, gen)) return { ok: false, reason: "fenced" }; + const floor = inboxSegmentFloor(initial.archive, initial.row); + if ( + floor === undefined || + initial.inbox.length > RUN_EVENTS_MAX_PAGE || + initial.inbox.reduce((size, item) => size + 3 * item.json.length, 0) > MAX_RECORD_BYTES + ) + return { ok: false, reason: "fenced" }; + const before = JSON.stringify(initial); + const prepared = await prepareSourceInputCheckpoint( + initial.row, + parsed, + initial.inbox + .filter((item) => item.seq > floor) + .map((item) => ({ seq: item.seq, message: parseStoredJson(item.json) as Record })), + initial.step ? (parseStoredJson(initial.step.json) as StepRecord) : undefined, + ); + let result: SourceInputCheckpointResult = { ok: false, reason: "fenced" }; + this.ctx.storage.transactionSync(() => { + if (!prepared || before !== JSON.stringify(capture())) return; + if (parsed.operation !== "read") { + this.sql.exec("UPDATE live_runs SET state_json=? WHERE run_id=?", JSON.stringify(prepared.state), runId); + if (prepared.step && initial.step) + this.sql.exec( + "UPDATE run_steps SET json=? WHERE run_id=? AND step=?", + JSON.stringify(prepared.step), + runId, + initial.step.step, + ); + } + result = { ok: true, checkpoint: prepared.checkpoint }; + }); + return result; + }); + } + async setState( runId: string, gen: string, @@ -15014,6 +15150,7 @@ const LEDGER_ROUTES = new Set([ "/runs/live-state", "/runs/step", "/runs/state", + "/runs/source-input/checkpoint", "/runs/inbox", "/runs/inbox/deliver", "/runs/inbox/read", @@ -15431,6 +15568,8 @@ function parseStep(v: unknown): Validated { !s.inboxDeferredSeqs.every((seq) => typeof seq === "number" && Number.isInteger(seq) && seq > 0)) ) return invalid("record.inboxDeferredSeqs must be an array of positive integers"); + if (s.inboxAcknowledgedRows !== undefined && !inboxAcknowledgedRowsOf(s.inboxAcknowledgedRows)) + return invalid("record.inboxAcknowledgedRows must contain exact row witnesses"); if (s.publicationAnswer !== undefined && typeof s.publicationAnswer !== "string") return invalid("record.publicationAnswer must be a string"); if (!Array.isArray(s.inFlight)) return invalid("record.inFlight must be an array"); @@ -16928,12 +17067,27 @@ async function handleLedger( throw error; } } + if (pathname === "/runs/source-input/checkpoint") { + const request = sourceInputCheckpointRequestOf(b.request); + if (!request) return json({ error: "invalid source input checkpoint request" }, 400); + const result = await stub.sourceInputCheckpoint(runId.value, g.value, request); + if (!result.ok) + console.log("[runs/source-input/checkpoint] refused", { + runId: runId.value, + operation: request.operation, + reason: result.reason, + }); + return json(result, result.ok ? 200 : 409); + } if (pathname === "/runs/step") { const record = parseStep(b.record); if (!record.ok) return json({ error: record.error }, 400); - return fenced( - await replayableRpc("step-rpc", (fresh) => fresh.recordStep(runId.value, g.value, record.value)), + const result = await replayableRpc("step-rpc", (fresh) => + fresh.recordStep(runId.value, g.value, record.value), ); + return result.ok && record.value.inboxAcknowledgedRows?.length + ? json({ ...result, inboxAcknowledgedRows: inboxAcknowledgedRowsOf(record.value.inboxAcknowledgedRows) }) + : fenced(result); } if (pathname === "/runs/state") { if (typeof b.state !== "object" || b.state === null) return json({ error: "state must be an object" }, 400); diff --git a/docs/reference/specs/harness-pi.md b/docs/reference/specs/harness-pi.md index 725f3981e..ac9e7d400 100644 --- a/docs/reference/specs/harness-pi.md +++ b/docs/reference/specs/harness-pi.md @@ -334,6 +334,9 @@ No production caller enables this command. Canonical source admission, current a ## Native source input file readback +- **Code**: `src/core/harness/pi/sourceInputCheckpoint.ts` +- **Tests**: `src/core/runLedger/writeThrough.test.ts` + The disabled host path can read one begun original from its exact Pi session file. The file must be complete, within the existing session-log byte bound, and use the supported native session format. Duplicate native entry IDs, broken parent links and duplicate source input identities hold the read. A command response or live entry list is not file proof. The readback receipt retains the host input ID, the complete original intent digest, native session and entry identities, and the exact entry digest. The stored metadata and rendered text must match the original input. This is private readback evidence. It grants no submission, canonical checkpoint, inbox acknowledgment or retention release. No production reader or delivery caller is enabled by this component. @@ -346,3 +349,12 @@ The readback receipt retains the host input ID, the complete original intent dig | During native streaming, a handled command produces no file receipt. A confirmed process kill and restart still produce no receipt for the lost original. Settled originals retain exact file receipts through native restart and compaction/restart without resubmission. | `[unit]` `src/core/harness/pi/testing/sourceInput.native.test.ts::native Pi source input persistence::distinguishes a handled command from saved input through crash, restart and compaction` | | The installed Pi process and host extension produce native file entries that the same reader binds to each original typed input. | `[unit]` `src/core/harness/pi/sourceInputCommand.test.ts::host source-input command::carries the host command through the real Pi RPC process into the original native file` | | Owning executor read, current access, canonical checkpoint commit and exact inbox witness acknowledgment form one integrated path through restart and uncertain writes. | `[gap]` Source input integration; component file readback does not close this gate. | + +### Canonical settlement of an existing native entry + +The host can pass an original file observation to `checkpointPiSourceInput`. It maps the native file and header identities to the shared admission receipt. The tracked writer checks current cumulative access, commits once, reads the canonical receipt, and acknowledges only its exact inbox witness. A lost mutation response requires exact readback; a missing first read retains the original operation because it can still commit later. This helper sends no native command, starts no model turn and releases no source retention pins. + +| Criterion | Proof | +| --- | --- | +| An installed native session entry reaches canonical receipt readback and exact ACK; a copied path holds, and reopening the original does not submit new native input. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::settles the original installed Pi session entry through canonical readback and exact ACK` | +| The production executor reader, native submission owner, recovery path and source-job settlement remain connected under current access and original custody. | `[gap]` Runtime delivery callers remain disabled; this local host settlement proof does not close production or staging acceptance. | diff --git a/docs/reference/specs/orchestration-plane.md b/docs/reference/specs/orchestration-plane.md index 13149359b..f3661ab42 100644 --- a/docs/reference/specs/orchestration-plane.md +++ b/docs/reference/specs/orchestration-plane.md @@ -77,7 +77,7 @@ Switchboard can say **what is happening**: every live and recently ended run, ev | The client half: the write-through acks received effects `deferred` when nothing is wired, runs an `admit` through the wired executor — a draining generation defers it — and the outcome post fires and forgets: a failure is one warning | `[unit]` `src/core/runLedger/writeThrough.test.ts::events, state, heartbeat::plane effects on a heartbeat answer are each acked deferred — this generation executes none yet (orchestration-plane item 7)`, `::an admit effect runs through the wired executor and its word is the ack; a draining generation defers it instead (record 0064)`, `::planeOutcome fires the post and swallows a failure with one warning — the dispatch never waits on the plane (orchestration-plane item 8)` | | The admission stage under `plane.admission: on`: two asks a second apart answer `admitted` then `queued` at position 1; the claim promotes the reservation; the seal admits the queued run with its admit effect and its attaching row under the plane's id; a withdrawn row is never admitted; `deploy.landed` flips `deploy_settled`; a sealed run's open effects are dropped | `[unit]` `deploy/cloudflare-memory/runLedger.test.ts::the plane's admission stage — /plane/admit, reservations, the seal's walk (orchestration-plane; record 0064)::two asks a second apart on one thread: the first is admitted with a reservation, the second queued at position 1; the first's claim promotes the reservation; the seal admits the queued run with its attaching row`, `::a duplicate admit decision after a roll keeps the effect's first offer and the attaching row (INSERT OR IGNORE)`, `::runs stop on a queued id withdraws it: the row goes withdrawn, a second withdraw answers false, and the seal admits nothing`, `::a pending deploy queues an ask on deploy_settled and deploy.landed flips it, admitting the queued run`, `::effects for a sealed run are dropped at the seal: an admitted-then-finished run's open admit goes with its finish`, `::validates: a missing threadKey, requester or request is 400; a malformed withdraw run id is 400` | | The bot's door under `plane.admission: on`: a queued ask holds nothing — the slot released, no row reserved or adopted, no heartbeat — and every verbosity preserves the actionable position and withdraw lever because no run card exists; an admitted ask proceeds; `off`, a resume and a restart never ask | `[unit]` `src/core/dispatch/admission.test.ts::admit — the plane's admission ask under plane.admission: on (record 0064, "The queue")::an ask the plane queues holds nothing and $level preserves its actionable position and withdrawal command`, `::an admitted ask proceeds — asked once, the reservation is the object's to promote`, `::off — the default — never asks; a resume and a restart re-enter decided work and never ask either` | -| The push transport: the state Worker POSTs committed effects to the bot's `/plane/effects`, which runs each through the SAME executor the heartbeat answers use and acks its word; draining or unwired defers; a pushed steer atomically verifies the open effect, fences authoritative ownership and renews its lease before registry delivery, so reclaim cannot cross the local wake; a wrong bearer or a malformed body runs nothing; a push that fails leaves the effect riding the next heartbeat answer | `[unit]` `src/channels/planeEffects.test.ts::POST /plane/effects — the push transport (record 0064)::runs each pushed effect through the wired executor and acks its word on the object`, `::delivers a pushed steer through the wired executor and acks only its outcome; probe effects remain for the heartbeat executor`, `::the stale generation defers a pushed steer, then the durable owner heartbeat delivers and acks it`, `::renews the durable owner fence before registry delivery, so reclaim cannot cross the local wake`, `::rechecks drain after the durable fence returns, so handoff cannot wake stale registry state`, `::a draining generation defers, and no wired executor defers too — the offer stays for a bot that can run it`, `::an effect whose execution or ack throws is one warning and stays offered — it rides the next heartbeat answer; the rest of the push still acks`, `::refuses a wrong or missing bearer, and everything when the token is unset (fail closed); refuses non-POST`, `::a non-JSON body, a body without an effects array and a malformed effect are 400 — nothing runs`, `deploy/cloudflare-memory/runLedger.test.ts::the plane's admission stage — /plane/admit, reservations, the seal's walk (orchestration-plane; record 0064)::a push that fails leaves the effect on the next heartbeat answer: the bot answered 404, nothing was acked, and the offer rides the heartbeat` | +| The push transport: the state Worker POSTs committed effects to the bot's `/plane/effects`, which runs each through the SAME executor the heartbeat answers use and acks its word; draining or unwired defers; a pushed steer atomically verifies the open effect, fences authoritative ownership and renews its lease before registry delivery, so reclaim cannot cross the local wake; provider recovery preserves the exact stored message for its witness, renders display text separately, and rechecks drain after receipt hashing with no asynchronous gap before the local inbox put; a wrong bearer or a malformed body runs nothing; a push that fails leaves the effect riding the next heartbeat answer | `[unit]` `src/channels/planeEffects.test.ts::POST /plane/effects — the push transport (record 0064)::runs each pushed effect through the wired executor and acks its word on the object`, `::delivers a pushed steer through the wired executor and acks only its outcome; probe effects remain for the heartbeat executor`, `::the stale generation defers a pushed steer, then the durable owner heartbeat delivers and acks it`, `::renews the durable owner fence before registry delivery, so reclaim cannot cross the local wake`, `::rechecks drain after the durable fence returns, so handoff cannot wake stale registry state`, `::a draining generation defers, and no wired executor defers too — the offer stays for a bot that can run it`, `::an effect whose execution or ack throws is one warning and stays offered — it rides the next heartbeat answer; the rest of the push still acks`, `::refuses a wrong or missing bearer, and everything when the token is unset (fail closed); refuses non-POST`, `::a non-JSON body, a body without an effects array and a malformed effect are 400 — nothing runs`, `deploy/cloudflare-memory/runLedger.test.ts::the plane's admission stage — /plane/admit, reservations, the seal's walk (orchestration-plane; record 0064)::a push that fails leaves the effect on the next heartbeat answer: the bot answered 404, nothing was acked, and the offer rides the heartbeat`, `src/channels/planeEffects.test.ts::exact provider recovery delivery::*` | | Provider down persists its closed cause on the level row; provider recovery live delivery: provider-up atomically writes the durable row and sequence-bearing offer; the Worker pushes it, a failed transaction or push loses nothing, an atomic effect/owner fence renews the lease before registry delivery and only an owner-fenced ack closes it, duplicate paths reissue once, and a sealed run emits none | `[unit]` `src/core/plane/decide.test.ts::decide — the checkpoint steers and the provider condition (record 0064)::the provider's next up report — from any run — writes each held turn's durable row and typed live steer together, then deletes the park; a repeat up steers nothing`, `::a provider up after the parked run is no longer live deletes the stale park and offers no steer`, `deploy/cloudflare-memory/runLedger.test.ts::the plane's checkpoint steers and the provider condition — the heartbeat body, /plane/park, /plane/level provider (record 0064)::a provider down and parked live run recover atomically as one durable row and one pushed offered steer; repeat up writes nothing`, `::fences a pushed steer and renews its owner's lease atomically before registry delivery`, `::a stale generation cannot close a steer offer after reclaim; the durable owner heartbeat receives and closes it`, `::a failed provider-up transaction writes neither the durable row nor its steer effect`, `::a failed live push leaves both the durable row and steer offer for an owner heartbeat; sealing first removes the park and produces no steer`, `src/channels/planeEffects.test.ts::POST /plane/effects — the push transport (record 0064)::the stale generation defers a pushed steer, then the durable owner heartbeat delivers and acks it`, `src/core/runLedger/writeThrough.test.ts::events, state, heartbeat::an owner heartbeat delivers a live steer once; duplicate heartbeat and reclaim copies of its durable sequence are skipped`, `src/core/harness/pi/harness.test.ts::runPiHarness — a run on pi from the first file to the answer::a provider-up effect pushed into the owning live inbox reissues the parked turn immediately and acks done before any heartbeat or reclaim` | | A queued id has a page and a lever: `getRun` answers the stored ask's view (the requester, the position, the waiting words — the queued reply's own) and authorizes it against the request's durably stamped channel, never one re-derived from an ambiguous thread key; only a legacy row without that stamp falls back to the thread key's channel. The run page heads with those facts, and `runs stop` on the id withdraws the waiting row for either mode; a row the queue holds not-waiting is a conflict | `[unit]` `src/core/runsService.test.ts::RunsService — a queued ask on the plane (record 0064)::authorizes a queued run with its stamped request channel, not a channel re-derived from the thread key`, `::getRun answers a queued id's view: the requester, the thread's channel, the position and the waiting words — so the id a person was told has a page` (legacy row without `request.channelId`), `::stopRun withdraws a queued id — the reply's runs stop lever — for either mode; the queue knows the id but not as waiting is a conflict`, `web/src/pages/runPage.test.ts::RunPage — history mode::a queued ask's page heads with the position and the waiting words, amber` | | The deploy runner posts the window: `deploy all` with a bot step posts `pending` before the first Worker uploads and `landed` after the run — landed or failed alike — so `deploy_settled` flips end-to-end; no state Worker, a missing bearer, an older Worker or an unreachable one is one line each and never fails the deploy | `[unit]` `src/deploy/planeDeploy.test.ts::postPlaneDeploy — the /plane/deploy post from the deploy runner::posts pending and landed to the state Worker's /plane/deploy with the bearer, the store key and the commit; landed logs how many asks were admitted`, `::no state Worker posts nothing; a missing bearer is one line and nothing is sent`, `::an older state Worker (404) and an unreachable one (throw) are one line each — the deploy is never failed by the plane` | diff --git a/docs/reference/specs/run-history.md b/docs/reference/specs/run-history.md index abac6e9e4..a71db953d 100644 --- a/docs/reference/specs/run-history.md +++ b/docs/reference/specs/run-history.md @@ -17,13 +17,13 @@ Shared conversation text, negative custody checkpoints, original native/workspac - **Code**: `src/core/requestFailure.ts`, `src/core/exceptionDiagnostic.ts`, `src/core/storageRequestContext.ts`, `src/core/storageTransport.ts` - **Code**: `src/core/organizationResumeHold.ts` (fenced original-source hold and same-generation sweep retry), `src/core/runLedger/organizationResumeHold.ts` (safe reason and ordered state marker) -- **Tests**: `src/core/requestFailure.test.ts`, `deploy/cloudflare/containerStartContract.test.ts`, `src/core/storageRequestContext.test.ts`, `src/core/reviewFeedbackWorker.test.ts` +- **Tests**: `src/core/runLedger/sourceInputCheckpoint.test.ts`, `src/core/requestFailure.test.ts`, `deploy/cloudflare/containerStartContract.test.ts`, `src/core/storageRequestContext.test.ts`, `src/core/reviewFeedbackWorker.test.ts` - **Code**: `src/channels/githubActivityAccess.ts` (current GitHub source identity and requester read policy); `src/core/runLedger/sourceEvidence.ts` - **Tests**: `src/core/runLedger/sourceEvidence.test.ts` - **Code**: `src/core/references/sourceInputReference.ts`, `src/core/references/sourceInputProof.ts`, `src/core/references/sourceTaskSnapshot.ts`, `src/core/testing/sourceInputs.ts` (source-input identity, canonical data checks and synthetic test fixture) - **Tests**: `src/core/coordinator/managedPrSourceContract.test.ts`, `src/core/references/sourceInputProof.test.ts`, `src/core/references/sourceTaskSnapshot.test.ts` -- **Code**: `src/core/runLedger/sourceInputIntent.ts` (private terminal input retention) +- **Code**: `src/core/runLedger/sourceInputIntent.ts` (private terminal input retention); `src/core/runLedger/inboxAcknowledgments.ts` (exact normal-row settlement) - **Tests**: `src/core/runLedger/sourceInputArchive.test.ts` - **Tests**: `src/core/runLedger/inboxDelivery.test.ts`, `src/core/runLedger/sourceRelevance.test.ts` @@ -1156,6 +1156,23 @@ An input archive refusal reports one warning from its owning boundary with the c | Actual SQLite finish, private readback, rewrite and zero-budget trimming preserve prepared and begun originals and unacknowledged rows; summaries omit the metadata | `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::source-input context readers in SQLite::finishes or settles an unresolved %s input privately and preserves it through trimming` | | Terminal recovery copies the original frame and refuses an unsupported version; ordinary run views omit native input metadata | `[unit]` `src/core/dispatch/record.test.ts::durable source archive assembly::keeps the original task on terminal recovery and refuses corrupt task proof`; `src/core/runsService.test.ts::RunsService.getRun::keeps original task proof out of ordinary persisted views` | +The ledger exposes a separate native-input checkpoint transaction. A trusted harness adapter supplies an exact native admission receipt for a begun original. Commit saves it in a private version-2 input frame without advancing the inbox. The caller reads that canonical checkpoint, then supplies its receipt hash for exact acknowledgment. The store changes the saved acknowledgment and the exact row cursor in one transaction. It retains every other unread row and preserves earlier canonical deferrals. Ordinary step reports cannot consume source rows without exact proof or resurrect acknowledged source rows. + +The first acknowledgment requires the same current native session, launch ordinal, live destination, known retained context and saved task digest. A read remains historical evidence when those bindings change. A generation change alone preserves the original receipt and input coordinates. Missing support, a refused write or an unknown reply leaves the original obligation held. Native input is not resubmitted by this API. Source producers and delivery callers remain disabled. Native acknowledgment does not release source roots or recipient obligations. Once a source checkpoint exists, ordinary reports cannot drop earlier canonical deferred rows. A positive ordinary-input or control receipt can attach the original non-source row witnesses as `StepRecord.inboxAcknowledgedRows`. The store verifies the exact raw row bytes and current live owner, then clears only those deferrals in the same step write. It preserves other unread rows and never reopens an already consumed normal row because of a stale report. Source-evidence rows of every version must use their source receipt contract. The committed normal witnesses remain in the step for original unknown-write readback. Missing HTTP support, a changed original or a refused write keeps the obligation held. Runtime capture and callback integration remain separate qualification gates. + +The checkpoint HTTP boundary reports one refusal line with the canonical run ID, closed operation and refusal reason. A step refused by the source-input protection reducer reports one warning with the run ID, owner generation, public step and bounded acknowledgment count. Success stays silent. These signals contain no input ID, receipt hash, native locator, source payload or context. + +| Criterion | Proof | +| --- | --- | +| Receipt commit leaves the original unread; exact ACK consumes only its witness and stale reports retain unrelated canonical deferrals | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::commits proof before exact ACK and preserves unrelated rows through later steps`; `::retains unrelated canonical deferrals when a stale report drops them`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::commits the original before ACK and keeps exact proof private through terminal retention` | +| A positive original normal-row witness settles only that row, preserves other deferrals and cannot be erased or resurrected by a stale report | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::settles only a confirmed normal row and never resurrects it from a stale report`; `::uses positive normal proof without consuming another row below the proposed cursor`; `::keeps normal-only confirmation monotonic through later reports with no new proof`; `::preserves a committed normal receipt when a later exact source ACK changes the cursor`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::settles the exact normal row through HTTP and never resurrects it after stale reports` | +| Changed or false normal witnesses, source-row substitution and missing HTTP acknowledgment cannot settle a row; a failed SQLite insert leaves the prior boundary intact | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::refuses false normal-row proof and cannot settle source evidence through it`; `::holds changed original rows and ownership races during normal confirmation`; `::compares the original row and owner again after an asynchronous digest`; `::refuses a legacy success reply without positive normal-row acknowledgment`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::keeps the normal row unread when its SQLite step insert fails`; `::refuses a changed normal row while retaining the original confirmation identity` | +| Checkpoint refusal identifies the closed operation and reason; step protection refusal reports safe owner and count fields once, while successful writes remain silent and refusal preserves unread rows | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::reports only safe step protection refusal fields and leaves the prior boundary intact`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::reports only safe checkpoint refusal fields and keeps successful requests silent`; `::reports source-protection step refusal once without native or input details` | +| Ordinary cursors and state writes cannot bypass source proof, mint a checkpoint or erase an acknowledged one | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::holds source rows when an ordinary high-water step supplies no receipt`; `::keeps canonical proof private and rejects ordinary mint, erase or ACK` | +| Native identity aliases, changed digests and foreign owners refuse; original readback survives reclaim without replacement | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::refuses mismatched native identity, original digest, owner and ACK hashes`; `::reconciles the same original after reclaim and never aliases two native entries`; `::refuses a checkpoint when ownership changes while its digest is pending`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::fences old owners and retains the original receipt and unread rows after reclaim` | +| A changed current native session, launch ordinal, ending or task holds the first ACK while preserving the historical receipt | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::holds ACK when the current %s changes after commit` | +| Unknown commit and ACK replies read the original result without repeating a mutation; a real SQLite failure rolls back both ACK and cursor | `[unit]` `src/core/runLedger/sourceInputCheckpoint.test.ts::canonical source input checkpoints::reads the original after a lost %s reply without repeating a mutation`; `[worker]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::rolls back both receipt ACK and cursor when the SQLite step write fails` | + The tracked writer's `beginSourceInput` checks an existing prepared intent through the shared context-access validator. It validates the whole context with the new source reference, then uses the existing source writer to retain that dependency in both the session and live state. It checks the saved cumulative context before marking the exact original input begun and again after the state acknowledgment. A final owner-fenced readback must retain the same intent, context, native session and row witness. A changed context or native session, missing row, refused access or unknown state acknowledgment holds the input. Begun inputs cannot be begun again, including after a lost reply. Validator errors retain their original cause. This method sends no native input and provides no native admission receipt or inbox acknowledgment. No production caller uses it. The shared current-access validator and complete store row-binding path must be installed and qualified before a sender can use this method. The final readback is a consistency check; the shared provider guard must still recheck access at model admission. @@ -1169,6 +1186,25 @@ Each held return emits one `source.input.held` diagnostic with the canonical run | A lost begun-state reply stays held whether or not storage committed it; another call does not repeat the original write | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::holds a lost begun reply without repeating the original: committed=%s` | | Held inputs report one safe reason; a successful begin stays silent and diagnostic failure cannot authorize an input | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::reports one safe hold reason and stays silent on a successful begin` | +### Tracked native checkpoint operations + +`LedgerRun.sourceInputCheckpoint` serializes explicit commit, read and acknowledgment operations with the tracked source and state boundaries. A read can check route support before input begins. Mutations require current cumulative source access after their prerequisite reads. A successful mutation must retain its private receipt locally and prove canonical readback before it returns success. Later ordinary writes carry that version-2 frame. Beginning another original preserves earlier checkpoints. + +An uncertain mutation retains its original request witness in the existing write-boundary journal. A null first read does not clear it. Ordinary writes, another mutation and finishing stay held until exact canonical readback proves the original result. The host does not repeat the mutation or submit native input. Source-aware step writes first bind the store's exact protected cursor and deferred-row projection, so a lost reply can be reconciled without weakening equality or replaying the step. Runtime delivery and independent recipient settlement remain disabled and unqualified. + +Ordinary follow-ups carry the exact original stored-row witness captured before native delivery. In source-aware runs, positive native acceptance adds that witness to the next step. Normal-only runs retain the deployed cursor protocol until an exact canonical marker is present. The host clears the retained delta only after the step succeeds or exact canonical readback proves it. The canonical mask stays monotonic: a delayed lower cursor cannot offer a consumed row again. Source-evidence rows cannot use this normal-row path. Typed provider controls require their successful native response; a displayed echo alone does not settle them. This does not enable source delivery or settle recipient obligations. + +| Criterion | Proof | +| --- | --- | +| Reader preflight neither begins nor acknowledges the original; commit, read and exact ACK retain proof through later host state. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::checks checkpoint reader capability without beginning or acknowledging the input`; `::reads a native checkpoint before exact ACK and preserves it in later host state` | +| Revocation before mutation or during the final ACK prerequisite read leaves the original unread. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::holds native checkpoint changes after source access is revoked`; `::checks access after the final ACK prerequisite read: revoked=%s` | +| Lost commit or ACK replies reconcile only by exact readback; a still-running mutation remains held through null reads and ordinary writes. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::reconciles a lost host %s reply without repeating its mutation`; `::retains a still-running checkpoint mutation through a null read and later ordinary writes` | +| A saved Pi JSONL fixture crosses the host, Worker client and actual SQLite. Lost commit or ACK responses hold later state writes until exact readback, with one mutation of each kind and unrelated inbox rows still unread. | `[unit]` `deploy/cloudflare-memory/runLedger.test.ts::canonical native input checkpoint in SQLite::reconciles a saved Pi fixture through the host and SQLite after a lost %s response without repeating it` | +| Provider-recovery push parsing retains exact stored row bytes for normal acknowledgment; canonical display text stays separate. Push and heartbeat defer if drain begins during receipt hashing, then check the current run and admission slot without another asynchronous gap. | `[unit]` `src/channels/planeEffects.test.ts::exact provider recovery delivery::*` | +| A landed receipt survives a later access hold and beginning another input; a lost protected-step reply reconciles without replay. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::retains a landed checkpoint before returning a later access hold`; `::begins another original without dropping the earlier canonical checkpoint`; `::reconciles the exact protected step after an ACK and a lost step reply` | +| A normal row has its original canonical witness before native delivery. After a source ACK, its positive acceptance settles only that row; a lost step reply or stale cursor does not offer it again. | `[unit]` `src/core/dispatch/admission.test.ts::admit — the thread admission claim::captures the original normal row before native delivery and holds changed proof: changed=%s`; `src/core/runLedger/writeThrough.test.ts::source input admission::settles an original normal echo after source ACK without resurrecting it: boundary=%s`; `::reconciles an adopted normal settlement after a lost stale-step reply without offering it again` | +| A first normal confirmation received during an earlier step read remains queued for the next step. | `[unit]` `src/core/runLedger/writeThrough.test.ts::source input admission::retains a first normal confirmation that arrives during an earlier source step read` | + ## Retained original source tasks The optional version 1 `sourceTask` snapshot stores the original orchestrator coordinates and the same eight task fields as the live fold-target projection: repository, branch, base branch, input head, PR number, accepted operation-target data, native GitHub identity and record task key. These are data to compare, not a requester, credential, current permission or executable action target. The complete snapshot is bounded to 16 KiB; unsafe data, unknown fields and unsupported versions stay unproved. diff --git a/src/channels/planeEffects.test.ts b/src/channels/planeEffects.test.ts index 38cf030b6..0bf749092 100644 --- a/src/channels/planeEffects.test.ts +++ b/src/channels/planeEffects.test.ts @@ -1,11 +1,16 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { createHash } from "node:crypto"; +import * as receipts from "../core/references/receipts.js"; +import { seedSourceInputCheckpoints } from "../core/testing/sourceInputs.js"; +import { unreadInbox } from "../core/runLedger/decisions.js"; +import type { StepRecord } from "../core/runLedger/types.js"; import type { IncomingMessage, ServerResponse } from "node:http"; import { Secret } from "../secrets.js"; import { FollowUpInbox } from "../core/threadAdmission.js"; import { InMemoryRunLedger } from "../core/runLedger/inMemory.js"; import type { RunLedger } from "../core/runLedger/ledger.js"; import { LEASE_MS } from "../core/runLedger/types.js"; -import { createLedgerWriteThrough, deliverPlaneSteer } from "../core/runLedger/writeThrough.js"; +import { createLedgerWriteThrough, createPlaneSteerSender, deliverPlaneSteer } from "../core/runLedger/writeThrough.js"; import { handlePlaneEffects, type PlaneEffectsDeps } from "./planeEffects.js"; import type { CoordinatorReconcileEffect, @@ -92,6 +97,215 @@ function harness(over: Partial = {}) { const settle = () => new Promise((r) => setTimeout(r, 0)); +describe("exact provider recovery delivery", () => { + it.each([false, true])( + "acknowledges the original pushed row while keeping display text separate: changed=%s", + async (changed) => { + const ledger = new InMemoryRunLedger(() => 1000); + const fixture = await seedSourceInputCheckpoints(ledger); + const original = { + version: 1 as const, + kind: "provider-reissue" as const, + targetRunId: fixture.id, + channelId: "cli:main", + threadKey: fixture.thread, + text: changed + ? "stored display bytes" + : "the model provider anthropic is answering again — re-issue the held turn and continue", + at: 2000, + userId: "plane" as const, + userName: "plane" as const, + plane: { steer: "reissue" as const, provider: "anthropic" }, + // The canonical writer appends custody after the original message. + target: { + version: 1, + runId: fixture.id, + channelId: "cli:main", + threadKey: fixture.thread, + requester: "cli:alice", + producerGen: fixture.gen, + }, + }; + ledger.inbox.get(fixture.id)!.push({ seq: 5, message: original }); + const inbox = new FollowUpInbox(); + const sender = createPlaneSteerSender({ + draining: () => false, + getRun: () => ({ threadKey: fixture.thread }), + getInbox: () => ({ runId: fixture.id, inbox }), + }); + const h = harness({ execute: { draining: () => false, admit: async () => "done", steer: sender } }); + const r = request( + { effects: [{ id: "steer:source-consumer:5", kind: "steer", runId: fixture.id, seq: 5, message: original }] }, + { bearer: "memory-token" }, + ); + handlePlaneEffects(r.req, r.res, h.deps); + await vi.waitFor(() => expect(r.writes.status).toBe(200)); + expect(h.acked).toEqual([{ id: "steer:source-consumer:5", outcome: "done" }]); + const [delivered] = inbox.drain(); + expect(delivered.text).toBe( + "the model provider anthropic is answering again — re-issue the held turn and continue", + ); + expect( + await ledger.step( + fixture.id, + fixture.gen, + { + ...fixture.step, + step: 1, + inboxConsumedSeq: 5, + inboxAcknowledgedRows: [delivered.ledgerWitness!], + }, + [], + fixture.session, + ), + ).toEqual({ ok: true }); + const after = await ledger.peekInbox(fixture.id, fixture.gen, 0); + if (!after.ok) throw new Error("missing canonical provider row"); + expect(after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord)).map((row) => row.seq)).toEqual([ + 1, 2, 3, 4, + ]); + expect(delivered.ledgerWitness).toEqual({ + version: 1, + runId: fixture.id, + seq: 5, + digest: createHash("sha256").update(JSON.stringify(original)).digest("hex"), + }); + }, + ); + + it.each(["push", "heartbeat"] as const)( + "defers %s recovery if drain begins while receipt hashing waits", + async (transport) => { + const offered = steer("live-run-1", 7) as Extract; + const inbox = new FollowUpInbox(); + let draining = false; + let entered!: () => void, release!: () => void; + const hashing = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const originalHash = receipts.sourceHash; + const hash = vi.spyOn(receipts, "sourceHash").mockImplementation(async (value) => { + const digest = await originalHash(value); + entered(); + await gate; + return digest; + }); + const sender = createPlaneSteerSender({ + draining: () => draining, + getRun: () => ({ threadKey: "slack:C1:1.0" }), + getInbox: () => ({ runId: "live-run-1", inbox }), + }); + const execute = { draining: () => draining, admit: async () => "done" as const, steer: sender }; + const outcomes: PlaneAckOutcome[] = []; + let start: () => void; + let close: (() => Promise) | undefined; + if (transport === "push") { + const h = harness({ + execute, + ack: async (_effect, outcome) => { + outcomes.push(outcome); + }, + }); + const r = request({ effects: [offered] }, { bearer: "memory-token" }); + start = () => handlePlaneEffects(r.req, r.res, h.deps); + } else { + const inner = new InMemoryRunLedger(() => 1000); + await inner.claim({ + runId: "live-run-1", + threadKey: "slack:C1:1.0", + gen: "g1", + startedAt: 1000, + leaseMs: LEASE_MS, + meta: { channelId: "slack:C1", userId: "slack:UTEST", threadKey: "slack:C1:1.0", agent: "coding" }, + system: "coding", + tools: [], + }); + const ledger = new Proxy(inner, { + get(target, prop) { + if (prop === "heartbeat") return async () => ({ ok: true, effects: [offered] }); + if (prop === "planeAck") + return async (_id: string, outcome: PlaneAckOutcome) => { + outcomes.push(outcome); + }; + const value = target[prop as keyof InMemoryRunLedger]; + return typeof value === "function" ? value.bind(target) : value; + }, + }); + const beats: Array<() => void> = []; + const wt = createLedgerWriteThrough({ + ledger, + gen: "g1", + fallback: { put: async () => {}, abandoned: () => {} }, + warn: () => {}, + planeEffects: execute, + setInterval: (fn) => { + beats.push(fn); + return {}; + }, + clearInterval: () => {}, + }); + const row = inner.live.get("live-run-1")!; + const run = wt.adopt({ + runId: row.runId, + threadKey: row.threadKey, + meta: row.meta, + startedAt: row.startedAt, + state: row.state, + lastStep: 0, + lastSeq: 0, + }); + close = () => run.close(); + start = () => beats[0]!(); + } + try { + start(); + await hashing; + draining = true; + release(); + await vi.waitFor(() => expect(outcomes).toEqual(["deferred"])); + expect(inbox.drain()).toEqual([]); + draining = false; + start(); + await vi.waitFor(() => expect(outcomes).toEqual(["deferred", "done"])); + expect(inbox.drain().map((input) => input.ledgerSeq)).toEqual([7]); + start(); + await vi.waitFor(() => expect(outcomes).toEqual(["deferred", "done", "skipped"])); + expect(inbox.drain()).toEqual([]); + draining = true; + start(); + await vi.waitFor(() => expect(outcomes).toEqual(["deferred", "done", "skipped", "deferred"])); + } finally { + release(); + hash.mockRestore(); + await close?.(); + } + }, + ); + + it("checks the current run and admission slot before delivery and duplicate handling", async () => { + const inbox = new FollowUpInbox(); + let run: { finished?: boolean; threadKey?: string } | undefined; + let slot = { runId: "another-run", inbox }; + let draining = false; + const sender = createPlaneSteerSender({ draining: () => draining, getRun: () => run, getInbox: () => slot }); + const offered = steer() as Extract; + expect(await sender(offered)).toBe("deferred"); + run = { threadKey: "slack:C1:1.0", finished: true }; + expect(await sender(offered)).toBe("deferred"); + run.finished = false; + expect(await sender(offered)).toBe("deferred"); + slot = { runId: offered.runId, inbox }; + expect(await sender(offered)).toBe("done"); + expect(await sender(offered)).toBe("skipped"); + draining = true; + expect(await sender(offered)).toBe("deferred"); + expect(inbox.drain().map((input) => input.ledgerSeq)).toEqual([7]); + }); +}); + describe("POST /plane/effects — the push transport (record 0064)", () => { it("reconciles a closed offer without a runId and passes its verified report receipt to ACK", async () => { const offered: CoordinatorReconcileEffect = { diff --git a/src/channels/planeEffects.ts b/src/channels/planeEffects.ts index b94e024b3..36d784257 100644 --- a/src/channels/planeEffects.ts +++ b/src/channels/planeEffects.ts @@ -14,7 +14,7 @@ import type { IncomingMessage, ServerResponse } from "node:http"; import type { Secret } from "../secrets.js"; -import type { PlaneAckOutcome, PlaneEffect } from "../core/plane/decide.js"; +import type { PlaneAckOutcome, PlaneEffect, PlaneSteerMessage } from "../core/plane/decide.js"; import { isCoordinatorReconcileEffect, isCoordinatorReconcileReceipt, @@ -64,21 +64,8 @@ type ObjectValue = Record; const objectValue = (v: unknown): ObjectValue | undefined => typeof v === "object" && v !== null && !Array.isArray(v) ? (v as ObjectValue) : undefined; -function parseEffect(v: unknown): PushedEffect | undefined { - const e = objectValue(v); - if (!e || typeof e.id !== "string" || e.id.length === 0) return undefined; - if (e.kind === "coordinator_reconcile") return isCoordinatorReconcileEffect(e) ? e : undefined; - if (typeof e.runId !== "string" || e.runId.length === 0) return undefined; - if (e.kind === "admit") { - if (typeof e.threadKey !== "string" || e.threadKey.length === 0) return undefined; - const request = objectValue(e.request); - if (!request) return undefined; - return { id: e.id, kind: "admit", runId: e.runId, threadKey: e.threadKey, request }; - } - if (e.kind !== "steer" || !Number.isSafeInteger(e.seq) || (e.seq as number) < 1) return undefined; - const message = objectValue(e.message); +function isSteerMessage(message: Record, runId: string): message is PlaneSteerMessage { if ( - !message || typeof message.channelId !== "string" || message.channelId.length === 0 || typeof message.threadKey !== "string" || @@ -89,31 +76,37 @@ function parseEffect(v: unknown): PushedEffect | undefined { message.userId !== "plane" || message.userName !== "plane" ) - return undefined; + return false; const restored = messageFromInbox(message, message.at, { - runId: e.runId, + runId, channelId: message.channelId, threadKey: message.threadKey, }); - if (restored?.control?.kind !== "provider-reissue") return; + return restored?.control?.kind === "provider-reissue"; +} + +function parseEffect(v: unknown): PushedEffect | undefined { + const e = objectValue(v); + if (!e || typeof e.id !== "string" || e.id.length === 0) return undefined; + if (e.kind === "coordinator_reconcile") return isCoordinatorReconcileEffect(e) ? e : undefined; + if (typeof e.runId !== "string" || e.runId.length === 0) return undefined; + if (e.kind === "admit") { + if (typeof e.threadKey !== "string" || e.threadKey.length === 0) return undefined; + const request = objectValue(e.request); + if (!request) return undefined; + return { id: e.id, kind: "admit", runId: e.runId, threadKey: e.threadKey, request }; + } + if (e.kind !== "steer" || !Number.isSafeInteger(e.seq) || (e.seq as number) < 1) return undefined; + const message = objectValue(e.message); + if (!message || !isSteerMessage(message, e.runId)) return; return { id: e.id, kind: "steer", runId: e.runId, seq: e.seq as number, - message: { - version: 1, - kind: "provider-reissue", - targetRunId: e.runId, - ...(restored.custody ? { target: restored.custody } : {}), - channelId: message.channelId, - threadKey: message.threadKey, - text: restored.msg.text, - at: message.at, - userId: "plane", - userName: "plane", - plane: { steer: "reissue", provider: restored.control.provider }, - }, + // The exact stored bytes prove row settlement. Canonical display text is + // rendered separately at live delivery, never into this receipt input. + message, }; } diff --git a/src/core/dispatch/admission.test.ts b/src/core/dispatch/admission.test.ts index fcccacc96..56df033ee 100644 --- a/src/core/dispatch/admission.test.ts +++ b/src/core/dispatch/admission.test.ts @@ -1,6 +1,7 @@ import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; import { ConfigStore } from "../../config.js"; import { parseDirectives } from "../../directives.js"; @@ -426,6 +427,51 @@ describe("admit — the thread admission claim", () => { expect(admission.get(THREAD)).toBe(claim.live); // still the live run's slot }); + it.each([false, true])( + "captures the original normal row before native delivery and holds changed proof: changed=%s", + async (changed) => { + const inner = new InMemoryRunLedger(() => NOW); + await inner.claim({ + runId: "run-owned", + threadKey: THREAD, + gen: "gen-T", + leaseMs: 30_000, + startedAt: 5_000, + meta: { channelId: "slack:CX", userId: "slack:UX", threadKey: THREAD, agent: "general" }, + card: null, + system: "sys", + tools: [], + }); + const read = inner.readInbox.bind(inner); + if (changed) + inner.readInbox = async (...args) => + (await read(...args)).map((item) => ({ ...item, message: { ...item.message, text: "another payload" } })); + const s = setup("also check the migration"); + s.deps.runLedger = createLedgerWriteThrough({ + ledger: inner, + gen: "gen-T", + fallback: new NullRunStore(), + warn: () => {}, + }); + const live = s.admission.claim(THREAD, { agent: "general" }).live; + live.runId = "run-owned"; + expect(await admit(s.deps, s.ctx)).toEqual({ kind: "steered", where: "here", runId: "run-owned" }); + const [stored] = await read("run-owned", 0); + const [input] = live.inbox.drain(); + expect(input).toMatchObject({ text: "also check the migration", ledgerSeq: 1 }); + expect(input.ledgerWitness).toEqual( + changed + ? undefined + : { + version: 1, + runId: "run-owned", + seq: 1, + digest: createHash("sha256").update(JSON.stringify(stored!.message)).digest("hex"), + }, + ); + }, + ); + it("a requester DM question followed by fix it keeps one live run and its private address through durable delivery", async () => { const dm = { channelId: "slack:DMAIN", diff --git a/src/core/dispatch/admission.ts b/src/core/dispatch/admission.ts index db378a23a..89f9fc4a6 100644 --- a/src/core/dispatch/admission.ts +++ b/src/core/dispatch/admission.ts @@ -59,6 +59,9 @@ import { replyAck, replyOutcome, REFUSAL_SENTENCES } from "./reply.js"; import { RESTART_CLAIM_GRACE_MS } from "../budgets.js"; import type { RunStore } from "../runStore.js"; import { cancellationOf, cancellationRecordMatches } from "../runLedger/cancellation.js"; +import { sourceHash } from "../references/receipts.js"; +import { sourceSnapshot } from "../runLedger/sourceEvents.js"; +import { inboxCustodyOf } from "../runLedger/inboxMessage.js"; /** What thread admission reads off the dispatcher's dependencies. `CoreDeps` * extends this; a caller's shape is unchanged. */ @@ -231,6 +234,33 @@ export function followUpFromInbox( return followUpOf(msg, msg.text, at, { ledgerSeq: item.seq, ...(from ? { from } : { io }) }); } +/** Capture before delivery. Missing or changed row proof cannot be replaced + * with a witness read after the native input was accepted. */ +async function witnessedFollowUp( + input: DispatchFollowUp, + runId: string, + item: InboxItem | undefined, + expected?: Record, +): Promise { + if (!item || item.seq !== input.ledgerSeq || item.message.kind === "source-evidence") return input; + const original = structuredClone(item.message); + const custody = inboxCustodyOf(original.target); + if (original.target !== undefined && custody?.runId !== runId) return input; + const { target: _target, ...payload } = original; + if (expected && JSON.stringify(sourceSnapshot(payload)) !== JSON.stringify(sourceSnapshot(expected))) return input; + return { ...input, ledgerWitness: { version: 1, runId, seq: item.seq, digest: await sourceHash(original) } }; +} + +async function pushedFollowUp( + ledger: Partial>, + runId: string | undefined, + input: DispatchFollowUp, +): Promise { + if (runId === undefined || input.ledgerSeq === undefined || !ledger.readInbox) return input; + const original = (await ledger.readInbox(runId, input.ledgerSeq - 1)).find((item) => item.seq === input.ledgerSeq); + return witnessedFollowUp(input, runId, original, durableInboxMessage(input.msg, input.text, input.at, input.from)); +} + /** Close a restart's row this dispatch will never run (item 42): the thread * has a newer run — the user re-mentioned after the kill — so the reserved * run is closed `interrupted` with a record of its identity and request, @@ -668,6 +698,15 @@ async function claimThread(deps: AdmissionDeps, ctx: AdmissionContext): Promise< const ledgerSeq = !beforeReservation ? await deps.runLedger.pushInbox(claim.live.runId!, durableInboxMessage(msg, directives.text, at)) : undefined; + const input = await pushedFollowUp( + deps.runLedger, + claim.live.runId, + followUpOf(msg, directives.text, at, { + io, + ledgerSeq, + ...(beforeReservation ? { beforeReservation: true } : {}), + }), + ); if (admission.get(msg.threadKey) !== claim.live) { // The run finished and released the thread during the round trip: an // item pushed now would sit on a dead slot (and its durable copy went @@ -676,13 +715,7 @@ async function claimThread(deps: AdmissionDeps, ctx: AdmissionContext): Promise< console.log(`[dispatch] ${msg.threadKey} the run finished during the steer — running the follow-up fresh`); return { kind: "redispatch" }; } - claim.live.inbox.push( - followUpOf(msg, directives.text, at, { - io, - ledgerSeq, - ...(beforeReservation ? { beforeReservation: true } : {}), - }), - ); + claim.live.inbox.push(input); console.log( `[dispatch] ${msg.threadKey} follow-up steered into the ${claim.live.agent} run in flight (${claim.live.inbox.size} pending${ledgerSeq !== undefined ? `, durable seq ${ledgerSeq}` : ""})`, ); @@ -789,8 +822,14 @@ async function claimThread(deps: AdmissionDeps, ctx: AdmissionContext): Promise< // adopt-time re-read ran before this push landed, or after — either // way the inbox folds one seq in once): hand the item to it as well. const nowLive = admission.get(msg.threadKey); - if (nowLive && nowLive.runId === elsewhere.runId) - nowLive.inbox.push(followUpOf(msg, directives.text, now, { io, ledgerSeq: seq })); + if (nowLive && nowLive.runId === elsewhere.runId) { + const input = await pushedFollowUp( + deps.runLedger, + elsewhere.runId, + followUpOf(msg, directives.text, now, { io, ledgerSeq: seq }), + ); + if (admission.get(msg.threadKey) === nowLive) nowLive.inbox.push(input); + } console.log( `[dispatch] ${msg.threadKey} follow-up steered into run ${elsewhere.runId} live on another generation (durable seq ${seq}${nowLive ? ", now live here" : ""})`, ); @@ -884,7 +923,8 @@ export type SteerOutcome = export async function steerRun( deps: { config: Pick; - runLedger: Pick & Partial>; + runLedger: Pick & + Partial>; clock?: Clock; admission: Pick, "get">; }, @@ -936,7 +976,14 @@ export async function steerRun( if (ledgerSeq === undefined && (deps.runLedger.sessionPersistence !== false || live?.runId !== target.runId)) return { kind: "not_live" }; if (live && live.runId === target.runId) { - live.inbox.push(followUpOf(msg, text, at, { ledgerSeq, ...(sender.from ? { from: sender.from } : {}) })); + const input = await pushedFollowUp( + deps.runLedger, + target.runId, + followUpOf(msg, text, at, { ledgerSeq, ...(sender.from ? { from: sender.from } : {}) }), + ); + if (deps.admission.get(target.threadKey) !== live) + return ledgerSeq === undefined ? { kind: "not_live" } : { kind: "steered", where: "elsewhere", at, ledgerSeq }; + live.inbox.push(input); console.log( `[steer] ${sender.from ? `the run ${sender.from.runId}` : sender.userId} → the ${target.agent} run ${target.runId} in ${target.threadKey} (${live.inbox.size} pending${ledgerSeq !== undefined ? `, durable seq ${ledgerSeq}` : ""})`, ); @@ -994,7 +1041,8 @@ export const STEER_OWNER_REFUSED = */ export function createSteerSender(deps: { config: Pick; - runLedger: Pick & Partial>; + runLedger: Pick & + Partial>; /** The run the id names, as the process knows it (the registry's live row). */ runs: { getById(id: string): SteerableRun | null | Promise }; admission: Pick, "get">; @@ -1198,7 +1246,7 @@ export async function foldCarriedInbox( ); continue; } - admitted.inbox.push(followUp); + admitted.inbox.push(await witnessedFollowUp(followUp, carriedRow.runId, item)); folded++; } if (folded > 0) diff --git a/src/core/dispatch/runLoop.ts b/src/core/dispatch/runLoop.ts index 8002165f2..92b35bd44 100644 --- a/src/core/dispatch/runLoop.ts +++ b/src/core/dispatch/runLoop.ts @@ -4206,7 +4206,10 @@ export async function runLoop(deps: RunDeps, ctx: RunLoopContext): Promise mainSources.accept(inputs), + confirmedFollowUps: (inputs) => { + ledgerRun?.confirmInboxInputs(inputs); + mainSources.accept(inputs.filter((input) => input.userId !== PLANE_ACTOR_ID)); + }, onEvent, onProgress, // The provider park's capability (model-proxy item 12a; record diff --git a/src/core/harness/contract.ts b/src/core/harness/contract.ts index 3482ea259..f7e4f3017 100644 --- a/src/core/harness/contract.ts +++ b/src/core/harness/contract.ts @@ -645,7 +645,8 @@ export interface HarnessRun { /** Controller-recorded reads whose observed native result must be saved before another model call. */ sourceResultCallIds?: () => readonly string[]; prepareSourceMedia?: () => Promise; - /** Called only when the harness confirms a steer reached the model's conversation. */ + /** Positive native acceptance of an ordinary steer, or a successful typed + * internal control response. Source evidence needs its separate native proof. */ confirmedFollowUps?: (inputs: readonly FollowUpInput[]) => void; onEvent?: (event: RunEvent) => void; onProgress?: (note: string) => void; diff --git a/src/core/harness/pi/harness.test.ts b/src/core/harness/pi/harness.test.ts index 844d6beda..2eff7dc5c 100644 --- a/src/core/harness/pi/harness.test.ts +++ b/src/core/harness/pi/harness.test.ts @@ -7,7 +7,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createServer } from "node:net"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { ALLOWANCES, bearerExpiresAt, loopClock, MINUTE_MS, PROVIDER_RETRY_BACKOFFS_MS } from "../../budgets.js"; import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; import { createBashTool } from "@earendil-works/pi-coding-agent"; @@ -712,6 +712,12 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => userName: restored.msg.userName, msg: restored.msg, ledgerSeq: row.seq, + ledgerWitness: { + version: 1 as const, + runId: "run-7", + seq: row.seq, + digest: createHash("sha256").update(JSON.stringify(row.message)).digest("hex"), + }, }, }; }; @@ -2526,6 +2532,11 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => if (opened.kind !== "tracked") throw new Error(`the run was not tracked: ${opened.kind}`); const ledgerRun = opened.run; w.run.onStep = ledgerRun.step.bind(ledgerRun); + const confirmedControls: number[] = []; + w.run.confirmedFollowUps = (inputs) => { + confirmedControls.push(...inputs.filter((input) => input.userId === "plane").map((input) => input.ledgerSeq!)); + ledgerRun.confirmInboxInputs(inputs); + }; const firstUp = await providerUp(), inFlightUp = await providerUp(); const up = firstUp.input, @@ -2585,6 +2596,7 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => w.inbox.push({ ...up, ledgerSeq: firstUpSeq }); await expect(turn).resolves.toBe("follow-up recovered"); + expect([...new Set(confirmedControls)].sort((a, b) => a - b)).toEqual([1, 2]); const [reclaimed] = await reclaimWithLease(); // Local cursor/echo proof is not native consumption: SQLite retains the exact raw rows. expect(await ledger.readInbox("run-7", 0)).toEqual([firstUp.row, inFlightUp.row]); @@ -2636,6 +2648,11 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => if (opened.kind !== "tracked") throw new Error(`the run was not tracked: ${opened.kind}`); const ledgerRun = opened.run; w.run.onStep = ledgerRun.step.bind(ledgerRun); + const confirmedControls: number[] = []; + w.run.confirmedFollowUps = (inputs) => { + confirmedControls.push(...inputs.filter((input) => input.userId === "plane").map((input) => input.ledgerSeq!)); + ledgerRun.confirmInboxInputs(inputs); + }; const ordinary = { text: "also bump the changelog", userId: "slack:UALICE", at: NOW }; const ordinaryRow = await externalRow(ordinary), controlRow = await providerUp(); @@ -2706,6 +2723,7 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => // The bot process dies here; reclaim must use the durable cursor, not the // in-process relaunch record, and offer only the ordinary deferred row. + expect([...new Set(confirmedControls)].sort((a, b) => a - b)).toEqual([2]); const [reclaimed] = await reclaimWithLease(); expect(planResume({ transcript: completed, lastStep: reclaimed!.lastStep!, tools: [] })).toMatchObject({ kind: "finish", @@ -2861,6 +2879,11 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => }); if (opened.kind !== "tracked") throw new Error(`the run was not tracked: ${opened.kind}`); w.run.onStep = opened.run.step.bind(opened.run); + const confirmedControls: number[] = []; + w.run.confirmedFollowUps = (inputs) => { + confirmedControls.push(...inputs.filter((input) => input.userId === "plane").map((input) => input.ledgerSeq!)); + opened.run.confirmInboxInputs(inputs); + }; const controlRow = await providerUp(), up = controlRow.input, upSeq = controlRow.row.seq; @@ -2906,6 +2929,7 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => await expect(w.start()).resolves.toBe("recovered on the local retry"); + expect([...new Set(confirmedControls)].sort((a, b) => a - b)).toEqual([1]); const [reclaimed] = await reclaimWithLease(); // Local cursor/echo proof is not native consumption: SQLite retains the exact raw rows. expect(await ledger.readInbox("run-7", 0)).toEqual([controlRow.row]); @@ -2941,6 +2965,11 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => }); if (opened.kind !== "tracked") throw new Error(`the run was not tracked: ${opened.kind}`); w.run.onStep = opened.run.step.bind(opened.run); + const confirmedControls: number[] = []; + w.run.confirmedFollowUps = (inputs) => { + confirmedControls.push(...inputs.filter((input) => input.userId === "plane").map((input) => input.ledgerSeq!)); + opened.run.confirmInboxInputs(inputs); + }; const firstUp = await providerUp(), inFlightUp = await providerUp(); const up = firstUp.input, @@ -2994,6 +3023,7 @@ describe("runPiHarness — a run on pi from the first file to the answer", () => w.inbox.push({ ...up, ledgerSeq: firstUpSeq }); await expect(done).resolves.toBe("recovered on the plane reissue"); + expect([...new Set(confirmedControls)].sort((a, b) => a - b)).toEqual([1, 2]); const [reclaimed] = await reclaimWithLease(); // Local cursor/echo proof is not native consumption: SQLite retains the exact raw rows. expect(await ledger.readInbox("run-7", 0)).toEqual([firstUp.row, inFlightUp.row]); diff --git a/src/core/harness/pi/harness.ts b/src/core/harness/pi/harness.ts index 92d579baa..862f08f6e 100644 --- a/src/core/harness/pi/harness.ts +++ b/src/core/harness/pi/harness.ts @@ -1686,7 +1686,10 @@ export async function runPiHarnessOpen(deps: PiHarnessDeps, run: HarnessRun): Pr const at = unechoed.findIndex((u) => echoKey(u.message) === key); if (at < 0) return; const [echoed] = unechoed.splice(at, 1); - run.confirmedFollowUps?.(echoed!.inputs); + const ordinary = echoed!.inputs.filter( + (input) => !(input.userId === PLANE_ACTOR_ID && isReissueSteerText(input.text)), + ); + if (ordinary.length) run.confirmedFollowUps?.(ordinary); if (echoed!.seq > mirror.inboxConsumedSeq) mirror.inboxConsumedSeq = echoed!.seq; }; unechoedSeqs = () => @@ -2419,6 +2422,7 @@ export async function runPiHarnessOpen(deps: PiHarnessDeps, run: HarnessRun): Pr ...reissueInFlightRows.map((item) => item.ledgerSeq ?? 0), ...pendingReissue.map((item) => item.ledgerSeq ?? 0), ); + run.confirmedFollowUps?.([...reissueInFlightRows, ...pendingReissue]); await mirror.checkpointInbox(); reissueInFlight = undefined; clearProviderHold(); @@ -2440,6 +2444,7 @@ export async function runPiHarnessOpen(deps: PiHarnessDeps, run: HarnessRun): Pr mirror.inboxConsumedSeq, ...pendingReissue.map((item) => item.ledgerSeq ?? 0), ); + run.confirmedFollowUps?.(pendingReissue); await mirror.checkpointInbox(); clearProviderHold(); } @@ -3050,6 +3055,7 @@ export async function runPiHarnessOpen(deps: PiHarnessDeps, run: HarnessRun): Pr ...turnReissueInFlightRows.map((item) => item.ledgerSeq ?? 0), ...turnReissueRows.map((item) => item.ledgerSeq ?? 0), ); + run.confirmedFollowUps?.([...turnReissueInFlightRows, ...turnReissueRows]); await mirror.checkpointInbox(); clearTurnProviderHold(); } @@ -3069,6 +3075,7 @@ export async function runPiHarnessOpen(deps: PiHarnessDeps, run: HarnessRun): Pr mirror.inboxConsumedSeq, ...turnReissueRows.map((item) => item.ledgerSeq ?? 0), ); + run.confirmedFollowUps?.(turnReissueRows); await mirror.checkpointInbox(); clearTurnProviderHold(); } diff --git a/src/core/harness/pi/sourceInputCheckpoint.ts b/src/core/harness/pi/sourceInputCheckpoint.ts new file mode 100644 index 000000000..f23eb1b5d --- /dev/null +++ b/src/core/harness/pi/sourceInputCheckpoint.ts @@ -0,0 +1,42 @@ +import type { AudienceCheck } from "../../audienceDecision.js"; +import type { ContextDependencies } from "../../references/contextDependencies.js"; +import type { SourceInputAdmission, SourceInputIntent } from "../../runLedger/sourceInputIntent.js"; +import type { LedgerRun } from "../../runLedger/writeThrough.js"; +import { readPiSourceInputReceipt } from "./sourceInputReceipt.js"; + +/** Settle an existing native input. The host reads the original file through + * its executor; this operation never submits a command or starts a model. + * The tracked writer verifies canonical readback before each exact ACK. */ +export async function checkpointPiSourceInput( + original: SourceInputIntent, + file: { path: string; content: string }, + run: Pick, + validate: (context: ContextDependencies) => Promise, +): Promise { + const native = readPiSourceInputReceipt(original, file); + if (!native.ok) return false; + const receipt: SourceInputAdmission = { + version: 1, + inputId: native.receipt.inputId, + intentHash: native.receipt.intentHash, + native: { + harness: "pi", + sessionId: native.receipt.native.sessionFile, + sessionIdentity: native.receipt.native.sessionId, + entryId: native.receipt.native.entryId, + entryHash: native.receipt.native.entryHash, + }, + }; + const committed = await run.sourceInputCheckpoint({ operation: "commit", receipt }, validate); + if (!committed.ok || !committed.checkpoint) return false; + if (committed.checkpoint.acknowledged) return true; + const acknowledged = await run.sourceInputCheckpoint( + { operation: "ack", inputId: receipt.inputId, receiptHash: committed.checkpoint.receiptHash }, + validate, + ); + return ( + acknowledged.ok && + acknowledged.checkpoint?.acknowledged === true && + acknowledged.checkpoint.receiptHash === committed.checkpoint.receiptHash + ); +} diff --git a/src/core/runLedger/inMemory.ts b/src/core/runLedger/inMemory.ts index bd0d94907..7a32cc73a 100644 --- a/src/core/runLedger/inMemory.ts +++ b/src/core/runLedger/inMemory.ts @@ -5,6 +5,18 @@ import { sourceObligationContextReferences, sourceObligationHolder, } from "./sourceObligations.js"; +import { + inboxAcknowledgedRowsOf, + prepareInboxAcknowledgments, + inboxAcknowledgmentRowsUnchanged, +} from "./inboxAcknowledgments.js"; +import { + prepareSourceInputCheckpoint, + protectSourceInputStep, + sourceInputCheckpointRequestOf, + type SourceInputCheckpointRequest, + type SourceInputCheckpointResult, +} from "./sourceInputIntent.js"; import { inspectOriginal, type OriginalCell } from "./originalEvidenceReader.js"; import { ORIGINAL_CELL_BYTES, @@ -88,6 +100,7 @@ import { } from "../budgets.js"; import { planSourceJobClaim, planSourceJobRelease, planSourceRelevanceSave } from "./sourceEventJobs.js"; import { + sourceSnapshot, sourceRelevanceRequestOf, type SourceRelevanceSaveResult, isSourceEventKey, @@ -2129,6 +2142,10 @@ export class InMemoryRunLedger implements RunLedger { session?: string, ): Promise { if (!Number.isSafeInteger(record.step) || record.step < 0) throw new Error("invalid public step key"); + const normal = + record.inboxAcknowledgedRows === undefined ? undefined : inboxAcknowledgedRowsOf(record.inboxAcknowledgedRows); + if (record.inboxAcknowledgedRows !== undefined && !normal) return { ok: false, reason: "fenced" }; + record = { ...record, ...(normal ? { inboxAcknowledgedRows: normal } : {}) }; const owner = this.live.get(runId); if (owner && inboxSegmentFloor(this.steps.get(runId)?.inboxSegmentArchive, owner) === undefined) throw new Error("retained inbox segment boundary is unreadable"); @@ -2136,11 +2153,64 @@ export class InMemoryRunLedger implements RunLedger { if (!written.ok) return written; const fence = this.fence(runId, gen); if (!fence.ok) return fence; + const current = this.live.get(runId)!; + if (normal?.length && current.phase !== "live") return { ok: false, reason: "fenced" }; const list = this.steps.get(runId) ?? []; const base = workspaceDurabilityArchiveOf(this.allocationArchive(runId))?.promotionStepBase ?? 0; const index = base + record.step; - if (index < list.length) list[index] = record; - else list.push(record); + const existing = list[index]; + if (existing?.inboxAcknowledgedRows?.length) { + return JSON.stringify(sourceSnapshot(existing)) === JSON.stringify(sourceSnapshot(record)) + ? { ok: true } + : { ok: false, reason: "fenced" }; + } + const prior = list.at(-1); + if (normal?.length && prior && record.step <= prior.step) return { ok: false, reason: "fenced" }; + const floor = inboxSegmentFloor(list.inboxSegmentArchive, current); + if (floor === undefined) return { ok: false, reason: "fenced" }; + const inbox = (this.inbox.get(runId) ?? []).filter((item) => item.seq > floor); + const before = JSON.stringify({ + row: sourceInputWriteSnapshot(current), + prior, + archive: list.inboxSegmentArchive, + base, + }); + const prepared = normal?.length + ? await prepareInboxAcknowledgments(runId, record, inbox) + : { witnesses: [], rows: [] }; + if (!prepared) return { ok: false, reason: "fenced" }; + if ( + this.live.get(runId) !== current || + before !== + JSON.stringify({ + row: sourceInputWriteSnapshot(current), + prior: this.steps.get(runId)?.at(-1), + archive: this.steps.get(runId)?.inboxSegmentArchive, + base: workspaceDurabilityArchiveOf(this.allocationArchive(runId))?.promotionStepBase ?? 0, + }) || + !inboxAcknowledgmentRowsUnchanged(prepared.rows, (seq) => + (this.inbox.get(runId) ?? []).find((item) => item.seq === seq), + ) + ) + return { ok: false, reason: "fenced" }; + const protectedStep = protectSourceInputStep( + current.state, + record, + (this.inbox.get(runId) ?? []).filter((item) => item.seq > floor), + prior, + prepared.witnesses, + ); + if (!protectedStep) { + console.warn("[runs/step] source input protection refused", { + runId, + ownerGen: gen, + step: record.step, + acknowledged: normal?.length ?? 0, + }); + return { ok: false, reason: "fenced" }; + } + if (index < list.length) list[index] = protectedStep; + else list.push(protectedStep); this.steps.set(runId, list); return { ok: true }; } @@ -2346,6 +2416,44 @@ export class InMemoryRunLedger implements RunLedger { }; } + async sourceInputCheckpoint( + runId: string, + gen: string, + request: SourceInputCheckpointRequest, + ): Promise { + const parsed = sourceInputCheckpointRequestOf(request); + if (!parsed) return { ok: false, reason: "fenced" }; + const capture = () => ({ + row: this.live.get(runId), + inbox: this.inbox.get(runId) ?? [], + step: this.steps.get(runId)?.at(-1), + archive: this.steps.get(runId)?.inboxSegmentArchive, + }); + const initial = capture(); + const fence = checkFence(initial.row, gen); + if (!fence.ok) return fence; + if (!initial.row) return { ok: false, reason: "unknown-run" }; + if (parsed.operation !== "read" && this.promotionHeld(runId, gen)) throw new PromotionPendingError(runId); + const floor = inboxSegmentFloor(initial.archive, initial.row); + if (floor === undefined) return { ok: false, reason: "fenced" }; + const before = JSON.stringify(initial); + const prepared = await prepareSourceInputCheckpoint( + initial.row, + parsed, + initial.inbox.filter((item) => item.seq > floor), + initial.step, + ); + if (!prepared || before !== JSON.stringify(capture())) return { ok: false, reason: "fenced" }; + if (parsed.operation !== "read") { + initial.row.state = prepared.state; + if (prepared.step) { + const steps = this.steps.get(runId)!; + steps[steps.length - 1] = prepared.step; + } + } + return { ok: true, checkpoint: structuredClone(prepared.checkpoint) }; + } + async setState(runId: string, gen: string, state: RunState): Promise { if ( Object.hasOwn(state, "cancellation") || diff --git a/src/core/runLedger/inboxAcknowledgments.ts b/src/core/runLedger/inboxAcknowledgments.ts new file mode 100644 index 000000000..cec304f03 --- /dev/null +++ b/src/core/runLedger/inboxAcknowledgments.ts @@ -0,0 +1,80 @@ +import { sourceHash } from "../references/receipts.js"; +import { DURABLE_INBOX_MAX_BYTES } from "./inboxMessage.js"; +import { sourceSnapshot } from "./sourceEvents.js"; +import type { InboxItem, InboxRowWitness, StepRecord } from "./types.js"; + +export interface PreparedInboxAcknowledgments { + witnesses: InboxRowWitness[]; + rows: { seq: number; json: string }[]; +} + +/** Positive normal-input confirmation, never a cursor or source admission. + * Capture witnesses before native delivery; a later row cannot replace them. */ +export function inboxAcknowledgedRowsOf(value: unknown): InboxRowWitness[] | undefined { + try { + const raw = sourceSnapshot(value); + if (!Array.isArray(raw) || new TextEncoder().encode(JSON.stringify(raw)).byteLength > DURABLE_INBOX_MAX_BYTES) + return; + const rows: InboxRowWitness[] = []; + const seen = new Set(); + for (const item of raw) { + if ( + !item || + typeof item !== "object" || + Array.isArray(item) || + Object.keys(item).length !== 4 || + !["version", "runId", "seq", "digest"].every((key) => Object.hasOwn(item, key)) || + item.version !== 1 || + typeof item.runId !== "string" || + item.runId.length < 1 || + item.runId.length > 512 || + /[\r\n\0]/.test(item.runId) || + !Number.isSafeInteger(item.seq) || + Number(item.seq) <= 0 || + seen.has(Number(item.seq)) || + typeof item.digest !== "string" || + !/^[a-f0-9]{64}$/.test(item.digest) + ) + return; + seen.add(Number(item.seq)); + rows.push({ version: 1, runId: item.runId, seq: Number(item.seq), digest: item.digest }); + } + return rows.sort((a, b) => a.seq - b.seq); + } catch { + return; + } +} + +/** Verify original row bytes before a step clears a normal deferral. The owning + * store compares these bytes and its prior boundary again at the final commit. */ +export async function prepareInboxAcknowledgments( + runId: string, + record: Pick, + inbox: readonly InboxItem[], +): Promise { + if (record.inboxAcknowledgedRows === undefined) return { witnesses: [], rows: [] }; + const witnesses = inboxAcknowledgedRowsOf(record.inboxAcknowledgedRows); + if (!witnesses) return; + const rows: PreparedInboxAcknowledgments["rows"] = []; + for (const witness of witnesses) { + const raw = inbox.find((item) => item.seq === witness.seq); + if (witness.runId !== runId || !raw) return; + sourceSnapshot(raw.message); + const item: InboxItem = JSON.parse(JSON.stringify({ seq: raw.seq, message: raw.message })); + // Every source version uses its own native receipt contract. Even a legacy + // or unsupported source cannot become an ordinary-input acknowledgment. + if (item.message.kind === "source-evidence" || (await sourceHash(item.message)) !== witness.digest) return; + rows.push({ seq: item.seq, json: JSON.stringify(item) }); + } + return { witnesses, rows }; +} + +export function inboxAcknowledgmentRowsUnchanged( + rows: PreparedInboxAcknowledgments["rows"], + read: (seq: number) => InboxItem | undefined, +): boolean { + return rows.every(({ seq, json }) => { + const item = read(seq); + return !!item && JSON.stringify({ seq: item.seq, message: item.message }) === json; + }); +} diff --git a/src/core/runLedger/ledger.ts b/src/core/runLedger/ledger.ts index bb874858b..f0e18e9f1 100644 --- a/src/core/runLedger/ledger.ts +++ b/src/core/runLedger/ledger.ts @@ -1,3 +1,4 @@ +import type { SourceInputCheckpointRequest, SourceInputCheckpointResult } from "./sourceInputIntent.js"; import type { InboxDeliveryResult } from "./inboxDelivery.js"; import type { CanonicalCheckpointSource, @@ -322,6 +323,12 @@ export interface RunLedger { append(runId: string, gen: string, events: AppendableEvent[]): Promise; /** Commit a state boundary and row projection atomically; ended also fences execution replay. */ assignLiveState(runId: string, gen: string, assignment: LiveStateAssignRequest): Promise; + /** Commit native evidence, read its canonical checkpoint, then acknowledge only its exact witness. */ + sourceInputCheckpoint( + runId: string, + gen: string, + request: SourceInputCheckpointRequest, + ): Promise; setState(runId: string, gen: string, state: RunState): Promise; /** Any generation: a steer arrives on whichever container is up. */ pushInbox(runId: string, message: Record): Promise; diff --git a/src/core/runLedger/sourceInputCheckpoint.test.ts b/src/core/runLedger/sourceInputCheckpoint.test.ts new file mode 100644 index 000000000..ec1025aeb --- /dev/null +++ b/src/core/runLedger/sourceInputCheckpoint.test.ts @@ -0,0 +1,514 @@ +import { captureSourceTaskSnapshot } from "../references/sourceTaskSnapshot.js"; +import { describe, expect, it, vi } from "vitest"; +import { InMemoryRunLedger } from "./inMemory.js"; +import { WorkerRunLedger } from "../runLedgerWorker.js"; +import { seedSourceInputCheckpoints } from "../testing/sourceInputs.js"; +import type { StepRecord } from "./types.js"; +import { unreadInbox } from "./decisions.js"; +import { sourceHash } from "../references/receipts.js"; +import { sourceSnapshot } from "./sourceEvents.js"; +import { sourceInputIntentsOf, type SourceInputCheckpointRequest } from "./sourceInputIntent.js"; + +async function fixture() { + const ledger = new InMemoryRunLedger(() => 1000); + return { ledger, ...(await seedSourceInputCheckpoints(ledger)) }; +} +async function unread(ledger: InMemoryRunLedger, id: string, gen = "g1") { + const peek = await ledger.peekInbox(id, gen, 0); + if (!peek.ok) throw new Error("missing fixture owner"); + return peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq); +} + +describe("canonical source input checkpoints", () => { + it("commits proof before exact ACK and preserves unrelated rows through later steps", async () => { + const { ledger, id, gen, receipt, step, session } = await fixture(); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + expect(committed).toEqual({ + ok: true, + checkpoint: { + receipt, + receiptHash: await sourceHash(sourceSnapshot(receipt)), + taskHash: await sourceHash(null), + acknowledged: false, + }, + }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + const read = await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId }); + expect(read).toEqual(committed); + if (!read.ok || !read.checkpoint) throw new Error("missing checkpoint"); + const ack = { operation: "ack", inputId: receipt.inputId, receiptHash: read.checkpoint.receiptHash } as const; + expect(await ledger.sourceInputCheckpoint(id, gen, ack)).toEqual({ + ok: true, + checkpoint: { ...read.checkpoint, acknowledged: true }, + }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + expect(await ledger.step(id, gen, { ...step, step: 1 }, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + expect(await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 4 }, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 4]); + expect(await ledger.setState(id, gen, { progress: "later" })).toEqual({ ok: true }); + expect(await ledger.sourceInputCheckpoint(id, gen, ack)).toEqual({ + ok: true, + checkpoint: { ...read.checkpoint, acknowledged: true }, + }); + }); + + it("holds source rows when an ordinary high-water step supplies no receipt", async () => { + const { ledger, id, gen, step, session } = await fixture(); + expect(await ledger.step(id, gen, { ...step, step: 1, inboxConsumedSeq: 4 }, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([2, 4]); + }); + + it("refuses mismatched native identity, original digest, owner and ACK hashes", async () => { + const { ledger, id, gen, receipt } = await fixture(); + for (const invalid of [ + { ...receipt, inputId: "foreign" }, + { ...receipt, intentHash: "b".repeat(64) }, + { ...receipt, native: { ...receipt.native, sessionId: "foreign" } }, + { ...receipt, native: { ...receipt.native, harness: "opencode" as const } }, + ]) + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt: invalid })).toEqual({ + ok: false, + reason: "fenced", + }); + expect(await ledger.sourceInputCheckpoint(id, "stale", { operation: "commit", receipt })).toEqual({ + ok: false, + reason: "fenced", + }); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: "a".repeat(64), + }), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt })).toMatchObject({ + ok: true, + checkpoint: { acknowledged: false }, + }); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "commit", + receipt: { ...receipt, native: { ...receipt.native, entryId: "replacement" } }, + }), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + }); + + it("keeps canonical proof private and rejects ordinary mint, erase or ACK", async () => { + const { ledger, id, gen, receipt, intents } = await fixture(); + const saved = { + version: 2, + entries: intents.entries, + checkpoints: [ + { + receipt, + receiptHash: await sourceHash(sourceSnapshot(receipt)), + taskHash: await sourceHash(null), + acknowledged: false, + }, + ], + }; + expect(await ledger.setState(id, gen, { sourceInputIntents: saved })).toEqual({ ok: false, reason: "fenced" }); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt })).toMatchObject({ + ok: true, + checkpoint: { acknowledged: false }, + }); + expect(await ledger.setState(id, gen, { sourceInputIntents: intents })).toEqual({ ok: false, reason: "fenced" }); + expect( + await ledger.setState(id, gen, { + sourceInputIntents: { ...saved, checkpoints: [{ ...saved.checkpoints[0], acknowledged: true }] }, + }), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + expect(sourceInputIntentsOf({ ...saved, version: 1 })).toBeUndefined(); + }); + + it("reconciles the same original after reclaim and never aliases two native entries", async () => { + const { ledger, id, gen, receipt, intents } = await fixture(); + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt })).toMatchObject({ ok: true }); + const second = { + ...receipt, + inputId: intents.entries[1]!.id, + intentHash: await sourceHash(sourceSnapshot(intents.entries[1])), + }; + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt: second })).toEqual({ + ok: false, + reason: "fenced", + }); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "commit", + receipt: { ...second, native: { ...second.native, entryId: "native-entry-two" } }, + }), + ).toMatchObject({ ok: true, checkpoint: { receipt: { inputId: "source-input-two" } } }); + expect(await ledger.handoff(gen, [id])).toEqual({ marked: [id] }); + const reclaimed = await ledger.reclaim("g2", 20000, 10000); + expect(reclaimed[0]?.row.ownerGen).toBe("g2"); + const read = await ledger.sourceInputCheckpoint(id, "g2", { operation: "read", inputId: receipt.inputId }); + expect(read).toMatchObject({ ok: true, checkpoint: { receipt, acknowledged: false } }); + if (!read.ok || !read.checkpoint) throw new Error("missing original"); + expect( + await ledger.sourceInputCheckpoint(id, "g2", { + operation: "ack", + inputId: receipt.inputId, + receiptHash: read.checkpoint.receiptHash, + }), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + expect(await unread(ledger, id, "g2")).toEqual([1, 3, 4]); + }); + + it.each(["session", "launch", "ended", "task"] as const)( + "holds ACK when the current %s changes after commit", + async (change) => { + const { ledger, id, gen, receipt } = await fixture(); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing checkpoint"); + const row = (await ledger.listLive()).find((row) => row.runId === id)!; + if (change === "task") { + const sourceTask = captureSourceTaskSnapshot(row); + expect(sourceTask).toMatchObject({ version: 1, owner: { runId: id } }); + expect(await ledger.setState(id, gen, { sourceTask })).toEqual({ ok: true }); + } else { + const harness = row.state.harness as Record; + expect( + await ledger.setState(id, gen, { + harness: { ...harness, ...(change === "session" ? { sessionFile: "foreign" } : { ended: true }) }, + }), + ).toEqual({ ok: true }); + if (change === "launch") + expect( + await ledger.setState(id, gen, { + harnessLaunch: { ...(row.state.harnessLaunch as Record), ordinal: 1, phase: "prepared" }, + }), + ).toEqual({ ok: true }); + } + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId })).toEqual( + committed, + ); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + }, + ); + + it("retains unrelated canonical deferrals when a stale report drops them", async () => { + const { ledger, id, gen, receipt, step, session } = await fixture(); + expect( + await ledger.step(id, gen, { ...step, step: 1, inboxConsumedSeq: 4, inboxDeferredSeqs: [1] }, [], session), + ).toEqual({ ok: true }); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing checkpoint"); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + expect(await unread(ledger, id)).toEqual([1, 4]); + expect( + await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 4, inboxDeferredSeqs: [] }, [], session), + ).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 4]); + }); + + it("settles only a confirmed normal row and never resurrects it from a stale report", async () => { + const { ledger, id, gen, receipt, step, session } = await fixture(); + const original = await ledger.peekInbox(id, gen, 0); + if (!original.ok) throw new Error("missing original inbox"); + const witness = original.items.find((item) => item.seq === 1)!.witness; + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing checkpoint"); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).toMatchObject({ ok: true }); + expect(await unread(ledger, id)).toEqual([1, 3, 4]); + const confirmed = { ...step, step: 1, inboxConsumedSeq: 2, inboxAcknowledgedRows: [witness] }; + expect(await ledger.step(id, gen, confirmed, [], session)).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([3, 4]); + expect(await ledger.step(id, gen, confirmed, [], session)).toEqual({ ok: true }); + expect( + await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 0, inboxDeferredSeqs: [1] }, [], session), + ).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([3, 4]); + }); + + it("refuses false normal-row proof and cannot settle source evidence through it", async () => { + const { ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + const normal = observed.items.find((item) => item.seq === 1)!.witness; + const source = observed.items.find((item) => item.seq === 2)!.witness; + for (const witnesses of [ + [source], + [{ ...normal, digest: "0".repeat(64) }], + [{ ...normal, runId: "foreign" }], + [normal, normal], + ]) { + const report = { ...step, step: 1, inboxConsumedSeq: 4, inboxAcknowledgedRows: witnesses }; + expect(await ledger.step(id, gen, report, [], session)).toEqual({ ok: false, reason: "fenced" }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + } + }); + + it("uses positive normal proof without consuming another row below the proposed cursor", async () => { + const { ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + const witness = observed.items[0]!.witness; + expect( + await ledger.step( + id, + gen, + { ...step, step: 1, inboxConsumedSeq: 4, inboxAcknowledgedRows: [witness] }, + [], + session, + ), + ).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([2, 3, 4]); + expect(await ledger.step(id, gen, { ...step, step: 1, inboxConsumedSeq: 4 }, [], session)).toEqual({ + ok: false, + reason: "fenced", + }); + expect(await unread(ledger, id)).toEqual([2, 3, 4]); + }); + + it("keeps normal-only confirmation monotonic through later reports with no new proof", async () => { + const { ledger, id, gen, step, session } = await fixture(); + ledger.inbox.set( + id, + ledger.inbox.get(id)!.filter((item) => item.seq === 1 || item.seq === 3), + ); + delete ledger.live.get(id)!.state.sourceInputIntents; + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + expect( + await ledger.step( + id, + gen, + { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, + [], + session, + ), + ).toEqual({ ok: true }); + expect(await unread(ledger, id)).toEqual([3]); + for (const n of [2, 3, 4]) { + expect( + await ledger.step( + id, + gen, + { ...step, step: n, inboxConsumedSeq: n === 2 ? 4 : 0, inboxDeferredSeqs: [1] }, + [], + session, + ), + ).toEqual({ + ok: true, + }); + expect(await unread(ledger, id)).toEqual([3]); + } + }); + + it("holds changed original rows and ownership races during normal confirmation", async () => { + for (const change of ["row", "owner"] as const) { + const { ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + const report = { ...step, step: 1, inboxConsumedSeq: 4, inboxAcknowledgedRows: [observed.items[0]!.witness] }; + if (change === "row") ledger.inbox.get(id)![0]!.message.text = "replacement row"; + const saving = ledger.step(id, gen, report, [], session); + if (change === "owner") expect(await ledger.handoff(gen, [id])).toEqual({ marked: [id] }); + expect(await saving).toEqual({ ok: false, reason: "fenced" }); + if (change === "owner") { + expect((await ledger.reclaim("g2", 20000, 10000))[0]?.row.ownerGen).toBe("g2"); + expect(await unread(ledger, id, "g2")).toEqual([1, 2, 3, 4]); + } else expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + } + }); + + it("compares the original row and owner again after an asynchronous digest", async () => { + for (const change of ["row", "owner"] as const) { + const { ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + let release!: () => void, entered!: () => void; + const started = new Promise((resolve) => { + entered = resolve; + }); + const pending = new Promise((resolve) => { + release = resolve; + }); + const digest = crypto.subtle.digest.bind(crypto.subtle); + const spy = vi.spyOn(crypto.subtle, "digest").mockImplementationOnce(async (...args) => { + entered(); + await pending; + return digest(...args); + }); + try { + const saving = ledger.step( + id, + gen, + { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, + [], + session, + ); + await started; + if (change === "row") ledger.inbox.get(id)![0]!.message.text = "changed during confirmation"; + else expect(await ledger.handoff(gen, [id])).toEqual({ marked: [id] }); + release(); + expect(await saving).toEqual({ ok: false, reason: "fenced" }); + } finally { + release(); + spy.mockRestore(); + } + } + }); + + it("preserves a committed normal receipt when a later exact source ACK changes the cursor", async () => { + const { ledger, id, gen, receipt, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + expect( + await ledger.step( + id, + gen, + { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, + [], + session, + ), + ).toEqual({ ok: true }); + const committed = await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + if (!committed.ok || !committed.checkpoint) throw new Error("missing checkpoint"); + expect( + await ledger.sourceInputCheckpoint(id, gen, { + operation: "ack", + inputId: receipt.inputId, + receiptHash: committed.checkpoint.receiptHash, + }), + ).toMatchObject({ ok: true }); + expect(await unread(ledger, id)).toEqual([3, 4]); + const last = await ledger.peekInbox(id, gen, 0); + expect(last.ok && (last.boundary.lastStep as StepRecord | null)?.inboxAcknowledgedRows).toEqual([ + observed.items[0]!.witness, + ]); + }); + + it("refuses a legacy success reply without positive normal-row acknowledgment", async () => { + const { ledger, id, gen, step, session } = await fixture(); + const observed = await ledger.peekInbox(id, gen, 0); + if (!observed.ok) throw new Error("missing original inbox"); + for (const echo of [undefined, [], [{ ...observed.items[0]!.witness, digest: "a".repeat(64) }]]) { + let mutations = 0; + const wire = new WorkerRunLedger({ + baseUrl: "https://state.invalid", + token: "fixture", + storeKey: "runs:fixture", + fetch: async (input) => { + if (!String(input).endsWith("/runs/step")) return Response.json({ ok: true }); + mutations++; + return Response.json({ ok: true, ...(echo === undefined ? {} : { inboxAcknowledgedRows: echo }) }); + }, + }); + await expect( + wire.step(id, gen, { ...step, step: 1, inboxAcknowledgedRows: [observed.items[0]!.witness] }, [], session), + ).rejects.toMatchObject({ name: "UncertainStoreError" }); + expect(mutations).toBe(1); + } + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + }); + + it("reports only safe step protection refusal fields and leaves the prior boundary intact", async () => { + const { ledger, id, gen, step, session } = await fixture(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await ledger.step(id, gen, { ...step, step: 1 }, [], session)).toEqual({ ok: true }); + expect(warn.mock.calls).toEqual([]); + ledger.live.get(id)!.state.sourceInputIntents = { + version: 999, + native: "PRIVATE_NATIVE_SESSION", + input: "PRIVATE_INPUT_IDENTIFIER", + }; + expect(await ledger.step(id, gen, { ...step, step: 2, inboxConsumedSeq: 4 }, [], session)).toEqual({ + ok: false, + reason: "fenced", + }); + expect(warn.mock.calls).toEqual([ + ["[runs/step] source input protection refused", { runId: id, ownerGen: gen, step: 2, acknowledged: 0 }], + ]); + expect(ledger.steps.get(id)!.at(-1)).toMatchObject({ step: 1, inboxConsumedSeq: 0 }); + expect(await unread(ledger, id)).toEqual([1, 2, 3, 4]); + } finally { + warn.mockRestore(); + } + }); + + it("refuses a checkpoint when ownership changes while its digest is pending", async () => { + const { ledger, id, gen, receipt } = await fixture(); + const saving = ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt }); + expect(await ledger.handoff(gen, [id])).toEqual({ marked: [id] }); + expect(await saving).toEqual({ ok: false, reason: "fenced" }); + expect((await ledger.reclaim("g2", 20000, 10000))[0]?.row.ownerGen).toBe("g2"); + expect(await ledger.sourceInputCheckpoint(id, "g2", { operation: "read", inputId: receipt.inputId })).toEqual({ + ok: true, + checkpoint: null, + }); + expect(await unread(ledger, id, "g2")).toEqual([1, 2, 3, 4]); + }); + + it.each(["commit", "ack"] as const)( + "reads the original after a lost %s reply without repeating a mutation", + async (operation) => { + for (const committed of [false, true]) { + const { ledger, id, gen, receipt } = await fixture(); + if (operation === "ack") + expect(await ledger.sourceInputCheckpoint(id, gen, { operation: "commit", receipt })).toMatchObject({ + ok: true, + }); + let mutations = 0; + const wire = new WorkerRunLedger({ + baseUrl: "https://state.invalid", + token: "fixture", + storeKey: "runs:fixture", + fetch: async (_url, init) => { + const body = JSON.parse(String(init?.body)) as { request: SourceInputCheckpointRequest }; + if (body.request.operation === "read") + return Response.json(await ledger.sourceInputCheckpoint(id, gen, body.request)); + mutations++; + if (committed) await ledger.sourceInputCheckpoint(id, gen, body.request); + throw new TypeError("lost original response"); + }, + }); + const request: SourceInputCheckpointRequest = + operation === "commit" + ? { operation, receipt } + : { operation, inputId: receipt.inputId, receiptHash: await sourceHash(sourceSnapshot(receipt)) }; + await expect(wire.sourceInputCheckpoint(id, gen, request)).rejects.toThrow(); + expect(mutations).toBe(1); + const read = await wire.sourceInputCheckpoint(id, gen, { operation: "read", inputId: receipt.inputId }); + expect(read).toEqual({ + ok: true, + checkpoint: + operation === "commit" && !committed + ? null + : { + receipt, + receiptHash: await sourceHash(sourceSnapshot(receipt)), + taskHash: await sourceHash(null), + acknowledged: operation === "ack" && committed, + }, + }); + expect(await unread(ledger, id)).toEqual(operation === "ack" && committed ? [1, 3, 4] : [1, 2, 3, 4]); + expect(mutations).toBe(1); + } + }, + ); +}); diff --git a/src/core/runLedger/sourceInputIntent.ts b/src/core/runLedger/sourceInputIntent.ts index 866a84b0b..277abdfc8 100644 --- a/src/core/runLedger/sourceInputIntent.ts +++ b/src/core/runLedger/sourceInputIntent.ts @@ -1,3 +1,4 @@ +import { inboxAcknowledgedRowsOf } from "./inboxAcknowledgments.js"; import { isHarnessName, type HARNESS_NAMES } from "../harness/names.js"; import { harnessLaunchIntentOf } from "../harness/sessionPolicy.js"; import { @@ -9,7 +10,7 @@ import { sourceSnapshot } from "./sourceEvents.js"; import { DURABLE_INBOX_MAX_BYTES } from "./inboxMessage.js"; import { prepareSourceEvidenceMessage } from "./sourceEvidence.js"; import { sourceHash } from "../references/receipts.js"; -import type { InboxItem, InboxRowWitness, LiveRunRow, RunState } from "./types.js"; +import type { InboxItem, InboxRowWitness, LiveRunRow, RunState, StepRecord, FenceResult } from "./types.js"; import { isContextDependencies, mergeContextDependencies, @@ -30,11 +31,42 @@ export interface SourceInputIntent { renderedHash: string; } -export interface SourceInputIntents { +/** Native persistence evidence supplied by the trusted harness adapter, never + * source text or a provider response. sessionId is the original native locator. */ +export interface SourceInputAdmission { version: 1; + inputId: string; + intentHash: string; + native: { + harness: (typeof HARNESS_NAMES)[number]; + sessionId: string; + sessionIdentity: string; + entryId: string; + entryHash: string; + }; +} + +export interface SourceInputCheckpoint { + receipt: SourceInputAdmission; + receiptHash: string; + taskHash: string; + acknowledged: boolean; +} + +export interface SourceInputIntents { + version: 1 | 2; entries: SourceInputIntent[]; + /** Version 2 only. Older readers hold this whole private frame. */ + checkpoints?: SourceInputCheckpoint[]; } +export type SourceInputCheckpointRequest = + | { operation: "read"; inputId: string } + | { operation: "commit"; receipt: SourceInputAdmission } + | { operation: "ack"; inputId: string; receiptHash: string }; +export type SourceInputCheckpointResult = + { ok: true; checkpoint: SourceInputCheckpoint | null } | Extract; + export interface SourceInputRowBinding { seq: number; json: string; @@ -178,8 +210,9 @@ export function sourceInputArchiveState( return { sourceInputIntents: original, contextDependencies: context }; } -/** Both supported phases are unresolved. Unsupported retained data also stays - * protected; a decoder failure is never proof that the obligation ended. */ +/** Native ACK does not settle recipient obligations or transfer source pins. + * Unsupported retained data also stays protected; a decoder failure is never + * proof that the obligation ended. */ export const pendingSourceInputRetentionRequired = (record: { sourceInputIntents?: unknown }): boolean => record.sourceInputIntents !== undefined; @@ -197,8 +230,8 @@ export function sourceInputIntentsOf(value: unknown): SourceInputIntents | undef const v = sourceSnapshot(value); if ( !object(v) || - !closed(v, ["version", "entries"]) || - v.version !== 1 || + !closed(v, v.version === 2 ? ["version", "entries", "checkpoints"] : ["version", "entries"]) || + (v.version !== 1 && v.version !== 2) || !Array.isArray(v.entries) || v.entries.length === 0 || v.entries.length > 64 || @@ -277,7 +310,35 @@ export function sourceInputIntentsOf(value: unknown): SourceInputIntents | undef renderedHash: entry.renderedHash, }); } - return { version: 1, entries }; + if (v.version === 1) return { version: 1, entries }; + if (!Array.isArray(v.checkpoints) || v.checkpoints.length === 0 || v.checkpoints.length > entries.length) return; + const checkpoints: SourceInputCheckpoint[] = []; + const seen = new Set(); + const nativeRows = new Set(); + for (const raw of v.checkpoints) { + const checkpoint = sourceInputCheckpointOf(raw); + const entry = checkpoint && entries.find((entry) => entry.id === checkpoint.receipt.inputId); + if ( + !checkpoint || + !entry || + entry.phase !== "begun" || + seen.has(entry.id) || + checkpoint.receipt.native.harness !== entry.native.harness || + checkpoint.receipt.native.sessionId !== entry.native.sessionId + ) + return; + const nativeRow = JSON.stringify([ + checkpoint.receipt.native.harness, + checkpoint.receipt.native.sessionId, + checkpoint.receipt.native.sessionIdentity, + checkpoint.receipt.native.entryId, + ]); + if (nativeRows.has(nativeRow)) return; + nativeRows.add(nativeRow); + seen.add(entry.id); + checkpoints.push(checkpoint); + } + return { version: 2, entries, checkpoints }; } catch { return; } @@ -319,6 +380,10 @@ export function preserveSourceInputIntents( const before = oldRaw === undefined ? undefined : sourceInputIntentsOf(oldRaw); const after = nextRaw === undefined ? before : sourceInputIntentsOf(nextRaw); if ((oldRaw !== undefined && !before) || !after) return refuse("invalid-metadata"); + // Only the dedicated store transaction can mint or acknowledge a checkpoint. + // Omission preserves canonical proof; an explicit stale replacement refuses. + if (nextRaw !== undefined && JSON.stringify(after.checkpoints ?? []) !== JSON.stringify(before?.checkpoints ?? [])) + return refuse("original-changed"); for (const old of before?.entries ?? []) { const next = after.entries.find((entry) => entry.id === old.id); if ( @@ -344,3 +409,248 @@ export function preserveSourceInputIntents( } return { ...incoming, sourceInputIntents: after }; } + +export function sourceInputAdmissionOf(value: unknown): SourceInputAdmission | undefined { + try { + const v = sourceSnapshot(value); + if ( + !object(v) || + !closed(v, ["version", "inputId", "intentHash", "native"]) || + v.version !== 1 || + !text(v.inputId) || + !hash(v.intentHash) || + !object(v.native) + ) + return; + const n = v.native; + if ( + !closed(n, ["harness", "sessionId", "sessionIdentity", "entryId", "entryHash"]) || + !isHarnessName(n.harness) || + !text(n.sessionId, 4096) || + !text(n.sessionIdentity) || + !text(n.entryId) || + !hash(n.entryHash) + ) + return; + return { + version: 1, + inputId: v.inputId, + intentHash: v.intentHash, + native: { + harness: n.harness, + sessionId: n.sessionId, + sessionIdentity: n.sessionIdentity, + entryId: n.entryId, + entryHash: n.entryHash, + }, + }; + } catch { + return; + } +} + +export function sourceInputCheckpointOf(value: unknown): SourceInputCheckpoint | undefined { + try { + const v = sourceSnapshot(value); + if ( + !object(v) || + !closed(v, ["receipt", "receiptHash", "taskHash", "acknowledged"]) || + !hash(v.receiptHash) || + !hash(v.taskHash) || + typeof v.acknowledged !== "boolean" + ) + return; + const receipt = sourceInputAdmissionOf(v.receipt); + return receipt + ? { receipt, receiptHash: v.receiptHash, taskHash: v.taskHash, acknowledged: v.acknowledged } + : undefined; + } catch { + return; + } +} + +export function sourceInputCheckpointRequestOf(value: unknown): SourceInputCheckpointRequest | undefined { + try { + const v = sourceSnapshot(value); + if (!object(v)) return; + if (v.operation === "commit" && closed(v, ["operation", "receipt"])) { + const receipt = sourceInputAdmissionOf(v.receipt); + return receipt ? { operation: "commit", receipt } : undefined; + } + if (v.operation === "read" && closed(v, ["operation", "inputId"]) && text(v.inputId)) + return { operation: "read", inputId: v.inputId }; + if ( + v.operation === "ack" && + closed(v, ["operation", "inputId", "receiptHash"]) && + text(v.inputId) && + hash(v.receiptHash) + ) + return { operation: "ack", inputId: v.inputId, receiptHash: v.receiptHash }; + } catch { + return; + } +} + +/** Preserve unrelated unread rows when an exact ACK raises the cursor. Ordinary + * step reports cannot bypass pending source rows or resurrect acknowledged ones. */ +export function protectSourceInputStep( + state: RunState, + record: StepRecord, + inbox: readonly InboxItem[], + prior?: StepRecord, + verifiedNormalRows: readonly InboxRowWitness[] = [], +): StepRecord | undefined { + const raw = state.sourceInputIntents; + const inputs = raw === undefined ? undefined : sourceInputIntentsOf(raw); + if (raw !== undefined && !inputs) return; + const normal = + record.inboxAcknowledgedRows === undefined ? [] : inboxAcknowledgedRowsOf(record.inboxAcknowledgedRows); + const verified = inboxAcknowledgedRowsOf([...verifiedNormalRows]); + if (!normal || !verified || JSON.stringify(normal) !== JSON.stringify(verified)) return; + if ( + raw === undefined && + record.inboxAcknowledgedRows === undefined && + prior?.inboxAcknowledgedRows === undefined && + !inbox.some((item) => item.message.kind === "source-evidence" && item.message.version === 2) + ) + return record; + const acknowledged = new Set( + inputs?.entries + .filter((entry) => + inputs.checkpoints?.some((checkpoint) => checkpoint.receipt.inputId === entry.id && checkpoint.acknowledged), + ) + .map((entry) => entry.witness.seq), + ); + const normalSeqs = new Set(normal.map((witness) => witness.seq)); + const consumed = Math.max(record.inboxConsumedSeq, prior?.inboxConsumedSeq ?? 0, ...acknowledged, ...normalSeqs); + const deferred = new Set(record.inboxDeferredSeqs ?? []); + if ( + inputs?.checkpoints?.length || + record.inboxAcknowledgedRows !== undefined || + prior?.inboxAcknowledgedRows !== undefined + ) + for (const seq of prior?.inboxDeferredSeqs ?? []) deferred.add(seq); + for (const item of inbox) { + if (item.seq > consumed) continue; + if (acknowledged.has(item.seq) || normalSeqs.has(item.seq)) deferred.delete(item.seq); + else if ( + prior && + item.seq <= prior.inboxConsumedSeq && + !prior.inboxDeferredSeqs?.includes(item.seq) && + item.message.kind !== "source-evidence" + ) + deferred.delete(item.seq); + else if ( + record.inboxAcknowledgedRows !== undefined || + prior?.inboxAcknowledgedRows !== undefined || + item.seq > record.inboxConsumedSeq || + (item.message.kind === "source-evidence" && item.message.version === 2) + ) + deferred.add(item.seq); + } + for (const entry of inputs?.entries ?? []) { + if (entry.witness.seq <= consumed && !acknowledged.has(entry.witness.seq)) deferred.add(entry.witness.seq); + } + for (const seq of [...acknowledged, ...normalSeqs]) deferred.delete(seq); + const next = { + ...record, + ...(record.inboxAcknowledgedRows === undefined && prior?.inboxAcknowledgedRows === undefined + ? {} + : { inboxAcknowledgedRows: normal }), + inboxConsumedSeq: consumed, + ...(deferred.size || record.inboxDeferredSeqs !== undefined + ? { inboxDeferredSeqs: [...deferred].sort((a, b) => a - b) } + : {}), + }; + return new TextEncoder().encode(JSON.stringify(next.inboxDeferredSeqs ?? [])).byteLength <= DURABLE_INBOX_MAX_BYTES + ? next + : undefined; +} + +/** Prepare a fenced store transition. The caller compares the complete row, + * inbox and prior step again in its final synchronous transaction. No native + * operation or retry is performed here; read is the only unknown-write recovery. */ +export async function prepareSourceInputCheckpoint( + row: LiveRunRow, + request: SourceInputCheckpointRequest, + inbox: readonly InboxItem[], + lastStep: StepRecord | undefined, +): Promise<{ state: RunState; step?: StepRecord; checkpoint: SourceInputCheckpoint | null } | undefined> { + const inputs = sourceInputIntentsOf(row.state.sourceInputIntents); + const id = request.operation === "commit" ? request.receipt.inputId : request.inputId; + if (!inputs) return; + const original = inputs.entries.find((entry) => entry.id === id); + if (!original) return; + const saved = inputs.checkpoints?.find((entry) => entry.receipt.inputId === id); + if ( + saved && + (saved.receipt.intentHash !== (await sourceHash(sourceSnapshot(original))) || + saved.receiptHash !== (await sourceHash(sourceSnapshot(saved.receipt)))) + ) + return; + if (request.operation === "read") return { state: row.state, checkpoint: saved ?? null }; + if ( + row.phase !== "live" || + original.phase !== "begun" || + original.owner.runId !== row.runId || + original.owner.requester !== row.meta.userId || + original.owner.channelId !== row.meta.channelId || + original.owner.threadKey !== row.meta.threadKey + ) + return; + if (request.operation === "commit" && saved) { + return JSON.stringify(sourceSnapshot(request.receipt)) === JSON.stringify(sourceSnapshot(saved.receipt)) + ? { state: row.state, checkpoint: saved } + : undefined; + } + if (request.operation === "ack" && (!saved || saved.receiptHash !== request.receiptHash)) return; + if (request.operation === "ack" && saved?.acknowledged) return { state: row.state, checkpoint: saved }; + if (!sourceInputNativeMatches(row.state, original)) return; + const taskHash = await sourceHash(sourceSnapshot(row.state.sourceTask ?? null)); + if (saved && saved.taskHash !== taskHash) return; + const item = inbox.find((item) => item.seq === original.witness.seq); + if ( + !item || + (lastStep && item.seq <= lastStep.inboxConsumedSeq && !lastStep.inboxDeferredSeqs?.includes(item.seq)) || + (await sourceHash(item.message)) !== original.witness.digest + ) + return; + const context = row.state.contextDependencies; + if ( + !isContextDependencies(context) || + context.status !== "known" || + !context.sourceInputs?.some( + (reference) => JSON.stringify(sourceSnapshot(reference)) === JSON.stringify(sourceSnapshot(original.reference)), + ) + ) + return; + let checkpoint: SourceInputCheckpoint; + if (request.operation === "commit") { + const receipt = sourceInputAdmissionOf(request.receipt); + if ( + !receipt || + receipt.intentHash !== (await sourceHash(sourceSnapshot(original))) || + receipt.native.harness !== original.native.harness || + receipt.native.sessionId !== original.native.sessionId + ) + return; + checkpoint = { receipt, receiptHash: await sourceHash(sourceSnapshot(receipt)), taskHash, acknowledged: false }; + } else { + if (!saved) return; + checkpoint = { ...saved, acknowledged: true }; + } + const after = sourceInputIntentsOf({ + version: 2, + entries: inputs.entries, + checkpoints: [...(inputs.checkpoints ?? []).filter((entry) => entry.receipt.inputId !== id), checkpoint], + }); + if (!after) return; + const state = { ...row.state, sourceInputIntents: after }; + if (request.operation === "ack") { + if (!lastStep) return; + const step = protectSourceInputStep(state, lastStep, inbox, lastStep, lastStep.inboxAcknowledgedRows ?? []); + if (!step) return; + return { state, step, checkpoint }; + } + return { state, checkpoint }; +} diff --git a/src/core/runLedger/types.ts b/src/core/runLedger/types.ts index 009332da7..3994a3434 100644 --- a/src/core/runLedger/types.ts +++ b/src/core/runLedger/types.ts @@ -259,6 +259,8 @@ export interface StepRecord { /** Seqs at or below `inboxConsumedSeq` the run has not consumed yet: a * reclaim offers them again with every row past the cursor. */ inboxDeferredSeqs?: number[]; + /** Exact original non-source rows positively accepted by this step's native/control path. */ + inboxAcknowledgedRows?: InboxRowWitness[]; remainingMs: number; turn: number; iteration: number; diff --git a/src/core/runLedger/writeThrough.test.ts b/src/core/runLedger/writeThrough.test.ts index 7e65d4054..952f30fe2 100644 --- a/src/core/runLedger/writeThrough.test.ts +++ b/src/core/runLedger/writeThrough.test.ts @@ -1,4 +1,10 @@ import { describe, expect, it, vi } from "vitest"; +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SessionManager } from "@earendil-works/pi-coding-agent"; +import { checkpointPiSourceInput } from "../harness/pi/sourceInputCheckpoint.js"; import { captureSourceTaskSnapshot } from "../references/sourceTaskSnapshot.js"; import { testSourceInputIntent, seedSourceInputIntent } from "../testing/sourceInputs.js"; import { readSourceInputProof } from "../references/sourceInputProof.js"; @@ -14,6 +20,10 @@ import { storeRequestWitness } from "../storeResponse.js"; import { rememberStorageFailure } from "../storageFailureDiagnostic.js"; import * as receipts from "../references/receipts.js"; import { InMemoryRunLedger } from "./inMemory.js"; +import { unreadInbox } from "./decisions.js"; +import { sourceSnapshot } from "./sourceEvents.js"; +import type { StepRecord } from "./types.js"; +import { durableInboxMessage } from "./inboxMessage.js"; import { WorkerRunLedger } from "../runLedgerWorker.js"; import { PromotionPendingError } from "./promotion.js"; import { UNKNOWN_CONTEXT_DEPENDENCIES } from "../references/contextDependencies.js"; @@ -1291,7 +1301,84 @@ describe("mintGeneration", () => { }); describe("source input admission", () => { - async function fixture(harnessName: "pi" | "opencode" = "pi") { + it("reconciles an adopted normal settlement after a lost stale-step reply without offering it again", async () => { + const f = harness(); + const run = (await openRun(f.wt, openReq()))!; + await f.ledger.pushInbox("r1", { text: "confirmed ordinary input" }); + const before = await f.ledger.peekInbox("r1", "gen-A", 0); + if (!before.ok) throw new Error("missing original inbox"); + const original = before.items[0]!; + run.confirmInboxInputs([ + { + text: "confirmed ordinary input", + userId: "slack:UALICE", + at: 1, + ledgerSeq: 1, + ledgerWitness: original.witness, + }, + ]); + await run.step(step({ inboxConsumedSeq: 1 })); + const legacy = await f.ledger.peekInbox("r1", "gen-A", 0); + expect(legacy.ok && legacy.boundary.lastStep).toMatchObject({ step: 1, inboxConsumedSeq: 1 }); + expect(legacy.ok && (legacy.boundary.lastStep as StepRecord).inboxAcknowledgedRows).toBeUndefined(); + if (!legacy.ok) throw new Error("missing committed legacy step"); + expect( + await f.ledger.step( + "r1", + "gen-A", + { ...(legacy.boundary.lastStep as StepRecord), step: 2, inboxAcknowledgedRows: [original.witness] }, + [], + run.session!.key, + ), + ).toMatchObject({ ok: true }); + await f.ledger.pushInbox("r1", { text: "still owed" }); + const row = f.ledger.live.get("r1")!; + const session = run.session; + await run.close(); + const adopted = f.wt.adopt({ + runId: "r1", + threadKey: row.threadKey, + meta: row.meta, + state: row.state, + lastStep: 2, + lastSeq: 0, + session, + durableTurns: 4, + }); + const execute = f.ledger.step.bind(f.ledger); + const replacing = vi.spyOn(f.ledger, "step").mockImplementation(async (...args) => { + await execute(...args); + throw new UncertainStoreError( + "adopted step reply lost", + await storeRequestWitness("/runs/step", JSON.stringify({ runId: args[0], gen: args[1], record: args[2] })), + ); + }); + try { + await adopted.step(step({ firstIdx: 4, turn: 2, inboxConsumedSeq: 0, inboxDeferredSeqs: [1] })); + expect(adopted.writeBoundaryFailure).toMatchObject({ kind: "step", step: 3 }); + expect(await adopted.commitState({ progress: "original step read back" })).toBe("ok"); + const after = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + after.ok && after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord)).map((item) => item.seq), + ).toEqual([2]); + expect(after.ok && after.boundary.lastStep).toMatchObject({ + inboxConsumedSeq: 1, + inboxDeferredSeqs: [], + inboxAcknowledgedRows: [], + }); + expect(adopted.writeBoundaryFailure).toBeUndefined(); + } finally { + replacing.mockRestore(); + await adopted.close(); + } + }); + + async function fixture( + harnessName: "pi" | "opencode" = "pi", + native?: { sessionId: string; renderedHash: string }, + prefixNormal = false, + confirmBeforeSourceFrame = false, + ) { const inner = new InMemoryRunLedger(() => 10_000); const h = harness({ ledger: inner }); const req = openReq({ meta: { ...openReq().meta, agent: "orchestrator" } }); @@ -1299,6 +1386,10 @@ describe("source input admission", () => { const run = (await openRun(h.wt, req))!; const input = testSourceInputIntent(harnessName), entry = input.entries[0]!; + if (native) { + entry.native.sessionId = native.sessionId; + entry.renderedHash = native.renderedHash; + } entry.owner = { runId: "r1", gen: "gen-A", @@ -1320,7 +1411,29 @@ describe("source input admission", () => { }, }), ).toBe("ok"); + if (prefixNormal) + await inner.pushInbox( + "r1", + durableInboxMessage( + { channelId: "slack:C1", userId: "slack:UALICE", threadKey: "slack:C1:1.0", text: "Ordinary follow-up" }, + "Ordinary follow-up", + 1, + ), + ); const original = await seedSourceInputIntent(inner, input); + if (confirmBeforeSourceFrame) { + const observed = await inner.peekInbox("r1", "gen-A", 0); + if (!observed.ok) throw new Error("missing original normal row"); + run.confirmInboxInputs([ + { + text: "Ordinary follow-up", + userId: "slack:UALICE", + at: 1, + ledgerSeq: 1, + ledgerWitness: observed.items.find((item) => item.seq === 1)!.witness, + }, + ]); + } expect(await run.commitState({ sourceInputIntents: original })).toBe("ok"); let allowed = true; const validate = async (context: ContextDependencies) => { @@ -1341,6 +1454,585 @@ describe("source input admission", () => { }; } + it("checks checkpoint reader capability without beginning or acknowledging the input", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.sourceInputCheckpoint({ operation: "read", inputId: entry.id }, f.validate)).toEqual({ + ok: true, + checkpoint: null, + }); + expect(f.ledger.live.get("r1")?.state.sourceInputIntents).toEqual(f.original); + const peek = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + peek.ok && peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([1]); + } finally { + await f.run.close(); + } + }); + + it.each(["confirmed", "lost-reply", "before-source-frame"])( + "settles an original normal echo after source ACK without resurrecting it: boundary=%s", + async (boundary) => { + let lostReply = boundary === "lost-reply"; + const f = await fixture("pi", undefined, true, boundary === "before-source-frame"); + try { + const observed = await f.ledger.peekInbox("r1", "gen-A", 0); + if (!observed.ok) throw new Error("missing original inbox"); + const normal = observed.items.find((item) => item.seq === 1)!; + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "source-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + const pending = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + pending.ok && + pending.items.filter(unreadInbox(pending.boundary.lastStep as StepRecord)).map((item) => item.seq), + ).toEqual([1]); + if (boundary !== "before-source-frame") + f.run.confirmInboxInputs([ + { text: "Ordinary follow-up", userId: "slack:UALICE", at: 1, ledgerSeq: 1, ledgerWitness: normal.witness }, + ]); + const writes: StepRecord[] = []; + const execute = f.ledger.step.bind(f.ledger); + const replacing = vi.spyOn(f.ledger, "step").mockImplementation(async (...args) => { + writes.push(structuredClone(args[2])); + const result = await execute(...args); + if (lostReply) { + lostReply = false; + throw new UncertainStoreError( + "normal settlement reply lost", + await storeRequestWitness( + "/runs/step", + JSON.stringify({ runId: args[0], gen: args[1], record: args[2] }), + ), + ); + } + return result; + }); + await f.run.step(step({ inboxConsumedSeq: 1 })); + expect(await f.run.commitState({ progress: "after exact original readback" })).toBe("ok"); + await f.run.step(step({ firstIdx: 4, turn: 2, inboxConsumedSeq: 0, inboxDeferredSeqs: [1] })); + const after = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + after.ok && after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord)).map((item) => item.seq), + ).toEqual([]); + expect(writes.map((record) => record.inboxAcknowledgedRows ?? [])).toEqual([[normal.witness], []]); + expect(f.run.writeBoundaryFailure).toBeUndefined(); + replacing.mockRestore(); + } finally { + await f.run.close(); + } + }, + ); + + it("retains a first normal confirmation that arrives during an earlier source step read", async () => { + const f = await fixture("pi", undefined, true); + let release = () => {}; + let replacing: ReturnType | undefined; + try { + const original = await f.ledger.peekInbox("r1", "gen-A", 0); + if (!original.ok) throw new Error("missing original inbox"); + const normal = original.items.find((item) => item.seq === 1)!; + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "source-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + let entered = () => {}; + const readEntered = new Promise((resolve) => { + entered = resolve; + }); + const readRelease = new Promise((resolve) => { + release = resolve; + }); + const execute = f.ledger.peekInbox.bind(f.ledger); + replacing = vi.spyOn(f.ledger, "peekInbox").mockImplementation(async (...args) => { + entered(); + await readRelease; + return execute(...args); + }); + const earlier = f.run.step(step()); + await readEntered; + f.run.confirmInboxInputs([ + { text: "Ordinary follow-up", userId: "slack:UALICE", at: 1, ledgerSeq: 1, ledgerWitness: normal.witness }, + ]); + release(); + await earlier; + replacing.mockRestore(); + await f.run.step(step({ firstIdx: 4, turn: 2, inboxConsumedSeq: 1 })); + const after = await f.ledger.peekInbox("r1", "gen-A", 0); + expect(after.ok && after.boundary.lastStep).toMatchObject({ + inboxConsumedSeq: 2, + inboxAcknowledgedRows: [normal.witness], + }); + expect( + after.ok && after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord)).map((item) => item.seq), + ).toEqual([]); + } finally { + release(); + replacing?.mockRestore(); + await f.run.close(); + } + }); + + it("settles the original installed Pi session entry through canonical readback and exact ACK", async () => { + const root = mkdtempSync(join(tmpdir(), "switchboard-pi-checkpoint-")); + const manager = SessionManager.create(root, join(root, "sessions")); + manager.appendMessage({ role: "user", content: "Synthetic seed", timestamp: 1 }); + const path = manager.getSessionFile()!, + text = "Synthetic source input."; + const f = await fixture("pi", { sessionId: path, renderedHash: createHash("sha256").update(text).digest("hex") }); + try { + const entry = { ...structuredClone(f.original.entries[0]!), phase: "begun" as const }; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + manager.appendCustomMessageEntry("switchboard-source-input", text, false, { version: 1, intent: entry }); + const content = readFileSync(path, "utf8"); + const native = manager.getEntries().find((row) => row.type === "custom_message"); + if (!native) throw new Error("missing actual native entry"); + expect(await checkpointPiSourceInput(entry, { path: path + ".copy", content }, f.run, f.validate)).toBe(false); + const before = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + before.ok && + before.items.filter(unreadInbox(before.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([1]); + expect(await checkpointPiSourceInput(entry, { path, content }, f.run, f.validate)).toBe(true); + expect( + await f.ledger.sourceInputCheckpoint("r1", "gen-A", { operation: "read", inputId: entry.id }), + ).toMatchObject({ + ok: true, + checkpoint: { + acknowledged: true, + receipt: { inputId: entry.id, native: { harness: "pi", sessionId: path, entryId: native.id } }, + }, + }); + const after = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + after.ok && + after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([]); + const reopened = SessionManager.open(path); + expect(reopened.getEntries()).toEqual(manager.getEntries()); + expect( + await checkpointPiSourceInput(entry, { path, content: readFileSync(path, "utf8") }, f.run, f.validate), + ).toBe(true); + expect(readFileSync(path, "utf8")).toBe(content); + } finally { + await f.run.close(); + rmSync(root, { recursive: true, force: true }); + } + }); + + it("reads a native checkpoint before exact ACK and preserves it in later host state", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + expect(saved).toMatchObject({ ok: true, checkpoint: { receipt, acknowledged: false } }); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + const peek = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + peek.ok && peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([1]); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + expect(await f.run.commitState({ progress: "later host state" })).toBe("ok"); + expect(await f.run.sourceInputCheckpoint({ operation: "read", inputId: entry.id }, f.validate)).toMatchObject({ + ok: true, + checkpoint: { receipt, acknowledged: true }, + }); + const after = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + after.ok && + after.items.filter(unreadInbox(after.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([]); + } finally { + await f.run.close(); + } + }); + + it("holds native checkpoint changes after source access is revoked", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + expect(saved).toMatchObject({ ok: true, checkpoint: { acknowledged: false } }); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + f.revoke(); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toEqual({ ok: false, reason: "unavailable" }); + const peek = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + peek.ok && peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual([1]); + } finally { + await f.run.close(); + } + }); + + it.each(["commit", "ack"] as const)( + "reconciles a lost host %s reply without repeating its mutation", + async (operation) => { + for (const committed of [false, true]) { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + let receiptHash = ""; + if (operation === "ack") { + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + expect(saved).toMatchObject({ ok: true, checkpoint: { acknowledged: false } }); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + receiptHash = saved.checkpoint.receiptHash; + } + let mutations = 0; + const execute = f.ledger.sourceInputCheckpoint.bind(f.ledger); + const replacing = vi.spyOn(f.ledger, "sourceInputCheckpoint").mockImplementation(async (...args) => { + if (args[2].operation !== operation) return execute(...args); + mutations++; + if (committed) await execute(...args); + throw new UncertainStoreError( + "original checkpoint reply lost", + await storeRequestWitness( + "/runs/source-input/checkpoint", + JSON.stringify({ runId: args[0], gen: args[1], request: args[2] }), + ), + ); + }); + const result = await f.run.sourceInputCheckpoint( + operation === "commit" ? { operation, receipt } : { operation, inputId: entry.id, receiptHash }, + f.validate, + ); + expect(result).toMatchObject( + committed + ? { ok: true, checkpoint: { receipt, acknowledged: operation === "ack" } } + : { ok: false, reason: "unavailable" }, + ); + expect(mutations).toBe(1); + const peek = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + peek.ok && + peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual(operation === "ack" && committed ? [] : [1]); + replacing.mockRestore(); + } finally { + await f.run.close(); + } + } + }, + ); + + it("retains a still-running checkpoint mutation through a null read and later ordinary writes", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + const execute = f.ledger.sourceInputCheckpoint.bind(f.ledger); + let late: (() => Promise) | undefined, + mutations = 0; + const replacing = vi.spyOn(f.ledger, "sourceInputCheckpoint").mockImplementation(async (...args) => { + if (args[2].operation !== "commit") return execute(...args); + mutations++; + late = () => execute(...args); + throw new UncertainStoreError( + "original still in flight", + await storeRequestWitness( + "/runs/source-input/checkpoint", + JSON.stringify({ runId: args[0], gen: args[1], request: args[2] }), + ), + ); + }); + const request = { operation: "commit" as const, receipt }; + expect(await f.run.sourceInputCheckpoint(request, f.validate)).toEqual({ ok: false, reason: "unavailable" }); + expect(f.run.writeBoundaryFailure).toMatchObject({ kind: "source-input-checkpoint", runId: "r1", gen: "gen-A" }); + expect(await f.run.commitState({ progress: "held pending original" })).toBe("unavailable"); + expect(await f.run.sourceInputCheckpoint(request, f.validate)).toEqual({ ok: false, reason: "unavailable" }); + expect(mutations).toBe(1); + if (!late) throw new Error("missing original in-flight mutation"); + expect(await late()).toMatchObject({ ok: true, checkpoint: { acknowledged: false } }); + expect(await f.run.sourceInputCheckpoint({ operation: "read", inputId: entry.id }, f.validate)).toMatchObject({ + ok: true, + checkpoint: { receipt, acknowledged: false }, + }); + expect(f.run.writeBoundaryFailure).toBeUndefined(); + expect(await f.run.commitState({ progress: "original reconciled" })).toBe("ok"); + expect(mutations).toBe(1); + replacing.mockRestore(); + } finally { + await f.run.close(); + } + }); + + it.each([false, true])("checks access after the final ACK prerequisite read: revoked=%s", async (revoked) => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + expect(saved).toMatchObject({ ok: true, checkpoint: { acknowledged: false } }); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + const execute = f.ledger.sourceInputCheckpoint.bind(f.ledger); + const replacing = vi.spyOn(f.ledger, "sourceInputCheckpoint").mockImplementation(async (...args) => { + const result = await execute(...args); + if (revoked && args[2].operation === "read") f.revoke(); + return result; + }); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toMatchObject( + revoked ? { ok: false, reason: "unavailable" } : { ok: true, checkpoint: { acknowledged: true } }, + ); + const peek = await f.ledger.peekInbox("r1", "gen-A", 0); + expect( + peek.ok && peek.items.filter(unreadInbox(peek.boundary.lastStep as StepRecord | null)).map((item) => item.seq), + ).toEqual(revoked ? [1] : []); + replacing.mockRestore(); + } finally { + await f.run.close(); + } + }); + + it("retains a landed checkpoint before returning a later access hold", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + let checks = 0; + const validate = async (context: ContextDependencies) => { + if (++checks === 3) f.revoke(); + return f.validate(context); + }; + expect(await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, validate)).toEqual({ + ok: false, + reason: "unavailable", + }); + expect(await f.run.commitState({ progress: "metadata retained while access is held" })).toBe("ok"); + expect( + await f.ledger.sourceInputCheckpoint("r1", "gen-A", { operation: "read", inputId: entry.id }), + ).toMatchObject({ ok: true, checkpoint: { receipt, acknowledged: false } }); + } finally { + await f.run.close(); + } + }); + + it("begins another original without dropping the earlier canonical checkpoint", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + expect(await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate)).toMatchObject({ + ok: true, + checkpoint: { receipt, acknowledged: false }, + }); + const second = testSourceInputIntent(); + second.entries[0] = { ...structuredClone(entry), id: "source-input-two", phase: "prepared" }; + const next = await seedSourceInputIntent(f.ledger, second); + const original = f.ledger.live.get("r1")!.state.sourceInputIntents as typeof next; + expect( + await f.run.commitState({ + sourceInputIntents: { ...original, entries: [...original.entries, ...next.entries] }, + }), + ).toBe("ok"); + expect(await f.run.beginSourceInput("source-input-two", f.validate)).toBe(true); + expect(f.ledger.live.get("r1")?.state.sourceInputIntents).toMatchObject({ + version: 2, + entries: [ + { id: entry.id, phase: "begun" }, + { id: "source-input-two", phase: "begun" }, + ], + checkpoints: [{ receipt, acknowledged: false }], + }); + } finally { + await f.run.close(); + } + }); + + it("reconciles the exact protected step after an ACK and a lost step reply", async () => { + const f = await fixture(); + try { + const entry = f.original.entries[0]!; + expect(await f.run.beginSourceInput(entry.id, f.validate)).toBe(true); + const receipt = { + version: 1 as const, + inputId: entry.id, + intentHash: await receipts.sourceHash(sourceSnapshot({ ...entry, phase: "begun" })), + native: { + harness: "pi" as const, + sessionId: entry.native.sessionId, + sessionIdentity: "original-session-header", + entryId: "original-native-entry", + entryHash: "b".repeat(64), + }, + }; + const saved = await f.run.sourceInputCheckpoint({ operation: "commit", receipt }, f.validate); + if (!saved.ok || !saved.checkpoint) throw new Error("missing native checkpoint"); + expect( + await f.run.sourceInputCheckpoint( + { operation: "ack", inputId: entry.id, receiptHash: saved.checkpoint.receiptHash }, + f.validate, + ), + ).toMatchObject({ ok: true, checkpoint: { acknowledged: true } }); + let loseReply = true; + const writes: StepRecord[] = [], + execute = f.ledger.step.bind(f.ledger); + const replacing = vi.spyOn(f.ledger, "step").mockImplementation(async (...args) => { + writes.push(structuredClone(args[2])); + const result = await execute(...args); + if (loseReply) + throw new UncertainStoreError( + "protected step reply lost", + await storeRequestWitness("/runs/step", JSON.stringify({ runId: args[0], gen: args[1], record: args[2] })), + ); + return result; + }); + await f.run.step(step()); + expect(f.run.writeBoundaryFailure).toMatchObject({ kind: "step", step: 1 }); + loseReply = false; + await f.run.step(step({ firstIdx: 4, turn: 2 })); + expect(f.run.writeBoundaryFailure).toBeUndefined(); + expect(writes.map((record) => ({ step: record.step, inboxConsumedSeq: record.inboxConsumedSeq }))).toEqual([ + { step: 1, inboxConsumedSeq: 1 }, + { step: 2, inboxConsumedSeq: 1 }, + ]); + replacing.mockRestore(); + } finally { + await f.run.close(); + } + }); + it.each(["pi", "opencode"] as const)( "retains the exact %s source before beginning its original input", async (native) => { @@ -3287,10 +3979,17 @@ describe("events, state, heartbeat", () => { plane: { steer: "reissue", provider: "anthropic" }, }, }; - expect(deliverPlaneSteer(effect, { runId: "r1", inbox })).toBe("done"); - expect(inbox.drain()[0].text).toBe( - "the model provider anthropic is answering again — re-issue the held turn and continue", - ); + const witness = { + version: 1 as const, + runId: "r1", + seq: 8, + digest: createHash("sha256").update(JSON.stringify(effect.message)).digest("hex"), + }; + expect(deliverPlaneSteer(effect, { runId: "r1", inbox }, { ...witness, seq: 9 })).toBe("deferred"); + expect(deliverPlaneSteer(effect, { runId: "r1", inbox }, witness)).toBe("done"); + const [input] = inbox.drain(); + expect(input.ledgerWitness).toEqual(witness); + expect(input.text).toBe("the model provider anthropic is answering again — re-issue the held turn and continue"); }); it("heartbeat steers reject malformed version, target, principal and sequence before queue delivery", () => { diff --git a/src/core/runLedger/writeThrough.ts b/src/core/runLedger/writeThrough.ts index 1d6d71648..f1a44d344 100644 --- a/src/core/runLedger/writeThrough.ts +++ b/src/core/runLedger/writeThrough.ts @@ -55,6 +55,9 @@ import { sealPausedHardStop } from "./pausedStop.js"; import type { SourceReadState } from "../../mcp/sourceReadState.js"; import { sourceTaskSnapshotOf } from "../references/sourceTaskSnapshot.js"; import type { StepReport } from "./stepReport.js"; +import { inboxAcknowledgedRowsOf, prepareInboxAcknowledgments } from "./inboxAcknowledgments.js"; +import type { InboxRowWitness } from "./types.js"; +import type { FollowUpInput } from "../threadAdmission.js"; import type { ChatMessage } from "../chatMessage.js"; import type { ToolDef } from "../provider.js"; import type { RunEvent } from "../runEvents.js"; @@ -71,7 +74,15 @@ import { type UncertainStoreDiagnosis, } from "../storeFailure.js"; import { preserveHarnessPolicy } from "./checkpointState.js"; -import { sourceInputIntentsOf, sourceInputNativeMatches } from "./sourceInputIntent.js"; +import { + sourceInputIntentsOf, + sourceInputNativeMatches, + protectSourceInputStep, + sourceInputCheckpointRequestOf, + type SourceInputCheckpointRequest, + type SourceInputCheckpointResult, + type SourceInputCheckpoint, +} from "./sourceInputIntent.js"; import { sourceSnapshot } from "./sourceEvents.js"; import type { AudienceCheck } from "../audienceDecision.js"; import { assignLedgerLiveState } from "./decisions.js"; @@ -168,6 +179,31 @@ export interface LedgerWriteThroughOptions { schedule?: (fn: () => void, ms: number) => { cancel(): void }; } +/** The live sender shared by push and heartbeat delivery. Registry and slot + * lookups stay beside delivery so an old destination cannot be retained. */ +export function createPlaneSteerSender(deps: { + draining(): boolean; + getRun(id: string): { finished?: boolean; threadKey?: string } | null | undefined; + getInbox(threadKey: string): Parameters[1]; +}): (effect: Extract) => Promise { + return async (effect) => { + if (deps.draining()) return "deferred"; + effect = structuredClone(effect); + const witness: InboxRowWitness = { + version: 1, + runId: effect.runId, + seq: effect.seq, + digest: await sourceHash(effect.message), + }; + // Hashing yields. Check drain again before fresh target lookups and the + // synchronous inbox put; neither transport can wake a departing owner. + if (deps.draining()) return "deferred"; + const run = deps.getRun(effect.runId); + if (!run || run.finished || !run.threadKey) return "deferred"; + return deliverPlaneSteer(effect, deps.getInbox(run.threadKey), witness); + }; +} + /** Put an already-durable steer into this generation's live inbox. The inbox's * own durable-sequence set is the idempotency fence shared by a pushed * effect, a heartbeat replay and a reclaimed row. */ @@ -184,6 +220,7 @@ export function deliverPlaneSteer( userId: string; userName?: string; ledgerSeq: number; + ledgerWitness?: InboxRowWitness; msg: { channelId: string; threadKey: string; @@ -195,6 +232,7 @@ export function deliverPlaneSteer( }; } | undefined, + originalWitness?: InboxRowWitness, ): PlaneAckOutcome { if (live?.runId !== effect.runId) return "deferred"; const message = effect.message; @@ -217,6 +255,8 @@ export function deliverPlaneSteer( threadKey: message.threadKey, }); if (restored?.control?.kind !== "provider-reissue") return "deferred"; + const witness = originalWitness && inboxAcknowledgedRowsOf([originalWitness])?.[0]; + if (originalWitness && (!witness || witness.runId !== effect.runId || witness.seq !== effect.seq)) return "deferred"; const before = live.inbox.arrived; live.inbox.push({ text: restored.msg.text, @@ -224,6 +264,7 @@ export function deliverPlaneSteer( userId: restored.msg.userId, userName: restored.msg.userName, ledgerSeq: effect.seq, + ...(witness ? { ledgerWitness: witness } : {}), msg: restored.msg, }); return live.inbox.arrived === before ? "skipped" : "done"; @@ -411,7 +452,7 @@ export type WriteBoundaryFailure = { version: 1; runId: string; gen: string; - kind: "live-state" | "context-checkpoint"; + kind: "live-state" | "context-checkpoint" | "source-input-checkpoint"; requestDigest: string; expectedDigest: string; } @@ -427,6 +468,7 @@ export function writeBoundaryDiagnosticSummary(failure: WriteBoundaryFailure | u step: "/runs/step", "live-state": "/runs/live-state", "context-checkpoint": "/runs/session/checkpoint", + "source-input-checkpoint": "/runs/source-input/checkpoint", }[failure.kind]; return storeWriteDiagnosisSummary(operation, failure.diagnosis); } @@ -445,6 +487,9 @@ export interface LedgerRun { tracked(): boolean; /** The runner's step hook: the step's turns, then its record — awaited. */ step(report: StepReport): Promise; + /** Positive native acceptance of original normal/control rows. Source input + * uses its separate native receipt and exact checkpoint acknowledgment. */ + confirmInboxInputs(inputs: readonly FollowUpInput[]): void; /** A registry event, in publish order, with the registry's `seq`. */ event(event: RunEvent, seq: number): void; /** Reconcile uncertain snapshots before a live-state assignment can change their canonical readback. */ @@ -461,6 +506,12 @@ export interface LedgerRun { * input begun. A begun or uncertain original cannot be begun again. This * neither sends native input nor proves native admission or inbox ACK. */ beginSourceInput(id: string, validate: (context: ContextDependencies) => Promise): Promise; + /** One explicit checkpoint operation. Mutations require fresh canonical + * readback; an unknown result never resubmits native input or retries a write. */ + sourceInputCheckpoint( + request: SourceInputCheckpointRequest, + validate: (context: ContextDependencies) => Promise, + ): Promise; /** Persist one controller-admitted result before handing its bytes to a model. */ recordSourceResult(receipt: SourceResultReceipt): Promise; /** Freeze an acknowledged source cursor in the owned live row before handoff. */ @@ -812,6 +863,9 @@ export class NullLedgerRun implements LedgerRun { async step(_report: StepReport): Promise { // no ledger to mirror onto } + confirmInboxInputs(_inputs: readonly FollowUpInput[]): void { + // No canonical inbox belongs to an untracked run. + } event(_event: RunEvent, _seq: number): void { // no ledger to mirror onto } @@ -830,6 +884,9 @@ export class NullLedgerRun implements LedgerRun { ): Promise { return false; } + async sourceInputCheckpoint(): Promise<{ ok: false; reason: "unavailable" }> { + return { ok: false, reason: "unavailable" }; + } async recordSourceResult(_receipt: SourceResultReceipt): Promise { return false; } @@ -1372,6 +1429,25 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge request: StoreRequestWitness; expected: unknown; }> = []; + private readonly confirmedInbox = new Map(); + private inboxAcknowledgmentsActive = false; + private inboxBoundaryUnobserved = false; + confirmInboxInputs(inputs: readonly FollowUpInput[]): void { + if (!this.tracked() || this.finished || this.handedOff || this.finishLanding) return; + for (const input of inputs) { + const witness = input.ledgerWitness && inboxAcknowledgedRowsOf([input.ledgerWitness])?.[0]; + if (witness?.runId === this.runId && witness.seq === input.ledgerSeq && !this.confirmedInbox.has(witness.seq)) { + this.confirmedInbox.set(witness.seq, witness); + this.inboxAcknowledgmentsActive ||= this.state.sourceInputIntents !== undefined; + } + } + } + private forgetConfirmedInbox(rows: readonly InboxRowWitness[] | undefined): void { + for (const row of rows ?? []) { + if (JSON.stringify(this.confirmedInbox.get(row.seq)) === JSON.stringify(row)) + this.confirmedInbox.delete(row.seq); + } + } get writeBoundaryFailure(): WriteBoundaryFailure | undefined { const pending = this.pendingBoundaries[0]; return pending && structuredClone(pending.failure); @@ -1408,7 +1484,28 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge if (!this.pendingBoundaries.includes(pending)) continue; if (!observed.ok) return false; const state = observed.boundary.state as RunState | undefined; - if (pending.failure.kind === "context-checkpoint") { + if (pending.failure.kind === "source-input-checkpoint") { + const request = pending.expected as Exclude; + const id = request.operation === "commit" ? request.receipt.inputId : request.inputId; + const read = await ledger.sourceInputCheckpoint(this.runId, gen, { operation: "read", inputId: id }); + if ( + !read.ok || + !read.checkpoint || + (request.operation === "commit" + ? JSON.stringify(sourceSnapshot(read.checkpoint.receipt)) !== + JSON.stringify(sourceSnapshot(request.receipt)) + : !read.checkpoint.acknowledged || read.checkpoint.receiptHash !== request.receiptHash) + ) + return false; + const retained = sourceInputIntentsOf(state?.sourceInputIntents); + if ( + !retained?.checkpoints?.some( + (checkpoint) => JSON.stringify(checkpoint) === JSON.stringify(read.checkpoint), + ) + ) + return false; + this.state = { ...this.state, sourceInputIntents: retained }; + } else if (pending.failure.kind === "context-checkpoint") { const expected = pending.expected as ContextBoundaryExpected; const receipt = state?.contextCheckpointReceipt; if (!this.checkpointMatches(receipt, expected)) return false; @@ -1453,6 +1550,7 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge if (pending.failure.kind === "step") { const expected = pending.expected as StepRecord; this.turnsWritten = Math.max(this.turnsWritten ?? 0, expected.turnIndex); + this.forgetConfirmedInbox(expected.inboxAcknowledgedRows); } else if (pending.failure.kind === "state") { this.acknowledgedStateVersion = Math.max(this.acknowledgedStateVersion, pending.failure.stateVersion); } @@ -1581,6 +1679,7 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge this.onStop = req.onStop; this.onFenced = req.onFenced; this.stepNo = from.stepNo; + this.inboxBoundaryUnobserved = from.resumable === true; // An adopted run's next heartbeat says the round it is on, not round zero. this.factRound = from.stepNo; this.lastSeq = from.lastSeq; @@ -2015,7 +2114,7 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge const pending = sourceInputIntentsOf(this.state.sourceInputIntents); if (JSON.stringify(pending) !== JSON.stringify(original)) return hold("intent-changed"); const begun = { - version: 1 as const, + ...original, entries: original.entries.map((input) => (input.id === id ? { ...input, phase: "begun" as const } : input)), }; if (!(await this.setStateAndFlush({ sourceInputIntents: begun }))) return hold("begin-unconfirmed"); @@ -2042,6 +2141,171 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge return sending; } + sourceInputCheckpoint( + request: SourceInputCheckpointRequest, + validate: (context: ContextDependencies) => Promise, + ): Promise { + const frozen = sourceInputCheckpointRequestOf(request); + const sending = this.sourceSending.then(() => + this.trackBoundary(async (prior) => { + await prior; + return this.serializeState(async () => { + const unavailable = { ok: false, reason: "unavailable" } as const; + const held = (reason: string) => { + try { + warn( + JSON.stringify({ + event: "source.input.checkpoint.held", + runId: this.runId, + operation: frozen?.operation ?? "invalid", + reason, + }), + ); + } catch { + /* A diagnostic failure cannot permit an input. */ + } + return unavailable; + }; + try { + if (!frozen || !this.tracked() || this.finished || this.handedOff || this.finishLanding) + return held("owner-unavailable"); + if (!(await this.reconcilePendingBoundary())) return held("write-unconfirmed"); + const before = await ledger.peekInbox(this.runId, gen, 0); + if (!before.ok) return held("readback-unavailable"); + const state = before.boundary.state as RunState; + const id = frozen.operation === "commit" ? frozen.receipt.inputId : frozen.inputId; + const inputs = sourceInputIntentsOf(state.sourceInputIntents); + const entry = inputs?.entries.find((input) => input.id === id); + const context = state.contextDependencies; + if ( + !entry || + (frozen.operation !== "read" && entry.phase !== "begun") || + !sourceInputNativeMatches(state, entry) || + !isContextDependencies(context) || + context.status !== "known" + ) + return held("input-unproved"); + // Check only custody and source state. Progress counters can move + // without changing which original input this host can settle. + const binding = (value: RunState) => + JSON.stringify( + sourceSnapshot({ + entries: sourceInputIntentsOf(value.sourceInputIntents)?.entries ?? null, + harness: value.harness ?? null, + launch: value.harnessLaunch ?? null, + context: value.contextDependencies ?? null, + task: value.sourceTask ?? null, + }), + ); + const checked = binding(state), + local = binding(this.state); + if (!(await validate(structuredClone(context))).ok) return held("access-refused"); + const current = await ledger.peekInbox(this.runId, gen, 0); + if ( + !current.ok || + binding(current.boundary.state as RunState) !== checked || + binding(this.state) !== local + ) + return held("context-changed"); + if (frozen.operation === "ack") { + const saved = await ledger.sourceInputCheckpoint(this.runId, gen, { operation: "read", inputId: id }); + if (!saved.ok || !saved.checkpoint || saved.checkpoint.receiptHash !== frozen.receiptHash) + return held("checkpoint-unproved"); + } + // Access can be revoked while either prerequisite read waits. + if (!(await validate(structuredClone(context))).ok) return held("access-refused"); + if ( + !this.tracked() || + this.finished || + this.handedOff || + this.finishLanding || + binding(this.state) !== local + ) + return held("context-changed"); + let result: SourceInputCheckpointResult | undefined; + try { + result = await ledger.sourceInputCheckpoint(this.runId, gen, frozen); + } catch (error) { + if (frozen.operation === "read" || !(error instanceof UncertainStoreError)) throw error; + // A late mutation can still commit. Read its original identity; + // never repeat it from a timeout or missing response. + this.pendingBoundaries.push({ + failure: { + version: 1, + kind: "source-input-checkpoint", + runId: this.runId, + gen, + requestDigest: error.request.digest, + expectedDigest: await sourceHash(sourceSnapshot(frozen)), + ...(error.diagnosis ? { diagnosis: error.diagnosis } : {}), + storageDiagnostic: originalStorageFailure(error), + }, + request: error.request, + expected: frozen, + }); + if (!(await this.reconcilePendingBoundary())) return held("write-unconfirmed"); + } + if (result && !result.ok) return result; + if (result?.ok && result.checkpoint && !this.retainSourceCheckpoint(result.checkpoint)) + return held("checkpoint-unproved"); + const observed = + frozen.operation === "read" + ? result + : await ledger.sourceInputCheckpoint(this.runId, gen, { operation: "read", inputId: id }); + if (!observed?.ok) return held("readback-unavailable"); + if (observed.checkpoint && !this.retainSourceCheckpoint(observed.checkpoint)) + return held("checkpoint-unproved"); + if ( + frozen.operation === "commit" && + (!observed.checkpoint || + JSON.stringify(sourceSnapshot(observed.checkpoint.receipt)) !== + JSON.stringify(sourceSnapshot(frozen.receipt))) + ) + return held("checkpoint-unproved"); + if ( + frozen.operation === "ack" && + (!observed.checkpoint?.acknowledged || observed.checkpoint.receiptHash !== frozen.receiptHash) + ) + return held("ack-unproved"); + if (!(await validate(structuredClone(context))).ok) return held("access-refused"); + const after = await ledger.peekInbox(this.runId, gen, 0); + if (!after.ok || binding(after.boundary.state as RunState) !== checked || binding(this.state) !== local) + return held("context-changed"); + const retained = sourceInputIntentsOf((after.boundary.state as RunState).sourceInputIntents); + if (!retained) return held("checkpoint-unproved"); + // Later ordinary state writes must carry the store's immutable + // checkpoint frame, including a newly acknowledged exact witness. + this.state = { ...this.state, sourceInputIntents: retained }; + return observed; + } catch { + return held("storage-or-access-unavailable"); + } + }); + }), + ); + this.sourceSending = sending.then( + (result) => result.ok, + () => false, + ); + return sending; + } + + private retainSourceCheckpoint(checkpoint: SourceInputCheckpoint): boolean { + const inputs = sourceInputIntentsOf(this.state.sourceInputIntents); + if (!inputs?.entries.some((entry) => entry.id === checkpoint.receipt.inputId)) return false; + const retained = sourceInputIntentsOf({ + version: 2, + entries: inputs.entries, + checkpoints: [ + ...(inputs.checkpoints ?? []).filter((saved) => saved.receipt.inputId !== checkpoint.receipt.inputId), + structuredClone(checkpoint), + ], + }); + if (!retained) return false; + this.state = { ...this.state, sourceInputIntents: retained }; + return true; + } + private async saveSources(sources: SessionSources): Promise { if (this.detached || !this.sessionRow) return false; let stage = "checkpoint"; @@ -2401,7 +2665,10 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge step(report: StepReport): Promise { if (this.finished || this.finishLanding) return Promise.resolve(); - return this.trackBoundary(() => this.sendStep(report)); + return this.trackBoundary(async (prior) => { + await prior; + return this.sendStep(report); + }); } private async sendStep(report: StepReport): Promise { @@ -2419,18 +2686,48 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge ); if (report.compaction) turns.push({ idx: this.rowIndex(report.firstIdx + report.turns.length), compaction: report.compaction }); - const record: StepRecord = { + const confirmedInbox = [...this.confirmedInbox.values()].sort((a, b) => a.seq - b.seq); + this.inboxAcknowledgmentsActive ||= this.state.sourceInputIntents !== undefined && confirmedInbox.length > 0; + let record: StepRecord = { step: ++this.stepNo, seq: this.lastSeq, turnIndex: report.firstIdx + turns.length, ...(report.publicationAnswer !== undefined ? { publicationAnswer: report.publicationAnswer } : {}), inFlight: report.inFlight, inboxConsumedSeq: report.inboxConsumedSeq, + ...(this.inboxAcknowledgmentsActive ? { inboxAcknowledgedRows: confirmedInbox } : {}), ...(report.inboxDeferredSeqs?.length ? { inboxDeferredSeqs: report.inboxDeferredSeqs } : {}), remainingMs: report.remainingMs, turn: report.turn, iteration: report.iteration, }; + if ( + this.state.sourceInputIntents !== undefined || + this.inboxAcknowledgmentsActive || + this.inboxBoundaryUnobserved || + confirmedInbox.length > 0 + ) { + const observed = await ledger.peekInbox(this.runId, gen, 0); + if (!observed.ok) throw new TransientStoreError("source input step boundary is unavailable"); + const state = observed.boundary.state as RunState; + const prior = observed.boundary.lastStep as StepRecord | undefined; + if ( + record.inboxAcknowledgedRows === undefined && + (prior?.inboxAcknowledgedRows !== undefined || + (state.sourceInputIntents !== undefined && confirmedInbox.length > 0)) + ) + record.inboxAcknowledgedRows = confirmedInbox; + const prepared = await prepareInboxAcknowledgments(this.runId, record, observed.items); + if (!prepared) throw new TransientStoreError("original inbox acknowledgment proof is unavailable"); + const protectedRecord = protectSourceInputStep(state, record, observed.items, prior, prepared.witnesses); + const inputs = sourceInputIntentsOf(state.sourceInputIntents); + if (!protectedRecord || (state.sourceInputIntents !== undefined && !inputs)) + throw new TransientStoreError("source input step proof is unavailable"); + record = protectedRecord; + this.inboxAcknowledgmentsActive ||= record.inboxAcknowledgedRows !== undefined; + this.inboxBoundaryUnobserved = false; + if (inputs) this.state = { ...this.state, sourceInputIntents: inputs }; + } const expected = structuredClone(record); const expectedDigest = await sourceHash(expected); // The heartbeat body's step facts (record 0064): the round is the step @@ -2455,7 +2752,20 @@ export function createLedgerWriteThrough(opts: LedgerWriteThroughOptions): Ledge try { const result = await ledger.step(this.runId, gen, record, turns, this.sessionRow?.key); if (!result.ok) this.detach(`step ${record.step} refused (${result.reason})`, result.reason === "fenced"); - else this.turnsWritten = record.turnIndex; + else { + this.turnsWritten = record.turnIndex; + this.forgetConfirmedInbox(record.inboxAcknowledgedRows); + if ( + record.inboxAcknowledgedRows === undefined && + this.state.sourceInputIntents === undefined && + !this.inboxAcknowledgmentsActive + ) + this.forgetConfirmedInbox( + confirmedInbox.filter( + (row) => row.seq <= record.inboxConsumedSeq && !record.inboxDeferredSeqs?.includes(row.seq), + ), + ); + } return; } catch (err) { if (err instanceof UncertainStoreError) { diff --git a/src/core/runLedgerWorker.ts b/src/core/runLedgerWorker.ts index a0b2417b1..c0031b9b9 100644 --- a/src/core/runLedgerWorker.ts +++ b/src/core/runLedgerWorker.ts @@ -1,3 +1,11 @@ +import { inboxAcknowledgedRowsOf } from "./runLedger/inboxAcknowledgments.js"; +import { + sourceInputCheckpointRequestOf, + sourceInputCheckpointOf, + type SourceInputCheckpointRequest, + type SourceInputCheckpointResult, +} from "./runLedger/sourceInputIntent.js"; +import { sourceSnapshot } from "./runLedger/sourceEvents.js"; import { noteStoreReadFailure } from "./storeFailure.js"; import { writeReceiptReadOf, @@ -1125,9 +1133,26 @@ export class WorkerRunLedger implements RunLedger { session?: string, ): Promise { this.checkIds(runId, gen); + const normal = + record.inboxAcknowledgedRows === undefined ? undefined : inboxAcknowledgedRowsOf(record.inboxAcknowledgedRows); + if (record.inboxAcknowledgedRows !== undefined && !normal) + throw new PermanentStoreError("run ledger: invalid inbox acknowledgments"); + record = { ...record, ...(normal ? { inboxAcknowledgedRows: normal } : {}) }; const written = await this.writeTurns(runId, gen, turns, session); if (!written.ok) return written; - return this.fenceResult(await this.post("/runs/step", { storeKey: this.opts.storeKey, runId, gen, record })); + const result = await this.post("/runs/step", { storeKey: this.opts.storeKey, runId, gen, record }); + if ( + normal?.length && + result.status === 200 && + result.data.ok === true && + JSON.stringify(inboxAcknowledgedRowsOf(result.data.inboxAcknowledgedRows)) !== JSON.stringify(normal) + ) + throw this.unknownAcknowledgement( + "run ledger: exact inbox acknowledgment missing", + result.request, + result.status, + ); + return this.fenceResult(result); } private checkSessionKey(key: string): void { @@ -1615,6 +1640,47 @@ export class WorkerRunLedger implements RunLedger { return r.data.items as InboxItem[]; } + async sourceInputCheckpoint( + runId: string, + gen: string, + request: SourceInputCheckpointRequest, + ): Promise { + this.checkIds(runId, gen); + const parsed = sourceInputCheckpointRequestOf(request); + if (!parsed) throw new PermanentStoreError("run ledger: invalid source input checkpoint request"); + const result = await this.post( + "/runs/source-input/checkpoint", + { storeKey: this.opts.storeKey, runId, gen, request: parsed }, + false, + parsed.operation === "read" ? "read" : "write", + ); + if (result.status !== 200 || result.data.ok !== true) { + const fence = this.fenceResult(result); + if (!fence.ok) return fence; + } + const checkpoint = sourceInputCheckpointOf(result.data.checkpoint); + const id = parsed.operation === "commit" ? parsed.receipt.inputId : parsed.inputId; + if (parsed.operation === "read" && result.data.checkpoint === null) { + this.fenceResult(result); + return { ok: true, checkpoint: null }; + } + if ( + !checkpoint || + checkpoint.receipt.inputId !== id || + checkpoint.receiptHash !== (await sourceHash(sourceSnapshot(checkpoint.receipt))) || + (parsed.operation === "commit" && + JSON.stringify(sourceSnapshot(parsed.receipt)) !== JSON.stringify(sourceSnapshot(checkpoint.receipt))) || + (parsed.operation === "ack" && (parsed.receiptHash !== checkpoint.receiptHash || !checkpoint.acknowledged)) + ) + throw this.unknownAcknowledgement( + "run ledger: invalid source input checkpoint acknowledgement", + result.request, + result.status, + ); + this.fenceResult(result); + return { ok: true, checkpoint }; + } + async peekInbox(runId: string, gen: string, afterSeq: number): Promise { this.checkIds(runId, gen); const r = await this.read("/runs/inbox/read", { storeKey: this.opts.storeKey, runId, gen, afterSeq, peek: true }); diff --git a/src/core/storageRequestContext.ts b/src/core/storageRequestContext.ts index c01f1e21c..8b01660ed 100644 --- a/src/core/storageRequestContext.ts +++ b/src/core/storageRequestContext.ts @@ -266,6 +266,7 @@ export const STORAGE_OPERATIONS = { "/runs/source-events/release": nonRun("source-event"), "/runs/source-events/relevance": relevance, "/runs/state": runId, + "/runs/source-input/checkpoint": runId, "/runs/step": runId, "/runs/stop": runId, "/runs/summary": id, diff --git a/src/core/testing/sourceInputs.ts b/src/core/testing/sourceInputs.ts index fae890f27..c845dc78a 100644 --- a/src/core/testing/sourceInputs.ts +++ b/src/core/testing/sourceInputs.ts @@ -97,3 +97,87 @@ export async function seedSourceInputIntent( }; return input; } + +/** Isolated native checkpoint fixture. These synthetic native IDs prove the + * store boundary only; they do not claim acceptance by a running harness. */ +export async function seedSourceInputCheckpoints(ledger: RunLedger, renderedHash?: string) { + const id = "source-consumer", + gen = "g1", + thread = "cli:thread"; + const policy = { version: 1, commandRoute: "native", identity: "write" }; + const launch = { version: 1, harness: "pi", phase: "prepared", ordinal: 0, sessionPolicy: policy }; + const requireOk = (result: { ok: boolean }) => { + if (!result.ok) throw new Error(`Native checkpoint fixture refused: ${JSON.stringify(result)}`); + }; + requireOk( + await ledger.claim({ + runId: id, + threadKey: thread, + gen, + startedAt: 1, + leaseMs: 10000, + system: "original", + tools: [], + meta: { agent: "orchestrator", userId: "cli:alice", channelId: "cli:main", threadKey: thread }, + state: { harnessLaunch: launch }, + }), + ); + requireOk(await ledger.setState(id, gen, { harnessLaunch: { ...launch, phase: "begun" } })); + requireOk( + await ledger.setState(id, gen, { + harness: { harness: "pi", launchOrdinal: 0, sessionFile: "original-native-session", sessionPolicy: policy }, + }), + ); + const session = `fixture:checkpoint:${crypto.randomUUID()}`; + await ledger.claimSession(session, id, gen); + const step = { + step: 0, + seq: 0, + turnIndex: 0, + inFlight: [], + inboxConsumedSeq: 0, + remainingMs: 1000, + turn: 0, + iteration: 0, + }; + requireOk(await ledger.step(id, gen, step, [], session)); + requireOk(await ledger.pushInbox(id, { text: "Unrelated first row" })); + const original = testSourceInputIntent(); + if (renderedHash !== undefined) original.entries[0]!.renderedHash = renderedHash; + const first = await seedSourceInputIntent(ledger, original); + requireOk(await ledger.pushInbox(id, { text: "Unrelated third row" })); + const second = testSourceInputIntent(); + second.entries[0]!.id = "source-input-two"; + if (renderedHash !== undefined) second.entries[0]!.renderedHash = renderedHash; + const another = await seedSourceInputIntent(ledger, second); + const intents: SourceInputIntents = { version: 1, entries: [...first.entries, ...another.entries] }; + requireOk(await ledger.setState(id, gen, { sourceInputIntents: intents })); + for (const entry of intents.entries) entry.phase = "begun"; + requireOk( + await ledger.setState(id, gen, { + sourceInputIntents: intents, + contextDependencies: { + version: 4, + status: "known", + revision: 0, + origins: [], + slack: [], + mcp: [], + sourceInputs: intents.entries.map((entry) => entry.reference), + }, + }), + ); + const receipt: import("../runLedger/sourceInputIntent.js").SourceInputAdmission = { + version: 1, + inputId: intents.entries[0]!.id, + intentHash: await sourceHash(sourceSnapshot(intents.entries[0])), + native: { + harness: "pi", + sessionId: "original-native-session", + sessionIdentity: "native-session-uuid", + entryId: "native-entry-one", + entryHash: "a".repeat(64), + }, + }; + return { id, gen, thread, session, step, intents, receipt }; +} diff --git a/src/core/threadAdmission.ts b/src/core/threadAdmission.ts index 0fbb9fab9..010336167 100644 --- a/src/core/threadAdmission.ts +++ b/src/core/threadAdmission.ts @@ -1,6 +1,7 @@ import { attributedText, foldThreadEvents } from "./threadEvents.js"; import type { DocumentAttachment, ImageAttachment, IncomingMessage, SlackDirectAudience, StagedFile } from "./types.js"; import { systemClock } from "./trace/clock.js"; +import type { InboxRowWitness } from "./runLedger/types.js"; // Thread admission (docs/reference/specs/thread-admission.md): ONE live run per thread. // @@ -62,6 +63,9 @@ export interface FollowUpInput { * how far the run has consumed the durable inbox. Absent when the ledger * is off, refused the push, or the run had no row yet. */ ledgerSeq?: number; + /** Original stored row observed before native delivery. A later callback + * can settle this row only; source evidence has its separate native proof. */ + ledgerWitness?: InboxRowWitness; /** The run that sent it, when a run did rather than a person — a parent's * `send_to_run` (docs/reference/specs/agent-conductor.md item 8). The * stream's `input` event names it, and the settle never runs it fresh: diff --git a/src/index.ts b/src/index.ts index 918197115..270469f14 100644 --- a/src/index.ts +++ b/src/index.ts @@ -120,7 +120,7 @@ import { meatOnPath } from "./core/meatProcess.js"; import { buildRunLedger } from "./core/runLedgerWorker.js"; import { createLedgerWriteThrough, - deliverPlaneSteer, + createPlaneSteerSender, mintGeneration, NullLedgerWriteThrough, } from "./core/runLedger/writeThrough.js"; @@ -608,15 +608,11 @@ export async function runBot(): Promise { await planeAdmitPass(); return "done"; }, - steer: async (effect: Extract): Promise => { - const run = defaultRunRegistry.getById(effect.runId); - if (!run || run.finished || !run.threadKey) return "deferred"; - // The push route checks the ledger's generation fence before reaching - // this local lookup. The heartbeat path is already owner-fenced by the - // heartbeat that carried the effect; the admission slot then prevents a - // different run on the same thread from receiving it. - return deliverPlaneSteer(effect, defaultAdmission.get(run.threadKey)); - }, + steer: createPlaneSteerSender({ + draining: () => draining, + getRun: (id) => defaultRunRegistry.getById(id), + getInbox: (threadKey) => defaultAdmission.get(threadKey), + }), }; const runLedger = ledgerClient ? createLedgerWriteThrough({