diff --git a/examples/adversarial-implementation/README.md b/examples/adversarial-implementation/README.md index eaf55140d..5bc2502bd 100644 --- a/examples/adversarial-implementation/README.md +++ b/examples/adversarial-implementation/README.md @@ -739,9 +739,24 @@ expand only when they identify one commit in the assigned repository. Missing, ambiguous and non-commit references hold without a correction prompt. The raw reply stays saved; `response-acceptance.json` records the expansions. Other evidence fields remain subject to the existing correspondence checks. -One narrated or fenced JSON result is accepted without another agent call. -Multiple candidates, incomplete JSON and unclosed fences hold with the original -reply and diagnostics. Schema matching never chooses between candidates. +One narrated or fenced JSON object is accepted without another agent call. +A complete JSON array embedded in prose is incidental only when non-whitespace +prose precedes its opening bracket on that physical line. Its nested contents do +not become candidates. An array occupying the reply, starting a line after +indentation, or occupying a JSON fence refuses. Inline objects always count, +including examples; fences give no candidate precedence. Multiple objects, +malformed or incomplete JSON-looking spans, non-object JSON fences and unclosed +fences hold with the original reply and diagnostics. Closed non-JSON fences and +ordinary Markdown links, checkboxes, progress notation and placeholders retain +their existing treatment. Schema matching never chooses between candidates. +`Phase.Extract` reports the selected object's original half-open UTF-16 span, +excluding prose and fences, alongside its existing JSON value. + +An eligible original implementation extraction hold has an explicit +[no-provider recovery action](recovery/README.md). It preserves the failed call +and publishes a separate derivative at the original feedback gate under the +approved amendment. Use its narrow overlay with the original prepared owner; +ordinary continuation and independent review keep their existing contracts. When the only invalid fields are an oversized summary or handoff, foundation response correction can shorten those fields in the same Planner session, at diff --git a/examples/adversarial-implementation/components/Phase/Extract.ts b/examples/adversarial-implementation/components/Phase/Extract.ts index d5420d429..725044ed9 100644 --- a/examples/adversarial-implementation/components/Phase/Extract.ts +++ b/examples/adversarial-implementation/components/Phase/Extract.ts @@ -28,7 +28,7 @@ export default function* Extract(props: Record): Operation { }, }; } - return { ok: true, json: JSON.stringify(parsed.value) }; + return { ok: true, json: JSON.stringify(parsed.value.value), span: parsed.value.span }; } function parseText(text: string): Result { @@ -48,14 +48,28 @@ function opensRecord(text: string): boolean { ); } -function readResult(input: string): Result { - const whole = parseText(input.trim()); +type Candidate = { value: Json; span: { start: number; end: number } }; + +function objectResult(value: Json, start: number, end: number): Result { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return Err(new Error("The agent reply contains a non-object JSON result.")); + } + return Ok({ value, span: { start, end } }); +} + +function readResult(input: string): Result { + const trimmed = input.trim(); + const whole = parseText(trimmed); if (whole.ok) { - return whole; + const start = input.indexOf(trimmed); + return objectResult(whole.value, start, start + trimmed.length); } - const candidates: Json[] = []; + const candidates: Candidate[] = []; let outside = ""; - let fence: { marker: string; json: boolean; unlabeled: boolean; body: string } | undefined; + let offset = 0; + let fence: + | { marker: string; json: boolean; unlabeled: boolean; body: string; start: number } + | undefined; for (const line of input.split(/(?<=\n)/)) { const delimiter = fence === undefined @@ -73,15 +87,23 @@ function readResult(input: string): Result { if (!parsed.ok) { return parsed; } - candidates.push(parsed.value); + const start = fence.start + fence.body.length - fence.body.trimStart().length; + const result = objectResult(parsed.value, start, start + fence.body.trim().length); + if (!result.ok) { + return result; + } + candidates.push(result.value); } fence = undefined; } else { fence.body += line; } + // Preserve physical lines and UTF-16 positions while excluding fence contents. + outside += line.replace(/[^\r\n]/g, " "); } else if (delimiter) { if (delimiter[2].includes(delimiter[1])) { outside += line; + offset += line.length; continue; } const language = delimiter[2].trim().toLowerCase(); @@ -90,11 +112,14 @@ function readResult(input: string): Result { json: language === "json", unlabeled: language === "", body: "", + start: offset + line.length, }; - outside += line.slice(0, delimiter.index) + "\n"; + outside += + line.slice(0, delimiter.index) + line.slice(delimiter.index).replace(/[^\r\n]/g, " "); } else { outside += line; } + offset += line.length; } if (fence !== undefined) { return Err(new Error("The agent reply contains an unclosed code fence.")); @@ -117,7 +142,18 @@ function readResult(input: string): Result { if (!parsed.ok) { return parsed; } - candidates.push(parsed.value); + if (Array.isArray(parsed.value)) { + const prefix = outside.slice(outside.lastIndexOf("\n", index - 1) + 1, index); + if (prefix.trim() === "") { + return Err(new Error("The agent reply contains a result-position JSON array.")); + } + } else { + const result = objectResult(parsed.value, index, end.value); + if (!result.ok) { + return result; + } + candidates.push(result.value); + } index = end.value - 1; } if (candidates.length !== 1) { diff --git a/examples/adversarial-implementation/reconcile-response.md b/examples/adversarial-implementation/reconcile-response.md new file mode 100644 index 000000000..66a6d34ca --- /dev/null +++ b/examples/adversarial-implementation/reconcile-response.md @@ -0,0 +1,26 @@ +--- +description: >- + Revalidate a retained original joined reply without another provider call. +props: + type: object + properties: + record: {type: string, pattern: '^/'} + proof: {type: string, pattern: '^/'} + required: [record, proof] + additionalProperties: false +returns: {type: object} +--- + + +{recordText} + + + +{reconciliation.output} + + + !/^\s+at /.test(line)).join("\n").slice(0,1024),data:null}}} as="bounded" /> + + + + diff --git a/examples/adversarial-implementation/recovery/README.md b/examples/adversarial-implementation/recovery/README.md new file mode 100644 index 000000000..29acb9da0 --- /dev/null +++ b/examples/adversarial-implementation/recovery/README.md @@ -0,0 +1,83 @@ +# Revalidate an original joined reply without another provider call + +Use this interface when an original implementation reply completed but extraction left its Ticket held without a canonical result. It validates retained evidence and publishes one separate derivative at the original feedback gate. It does not perform feedback or implement missing acceptance work. + +## Applies to + +The explicit native file entry and direct native REPL component invocation. Select the recovery include before the existing owning workflow include. For #1400, keep the owner at eda5c08a9fbcc4a308537b17f0b9547108fbc748. Do not select current-main's ordinary Ticket loaders in place of that owner. The repaired CLI supplies the new action; its include composition supplies the unchanged owner. + +## Public interface + +File entry `examples/adversarial-implementation/reconcile-response.md` has exactly two required props, with no other props: + +- `record: string`: absolute path to an existing confirmed Ticket return. Initially this is the original held return. On a confirmed repeat, supply the actual confirmed successor returned by the prior successful action. +- `proof: string`: absolute path to the proof document below. The first admitted observation is snapshotted. A confirmed repeat hydrates that same recorded proof and evidence; it does not refresh original files. + +Component `Ticket.ReconcileResponse` has exactly two required props: + +- `record: object`: the same parsed Ticket envelope, validated by the owning Ticket.Envelope/Load boundary. +- `proof: string`: the absolute proof-document path. + +It returns the existing bounded `ticket-return.v1` envelope. On success it returns a confirmed paused feedback successor. On refusal it returns a held envelope retaining the prior confirmed continuation and useful receipt paths in its diagnostic. It accepts no role, model, work, call ID, revision, raw text, candidate, result, next gate, correction bound or permission prop; those facts are derived or validated from retained evidence. + +Description: “Revalidate an original joined reply without prompting. Use ``, then advance its confirmed return through the owning workflow.” + +## Proof document + +The exact top-level shape is: + +```json +{ + "schema": "joined-response-proof.v1", + "amendment": {"path": "/absolute/decision.md", "utf8Bytes": 1, "sha256": "64 lowercase hexadecimal characters"}, + "provenance": {"path": "/absolute/provenance.md", "utf8Bytes": 1, "sha256": "64 lowercase hexadecimal characters"}, + "join": {"path": "/absolute/architect-join-proof.json", "utf8Bytes": 1, "sha256": "64 lowercase hexadecimal characters"}, + "handoffInputs": [ + {"path": "/absolute/known-unmet-acceptance.md", "utf8Bytes": 1, "sha256": "64 lowercase hexadecimal characters"} + ] +} +``` + +The displayed sizes/digests are explanatory placeholders, not a ready-made proof. Obtain each descriptor from the exact permitted UTF-8 text before invoking the action. No other top-level members are admitted. Each reference is the existing strict `{path, utf8Bytes, sha256}` descriptor with an absolute path, the owning text bound and current File permission/protection. The three named evidence texts are nonempty. handoffInputs is ordered, distinct and bounded to twelve references, and normal selected-input capacity applies. + +For #1400, amendment and provenance are the retained approved decision and provenance files. join is `/private/tmp/xmd-joined-phase-recovery-1396/ticket/attempts/0001/architect-join-proof.json`, not an operator assertion that a turn joined. Read and validate its full referenced original prompt event, exact source membership and outer native completion against the held record. Ignore its summary booleans as proof of those facts. handoffInputs includes the exact supplied `/private/tmp/xmd-pullrequest-1400.4n6d_64v/known-unmet-acceptance.md`; keep its complete A6/A4/A8/A2/A7/unfinished-root qualifications. + +The join report’s journal line descriptor names the complete JSONL record, including its newline. Its native completion descriptor names the whole native log; the line selects the completion record only after that log validates. Effective definitions must match the prepared Git source. Retained imports through the original entry must agree, but code after the extraction failure need not have run. + +Approval/provenance document the actual authority already granted. Descriptors verify evidence correspondence and grant no permission. This format creates neither authority tokens nor a model-selection or historical-migration interface. + +## Invoke the native entry + +Use the following path pattern with the owner's saved return and measured proof file: + +```bash +deno task xmd run --allow-absolute \ + /absolute/repaired/examples/adversarial-implementation/reconcile-response.md \ + --props-record /private/tmp/xmd-pullrequest-1400.4n6d_64v/implementation-return.json \ + --props-proof /absolute/owner/recovery-proof.json \ + --include /absolute/repaired/examples/adversarial-implementation/recovery/components \ + --include /absolute/owning-pin/examples/adversarial-implementation/components \ + --raw +``` + +Retain the successful joined native return under a new path. It is the confirmed envelope used for continuation or a confirmed repeat. Never redirect over the input return, any historical attempt or any original receipt. If the native call fails or publication is uncertain, preserve its first output and held return, and inspect the reserved reconciliation. Matching files do not authorize another publication. + +A direct REPL entry uses the same composition and returns the component value. It must bind the already read/validated held envelope and proof path; the action does not read arbitrary conversation bindings or change native cwd. + +## What success publishes + +The existing Ticket state shape is preserved. New files live under `ticket/reconciliations//`: request/proof receipts, a separate result.json derivative, source observation, explicit disposition and confirmation. The checkpoint's existing document/feedback fields link these records to the failed original call. The old call remains failed_without_result with its original result link absent, and its execution remains failed. No original file is rewritten. + +The successor is paused and eligible for the original policy-selected feedback. Reconciliation dispatches nothing. Advance it in a separate ordinary owning-pin `continue.md` invocation with steps=1 and no model-selection props. It retains original allocation, conversations, input accounting and all correction allowances. + +For a confirmed repeat, invoke reconcile-response with the retained confirmed successor as record and the same proof reference. It returns exactly that envelope with no writes, prompts, source checks or successor dispatch. A different proof identity refuses. Reusing the old held input after reservation is held: supply the actual successful returned successor if it exists, or obtain operator disposition if completion was lost. A result or confirmation file alone cannot replace that returned acknowledgment. + +## Refusals and next action + +The held diagnostic names the missing/mismatched proof class and retained path. Missing or changed frozen guide/input/session/source, unjoined provider work, wrong model/routing, substantive schema conflict, competing results or another failure class remain held. Use existing evidence to resolve the stated fact; this action never selects another result or asks another provider. + +A reserved partial or uncertain action remains held, including uncertainty in its confirmation write. Preserve it and its first failure for the owner. This repair introduces no automatic operator-disposition path. A completed refusal is retained, not overwritten by a later corrected proof. Independent response-only repair continues through its existing original-owner contract and allowance; it is not added to this action. + +## Read next + +Read the [workflow guide](../README.md#run-a-separate-phase-or-continue-a-saved-ticket) for ordinary continuation and the [recorded decision](../../../specs/decisions.md) for the approved amendment. A recovered parse supplies no PASS, completed acceptance row or delivery readiness. diff --git a/examples/adversarial-implementation/recovery/components/Phase/Extract.ts b/examples/adversarial-implementation/recovery/components/Phase/Extract.ts new file mode 100644 index 000000000..99df8564d --- /dev/null +++ b/examples/adversarial-implementation/recovery/components/Phase/Extract.ts @@ -0,0 +1 @@ +export { default, props, returns } from "../../../components/Phase/Extract.ts"; diff --git a/examples/adversarial-implementation/recovery/components/Ticket/JoinedProof.ts b/examples/adversarial-implementation/recovery/components/Ticket/JoinedProof.ts new file mode 100644 index 000000000..75ddb4d43 --- /dev/null +++ b/examples/adversarial-implementation/recovery/components/Ticket/JoinedProof.ts @@ -0,0 +1,321 @@ +import { canonicalize } from "@executablemd/core"; +import { z } from "zod"; +import { parseDurableEvent } from "@executablemd/durable-streams"; +import { parsePromptRecord } from "@executablemd/agent/host"; +import { + describe, + descriptor, + read, + same, + stateLimit, + textLimit, +} from "../../../components/Ticket/text-storage.ts"; + +export const props = { + type: "object", + properties: { + path: { type: "string", pattern: "^/" }, + mode: { enum: ["admit", "validate"] }, + record: { type: "object" }, + call: { type: "object" }, + request: { type: "string" }, + raw: { type: "string" }, + }, + required: ["path", "mode", "record", "call", "request", "raw"], + additionalProperties: false, +}; +export const returns = { type: "object" }; +const reference = descriptor.extend({ path: z.string().startsWith("/") }).strict(); +const nonempty = reference.extend({ utf8Bytes: z.number().int().positive().max(textLimit) }); +const proofSchema = z.strictObject({ + schema: z.literal("joined-response-proof.v1"), + amendment: nonempty, + provenance: nonempty, + join: nonempty, + handoffInputs: z.array(reference).min(1).max(12), +}); +const jsonObject = z.record(z.string(), z.json()); +const location = z.strictObject({ + path: z.string().startsWith("/"), + line: z.number().int().positive(), +}); +const joinSchema = z.object({ + journal: location.extend({ lineDescriptor: descriptor.omit({ path: true }) }), + retainedEvent: z.string().startsWith("/"), + nativeFinishedSource: location.extend({ + utf8Bytes: z.number().int().nonnegative().max(textLimit), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + }), +}); + +function failure(message: string): never { + throw new Error("Joined-response proof: " + message); +} + +function* observed(expected: z.infer) { + const text = yield* read("/", expected.path, expected.utf8Bytes); + if (!same(expected, describe(expected.path, text))) { + failure("named evidence changed: " + expected.path); + } + return text; +} + +export default function* JoinedProof(value: unknown) { + const input = z + .strictObject({ + path: z.string().startsWith("/"), + mode: z.enum(["admit", "validate"]), + record: jsonObject, + call: z.object({ + role: z.literal("implementor"), + session: z.string(), + provider: z.enum(["claude", "codex"]), + profile: z.strictObject({ provider: z.string(), model: z.string(), effort: z.string() }), + assignment: z.object({ + repository: z.string(), + identityDirectory: z.string(), + artifactDirectory: z.string(), + }), + }), + request: z.string(), + raw: z.string(), + }) + .parse(value); + const text = yield* read("/", input.path, stateLimit); + const proof = proofSchema.parse(JSON.parse(text)); + const references = [proof.amendment, proof.provenance, proof.join, ...proof.handoffInputs]; + if (new Set(references.map((item) => item.path)).size !== references.length) { + failure("proof references must be distinct."); + } + const texts: Record = {}; + for (const entry of references) { + texts[entry.path] = yield* observed(entry); + } + if (input.mode === "admit") { + return { file: describe(input.path, text), proof, references }; + } + const join = joinSchema.parse(JSON.parse(texts[proof.join.path])); + const journalText = yield* read("/", join.journal.path, textLimit); + if (!journalText.endsWith("\n")) { + failure("the original journal has an unfinished final record."); + } + const lines = journalText.split("\n"); + lines.pop(); + const promptText = lines[join.journal.line - 1]; + if ( + promptText === undefined || + !same( + { path: join.journal.path, ...join.journal.lineDescriptor }, + describe(join.journal.path, promptText + "\n"), + ) + ) { + failure("the original event is not at its recorded journal location."); + } + const event = parseDurableEvent(promptText); + if ( + !event.ok || + event.value.type !== "yield" || + event.value.description.type !== "agent_prompt" || + event.value.result.status !== "ok" + ) { + failure("the selected event is not a completed prompt record."); + } + const prompt = parsePromptRecord(event.value.result.value); + if ( + prompt === undefined || + prompt.status !== "completed" || + prompt.withheld || + prompt.error !== undefined || + prompt.text !== input.raw || + event.value.description.input !== input.request + ) { + failure("the completed provider request/reply does not match the original call."); + } + if ( + prompt.agent !== input.call.provider || + prompt.configuration?.model !== input.call.profile.model || + prompt.configuration?.effort !== input.call.profile.effort + ) { + failure("the provider or delivered model/effort changed."); + } + const sessionPath = + input.call.assignment.identityDirectory + + "/" + + encodeURIComponent(input.call.session) + + ".json"; + const identityText = yield* read("/", sessionPath, stateLimit); + const pair = z.strictObject({ kind: z.string(), value: z.string() }); + const identity = z + .strictObject({ + schema: z.literal("phase-session.v2"), + agent: z.string(), + name: z.string(), + cwd: z.string(), + sessionKey: z.string(), + identity: pair.nullable(), + attempted: z.boolean(), + started: z + .strictObject({ sessionKey: z.string(), cwd: z.string(), identity: pair.nullable() }) + .nullable(), + }) + .parse(JSON.parse(identityText)); + if ( + !identity.attempted || + identity.name !== input.call.session || + identity.agent !== prompt.agent || + identity.cwd !== input.call.assignment.repository || + identity.sessionKey !== prompt.sessionKey || + identity.identity === null || + identity.identity.kind !== "acpx.agentSessionId" || + identity.identity.value !== prompt.agentSessionId || + identity.started?.sessionKey !== prompt.sessionKey || + identity.started.cwd !== identity.cwd || + JSON.stringify(identity.started.identity) !== JSON.stringify(identity.identity) + ) { + failure("the original native session identity is missing or mismatched."); + } + const retainedEvent = yield* read("/", join.retainedEvent, textLimit); + const retained = parseDurableEvent(retainedEvent); + if (!retained.ok || JSON.stringify(retained.value) !== JSON.stringify(event.value)) { + failure("the retained event export does not match the original journal."); + } + const nativeText = yield* read("/", join.nativeFinishedSource.path, textLimit); + const nativeLine = nativeText.split("\n")[join.nativeFinishedSource.line - 1]; + if ( + nativeLine === undefined || + !same( + { + path: join.nativeFinishedSource.path, + utf8Bytes: join.nativeFinishedSource.utf8Bytes, + sha256: join.nativeFinishedSource.sha256, + }, + describe(join.nativeFinishedSource.path, nativeText), + ) + ) { + failure("the original native completion receipt changed."); + } + const finished = z + .object({ + kind: z.literal("finished"), + joined: z.literal(true), + outcome: z.literal("completed"), + submission: z.object({ sessionId: z.string(), execution: z.string(), entry: z.string() }), + result: z.object({ value: jsonObject }), + error: z.null(), + journal: z.literal("completed"), + }) + .parse(JSON.parse(nativeLine)); + if ( + JSON.stringify(canonicalize(finished.result.value)) !== + JSON.stringify(canonicalize(input.record)) + ) { + failure("the joined native entry returned another Ticket envelope."); + } + let order = 0; + let open = false; + let member = false; + let closed = false; + const imports: { name: string; path: string; utf8Bytes: number; sha256: string }[] = []; + const yields: Record = {}; + let ownerFound = false; + const sourceOwner = z + .strictObject({ coroutineId: z.string(), index: z.number().int().nonnegative() }) + .parse(event.value.description["executablemd.source-owner"]); + const position = z + .object({ + path: z.string(), + offset: z.number().int().nonnegative(), + line: z.number().int().positive(), + column: z.number().int().positive(), + }) + .parse(event.value.description["executablemd.source-position"]); + for (const [index, line] of lines.entries()) { + const parsed = parseDurableEvent(line); + if (!parsed.ok) { + failure("the original journal contains an unreadable event."); + } + const item = parsed.value; + if ( + item.type === "yield" && + item.description.type === "import_component" && + item.description.name === "__root__" + ) { + if (open || item.coroutineId !== "root") { + failure("the original journal has contradictory entry boundaries."); + } + order += 1; + open = true; + for (const key of Object.keys(yields)) { + delete yields[key]; + } + } + if (!open) { + failure("the original journal has an event outside an entry."); + } + const selected = finished.submission.entry === "entry-" + order; + if (item.type === "yield") { + const ordinal = yields[item.coroutineId] ?? 0; + if ( + order <= Number(finished.submission.entry.slice(6)) && + item.description.type === "import_component" && + item.result.status === "ok" + ) { + const definition = z + .object({ kind: z.literal("repository"), path: z.string(), content: z.string() }) + .safeParse(item.result.value); + if (definition.success) { + imports.push({ + name: item.description.name, + ...describe(definition.data.path, definition.data.content), + }); + if ( + selected && + item.coroutineId === sourceOwner.coroutineId && + ordinal === sourceOwner.index && + definition.data.path === position.path && + definition.data.content.slice(position.offset).startsWith(" + + + + + + /\/reconciliations\/[0-9a-f]{64}\/disposition\.json$/.test(path))} /> + + + + +{dispositionText.content} + + + + [path,saved.documents[path]]))} as="retained" /> + + + + + + + + + + +```bash exec as="existing" +if test -e {quoted} || test -L {quoted}; then printf reserved; else printf none; fi +``` + + + + + +{preparationText} + + + +```bash exec as="workflow" +set -e +git -C {workflowQuoted} rev-parse HEAD +git -C {workflowQuoted} status --porcelain --untracked-files=no -- examples/adversarial-implementation +``` + + + + + + + + + + + +{originalCallText} + !["status","execution","delivery","profile"].includes(key)))} as="callCorresponds" /> + + + +{assignmentText} + + + + +{executionText} + +{responseText} + + + + + saved.manifest.directory + "/" + part + "/" + nextId)].map(path => "'" + path.replaceAll("'","'\"'\"'") + "'").join(" ")} /> +```bash exec as="unoccupied" +for path in {slots}; do if test -e "$path" || test -L "$path"; then exit 1; fi; done +``` + + +{deliveryText} + [input.path,input]))} as="selected" /> + selected[input.path])} /> + + + + + + + + + + + + joined.imports.some(original => original.name === actual.name && (original.sha256 !== actual.sha256 || original.utf8Bytes !== actual.utf8Bytes)))}> + + + + +{extracted.json} + + + + !Object.hasOwn(revisions.value,key))}> + + + + + + + + + + + + + + + + + +```bash exec as="ancestry" +git merge-base --is-ancestor {saved.manifest.assignment.revision} {result.revision} +``` + + + + saved.manifest.api.ownedPaths.includes(path))}> + + + + + !Object.hasOwn(candidate,key)).map(key => ({field:key,kind:["phase","work","next"].includes(key) ? "assignment_metadata" : "canonical_default",value:checked.value[key]})),...checked.normalizations.map(change => ({kind:"revision_expansion",...change})),...(candidate.next !== undefined && JSON.stringify(candidate.next) !== JSON.stringify(checked.value.next) ? [{field:"next",kind:"actual_policy",original:candidate.next,value:checked.value.next}] : [])],joined,guide,execution,source:{revision:result.revision,checkout:after,ancestry,changes,changedPaths:changes.paths,signature,artifacts:result.artifacts,evidence:result.evidence}}} /> + + + + + + +{validation.output} + + + + + + + entry.path),...validated.joined.originals.map(entry => entry.path),requestDescriptor.path,derivative.path,sourceDescriptor.path,...result.artifacts,...(result.assessment?.evidence ?? []),...result.evidence.flatMap(entry => entry.revision === null ? [entry.artifact,entry.candidate] : [entry.artifact])]} /> + + + + + documents[expected.path].sha256 !== expected.sha256 || documents[expected.path].utf8Bytes !== expected.utf8Bytes)}> + entry.path)])]}} /> + + + + 12}> + + + + + + + + + + + +{publicationCheck.output} + + + + + + diff --git a/examples/adversarial-implementation/recovery/components/Ticket/ReconcileResponse.md b/examples/adversarial-implementation/recovery/components/Ticket/ReconcileResponse.md new file mode 100644 index 000000000..9cd0fdf18 --- /dev/null +++ b/examples/adversarial-implementation/recovery/components/Ticket/ReconcileResponse.md @@ -0,0 +1,36 @@ +--- +description: >- + Revalidate an original joined reply without prompting. Use + , then advance its confirmed return through the owning workflow. +props: + type: object + properties: + record: {type: object} + proof: {type: string, pattern: '^/'} + required: [record, proof] + additionalProperties: false +returns: {type: object} +--- + + + + + +{loaded.output} + + + /\/reconciliations\/[0-9a-f]{64}\/result\.json$/.test(path)) ?? saved.manifest.directory + "/reconciliations/" + envelope.continuation.sha256 + "/result.json"),execution:call.execution,call:call.record + "/call.json"}} /> + + + + + + + +{reconciled.output} + + + !/^\s+at /.test(line)).join("\n").slice(0,1024),data:null}}} as="bounded" /> + + diff --git a/examples/adversarial-implementation/recovery/components/Ticket/RecoveryCorrespondence.ts b/examples/adversarial-implementation/recovery/components/Ticket/RecoveryCorrespondence.ts new file mode 100644 index 000000000..05d892ada --- /dev/null +++ b/examples/adversarial-implementation/recovery/components/Ticket/RecoveryCorrespondence.ts @@ -0,0 +1,16 @@ +import { canonicalize } from "@executablemd/core"; +import { z } from "zod"; + +export const props = { + type: "object", + properties: { original: { type: "object" }, recorded: { type: "object" } }, + required: ["original", "recorded"], + additionalProperties: false, +}; +export const returns = { type: "boolean" }; +export default function* RecoveryCorrespondence(value: unknown) { + const input = z.strictObject({ original: z.json(), recorded: z.json() }).parse(value); + return ( + JSON.stringify(canonicalize(input.original)) === JSON.stringify(canonicalize(input.recorded)) + ); +} diff --git a/examples/adversarial-implementation/recovery/components/Ticket/RecoveryOwner.ts b/examples/adversarial-implementation/recovery/components/Ticket/RecoveryOwner.ts new file mode 100644 index 000000000..455a61432 --- /dev/null +++ b/examples/adversarial-implementation/recovery/components/Ticket/RecoveryOwner.ts @@ -0,0 +1,87 @@ +import { getExpansion } from "@executablemd/core"; +import { Component } from "@executablemd/core/api"; +import { API } from "@executablemd/runtime"; +import { scoped } from "effection"; +import { z } from "zod"; +import { describe, read, stateLimit } from "../../../components/Ticket/text-storage.ts"; + +export const props = { + type: "object", + properties: { root: { type: "string", pattern: "^/" } }, + required: ["root"], + additionalProperties: false, +}; +export const returns = { type: "object" }; +const owners = [ + "Ticket.Load", + "Ticket.LoadState", + "Ticket.Schema", + "Ticket.Envelope", + "Ticket.Publish", + "Ticket.Advance", + "Ticket.Gate", + "Ticket.Continue", + "Ticket.Step", + "Phase.Schema", + "Phase.Response", + "Phase.SubmissionGuide", + "Phase.SubmissionInstructions", + "Phase.Request", + "Phase.Instructions", + "Phase.Profile", + "Phase.Run", + "Phase.Role", + "Phase.Correct", +]; + +export default function RecoveryOwner(value: unknown) { + return scoped(function* () { + const { root } = z.strictObject({ root: z.string().startsWith("/") }).parse(value); + const directory = root.replace(/\/$/, "") + "/examples/adversarial-implementation/components/"; + const definitions: { name: string; path: string; utf8Bytes: number; sha256: string }[] = []; + let reading: { path: string; text: string }[] = []; + yield* API.Fs.around({ + *readTextFile([path], next) { + const text = yield* next(path); + reading.push({ path, text }); + return text; + }, + }); + const expansion = yield* getExpansion(); + for (const name of owners) { + reading = []; + yield* Component.operations.importComponent(name, expansion.position); + const relative = name.replaceAll(".", "/"); + const selected = reading.filter( + (item) => + item.path === directory + relative + ".md" || item.path === directory + relative + ".ts", + ); + if (selected.length !== 1) { + throw new Error( + "Joined-response owner mismatch for " + + name + + "; select the original prepared owning include.", + ); + } + const retained = yield* API.Process.operations.exec({ + command: [ + "git", + "show", + "HEAD:" + + "examples/adversarial-implementation/components/" + + selected[0].path.slice(directory.length), + ], + cwd: root, + }); + if (retained.exitCode !== 0 || retained.stdout !== selected[0].text) { + throw new Error( + "The effective owning definition differs from its prepared Git source: " + name, + ); + } + definitions.push({ name, ...describe(selected[0].path, selected[0].text) }); + } + const control = directory + "Ticket/control.ts"; + const controlText = yield* read("/", control, stateLimit); + return { definitions, control: describe(control, controlText) }; + }); +} diff --git a/examples/adversarial-implementation/tests/Delivery.test.md b/examples/adversarial-implementation/tests/Delivery.test.md index 8ce944395..10caf6af4 100644 --- a/examples/adversarial-implementation/tests/Delivery.test.md +++ b/examples/adversarial-implementation/tests/Delivery.test.md @@ -202,3 +202,25 @@ pwd -P + + + + + + + + + + + + + + + + + + diff --git a/examples/adversarial-implementation/tests/JoinedResponseRecovery.test.md b/examples/adversarial-implementation/tests/JoinedResponseRecovery.test.md new file mode 100644 index 000000000..ca0635664 --- /dev/null +++ b/examples/adversarial-implementation/tests/JoinedResponseRecovery.test.md @@ -0,0 +1,16 @@ +```bash exec as="location" +pwd -P +``` + + + + "'" + value.replaceAll("'","'\"'\"'") + "'").join(" ")} /> +```bash exec as="ran" +deno {caseArguments} +``` + + + + + + diff --git a/examples/adversarial-implementation/tests/ProductionRole.test.md b/examples/adversarial-implementation/tests/ProductionRole.test.md index dbaf20e74..405402ac4 100644 --- a/examples/adversarial-implementation/tests/ProductionRole.test.md +++ b/examples/adversarial-implementation/tests/ProductionRole.test.md @@ -186,3 +186,15 @@ false incident.issue)} expected={[1075,1081]} /> incident.validationCode === "metadata-8" && !incident.canonicalResultCreated && !incident.implementationStarted && !incident.rawRewritten && incident.responseCorrections === 0 && incident.source.startsWith("/private/tmp/"))} expected={true} /> + + + + + + + + + + + + diff --git a/examples/adversarial-implementation/tests/Workflow.test.md b/examples/adversarial-implementation/tests/Workflow.test.md index 6cb45ecd9..9ccf060bb 100644 --- a/examples/adversarial-implementation/tests/Workflow.test.md +++ b/examples/adversarial-implementation/tests/Workflow.test.md @@ -63,6 +63,23 @@ printf '%s' "$XMD_EXAMPLE_COMMAND" + + + + + + + + + + + + + + + + + @@ -149,6 +166,19 @@ printf '%s' "$XMD_EXAMPLE_COMMAND" + + + + + +{child.stdout} + + +{text} + + + + diff --git a/examples/adversarial-implementation/tests/components/Adversarial/PlannerRole.md b/examples/adversarial-implementation/tests/components/Adversarial/PlannerRole.md index 22c9efd79..e056f7eb4 100644 --- a/examples/adversarial-implementation/tests/components/Adversarial/PlannerRole.md +++ b/examples/adversarial-implementation/tests/components/Adversarial/PlannerRole.md @@ -39,7 +39,8 @@ git rev-parse HEAD Use format to name a real consumer. The API owns formatting; consumers own their scenario. -Completed foundation. +Completed foundation. +Selected ["title","body"]. {reply} diff --git a/packages/cli/tests/adversarial-diagnosis.test.ts b/packages/cli/tests/adversarial-diagnosis.test.ts index d966af123..6ff36b7b3 100644 --- a/packages/cli/tests/adversarial-diagnosis.test.ts +++ b/packages/cli/tests/adversarial-diagnosis.test.ts @@ -337,7 +337,7 @@ describe("adversarial problem-solver phase", () => { howToObtain: "Capture one journal per child.", }; const json = JSON.stringify(result); - const reply = `Recording one overlap pair.\n${json}`; + const reply = `Recording one overlap pair with ["title","body"].\n${json}`; const first = join(test.root, "progress"); test.fake.script({ reply }); expect(JSON.parse(yield* test.run(first))).toMatchObject({ status: "missing_witness" }); diff --git a/packages/cli/tests/fixtures/joined-response-owner/README.md b/packages/cli/tests/fixtures/joined-response-owner/README.md new file mode 100644 index 000000000..f3ca81ba3 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/README.md @@ -0,0 +1,25 @@ +# Controlled owning workflow + +Use this closure in the joined-response recovery tests. `manifest.json` records +original paths, hashes and the eda5c08a9fbcc4a308537b17f0b9547108fbc748 origin. +The fixture assembler copies byte-identical common definitions from tracked +source and the differing definitions from this directory into a temporary owner. +Its real clean signed commit supplies preparation identity. CI needs no private +worktree or historical Git object. + +The relative `Ticket/control.ts` dependency remains model-aware. The original +extractor rejects the controlled narrated reply before the recovery overlay loads +the repaired canonical parser. `package.json`, `text-storage.ts` and +`native-node.ts` preserve the module context of that relative dependency. + +The pinned continuation's dormant model branch needs `Ticket.SelectModel` during +native syntax preflight. Its exact pinned definition is test-only; the source +boundary fails if expansion actually invokes it. Continuation supplies no model +selection props and proves ordinary Step forwarding to the original Haiku session. + +`git-boundary.ts` observes real signed fixture repositories where the headless +host has no Repository composition provider. The Node CLI uses its `Git.Changes` +forwarding component for that same boundary. `no-dispatch.ts` rejects any provider +prompt or role dispatch during reconciliation. Native File and rename cuts live +in the shared test support; selection, validators, snapshots, Advance and Publish +remain production components. diff --git a/packages/cli/tests/fixtures/joined-response-owner/boundary-runner.ts b/packages/cli/tests/fixtures/joined-response-owner/boundary-runner.ts new file mode 100644 index 000000000..a4147fb0d --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/boundary-runner.ts @@ -0,0 +1,8 @@ +import { useQuietProcessOutput } from "@executablemd/runtime"; +import { main } from "effection"; +import { proofBoundary } from "../../support/joined-response-boundaries.ts"; + +await main(function* (args) { + yield* useQuietProcessOutput(); + console.log("\n" + JSON.stringify(yield* proofBoundary(args[0]))); +}); diff --git a/packages/cli/tests/fixtures/joined-response-owner/boundary/Git/Changes.ts b/packages/cli/tests/fixtures/joined-response-owner/boundary/Git/Changes.ts new file mode 100644 index 000000000..f3e61b5ae --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/boundary/Git/Changes.ts @@ -0,0 +1,3 @@ +export { observeChanges as default } from "../../git-boundary.ts"; +export const props = { type: "object" }; +export const returns = { type: "object" }; diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Entry/Continue.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Entry/Continue.md new file mode 100644 index 000000000..1711d472a --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Entry/Continue.md @@ -0,0 +1,24 @@ +--- +props: + type: object + properties: + record: {type: string} + steps: {type: integer, minimum: 1, default: 1} + implementationModel: {type: string, minLength: 1} + implementationModelEvidence: {type: string, pattern: '^/'} + required: [record] + additionalProperties: false +returns: {type: object} +--- + +{text} + + + + +{continued.output} + + !/^\s+at /.test(line)).join("\n").slice(0,1024),data:null}})}} as="bounded" /> + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Correct.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Correct.md new file mode 100644 index 000000000..4c643d721 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Correct.md @@ -0,0 +1,105 @@ +--- +props: + type: object + properties: + assignment: {type: object} + role: {enum: [architect, planner, implementor]} + session: {type: string} + attempt: {type: string} + raw: {type: string} + profile: {type: object} + plannerProvider: {enum: [claude, codex], default: claude} + implementationProvider: {enum: [claude, codex]} + implementationModel: {type: string, minLength: 1} + inputs: {type: array, items: {type: object}} + maxResponseCorrections: {type: integer, minimum: 0, maximum: 3, default: 3} + required: [assignment, role, session, attempt, raw, profile, implementationProvider, inputs] + additionalProperties: false +returns: {type: object} +--- + + + + + + + + + + + + + + +{establishedText} + + + +{extracted.json} + + + + + + + + + + +{appliedText} + + + + + + + + + request.role === props.role),discoveryGaps:(established.discoveryGaps ?? []).filter(gap => gap.request.role === props.role)}} /> + += props.maxResponseCorrections}> + + + + + + +```bash exec as="reserved" +mkdir -- {quoted} +``` + + input.path)])],permitted:"Only rejected syntax/schema/identity/routing/handoff/provenance metadata and an assessment that was missing or invalid; preserve any valid established assessment, substantive outcome, source and genuine evidence. Other owners' gaps stay referenced, not redeclared."}} /> + 64000}> + + + +```bash exec as="identities" +shasum -a 256 -- {quoted}/request.json {quoted}/diagnostic.json {quoted}/original-inputs.json {quotedAssignment} {quotedRaw} +``` + +{identities.stdout} + + +{raw} + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Extract.ts b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Extract.ts new file mode 100644 index 000000000..d5420d429 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Extract.ts @@ -0,0 +1,157 @@ +import { parseJson } from "@executablemd/core"; +import type { Json } from "@executablemd/core"; +import { Err, Ok } from "effection"; +import type { Operation, Result } from "effection"; + +export const props = { + type: "object", + properties: { text: { type: "string" } }, + required: ["text"], + additionalProperties: false, +}; +export const returns = { type: "object" }; + +export default function* Extract(props: Record): Operation { + const input = props.text; + if (typeof input !== "string") { + throw new TypeError("Phase.Extract requires text."); + } + const parsed = readResult(input); + if (!parsed.ok) { + return { + ok: false, + rejection: { + kind: "response_validation", + code: "extraction", + message: parsed.error.message, + issues: [], + }, + }; + } + return { ok: true, json: JSON.stringify(parsed.value) }; +} + +function parseText(text: string): Result { + try { + return Ok(parseJson(JSON.parse(text))); + } catch (error) { + return Err(error); + } +} + +function opensRecord(text: string): boolean { + return ( + /^\s*\{\s*(?:"|}|$)/.test(text) || + /^\s*\[\s*(?:\{|\[|"|\]|(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)(?=\s*(?:,|\]|$))|$)/.test( + text, + ) + ); +} + +function readResult(input: string): Result { + const whole = parseText(input.trim()); + if (whole.ok) { + return whole; + } + const candidates: Json[] = []; + let outside = ""; + let fence: { marker: string; json: boolean; unlabeled: boolean; body: string } | undefined; + for (const line of input.split(/(?<=\n)/)) { + const delimiter = + fence === undefined + ? /(`{3,}|~{3,})([^\r\n]*)/.exec(line) + : /^ {0,3}(`{3,}|~{3,})([^\r\n]*)/.exec(line); + if (fence !== undefined) { + if ( + delimiter && + delimiter[1][0] === fence.marker[0] && + delimiter[1].length >= fence.marker.length && + delimiter[2].trim() === "" + ) { + if (fence.json || (fence.unlabeled && opensRecord(fence.body))) { + const parsed = parseText(fence.body); + if (!parsed.ok) { + return parsed; + } + candidates.push(parsed.value); + } + fence = undefined; + } else { + fence.body += line; + } + } else if (delimiter) { + if (delimiter[2].includes(delimiter[1])) { + outside += line; + continue; + } + const language = delimiter[2].trim().toLowerCase(); + fence = { + marker: delimiter[1], + json: language === "json", + unlabeled: language === "", + body: "", + }; + outside += line.slice(0, delimiter.index) + "\n"; + } else { + outside += line; + } + } + if (fence !== undefined) { + return Err(new Error("The agent reply contains an unclosed code fence.")); + } + for (let index = 0; index < outside.length; index += 1) { + if ( + (outside[index] !== "{" && outside[index] !== "[") || + /[A-Za-z0-9_$]/.test(outside[index - 1] ?? "") + ) { + continue; + } + if (!opensRecord(outside.slice(index))) { + continue; + } + const end = recordEnd(outside, index); + if (!end.ok) { + return end; + } + const parsed = parseText(outside.slice(index, end.value)); + if (!parsed.ok) { + return parsed; + } + candidates.push(parsed.value); + index = end.value - 1; + } + if (candidates.length !== 1) { + return Err(new Error("The agent reply must contain exactly one unambiguous JSON result.")); + } + return Ok(candidates[0]); +} + +function recordEnd(text: string, start: number): Result { + const closings: string[] = []; + let quoted = false; + let escaped = false; + for (let index = start; index < text.length; index += 1) { + const character = text[index]; + if (quoted) { + if (escaped) { + escaped = false; + } else if (character === "\\") { + escaped = true; + } else if (character === '"') { + quoted = false; + } + } else if (character === '"') { + quoted = true; + } else if (character === "{" || character === "[") { + closings.push(character === "{" ? "}" : "]"); + } else if (character === "}" || character === "]") { + if (character !== closings.pop()) { + return Err(new Error("The agent reply contains an incomplete JSON result.")); + } + if (closings.length === 0) { + return Ok(index + 1); + } + } + } + return Err(new Error("The agent reply contains an incomplete JSON result.")); +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Profile.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Profile.md new file mode 100644 index 000000000..84f3a3dac --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Profile.md @@ -0,0 +1,18 @@ +--- +description: 'Select the role profile and optional explicit Implementor model. Use .' +props: + type: object + properties: + role: {enum: [architect, planner, implementor]} + assessment: {type: object} + design: {type: boolean, default: false} + plannerProvider: {enum: [claude, codex], default: claude} + implementationProvider: {enum: [claude, codex], default: claude} + implementationModel: {type: string, minLength: 1} + required: [role, assessment] + additionalProperties: false +returns: {type: object} +--- + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Role.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Role.md new file mode 100644 index 000000000..6b0982460 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Role.md @@ -0,0 +1,73 @@ +--- +description: >- + Send one prepared request to its retained role conversation. Use . +props: + type: object + properties: + role: + enum: + - architect + - planner + - implementor + session: + type: string + minLength: 1 + inputs: + type: array + items: {type: object} + default: [] + correction: + anyOf: + - type: 'null' + - type: object + properties: + schema: {const: phase-response-correction.v1} + role: {enum: [architect, planner, implementor]} + session: {type: string} + provider: {enum: [claude, codex]} + initialize: {const: false} + phase: {enum: [discovery, implementation, review]} + work: {type: string} + revision: {type: string} + assignment: {type: string} + ordinal: {type: integer, minimum: 1, maximum: 3} + remaining: {type: integer, minimum: 0, maximum: 2} + raw: {type: string} + rejectedText: {type: string} + rejection: {type: object} + resultSchema: {type: object} + profile: {type: object} + established: {type: object} + report: {type: [string, 'null']} + applied: {type: [object, 'null']} + references: {type: array, items: {type: string}} + permitted: {type: string} + required: [schema, role, session, provider, initialize, phase, work, revision, assignment, ordinal, remaining, raw, rejectedText, rejection, resultSchema, profile, established, report, applied, references, permitted] + additionalProperties: false + default: null + assignment: + type: object + initialize: + type: boolean + default: false + plannerProvider: {enum: [claude, codex], default: claude} + implementationProvider: + enum: [claude, codex] + default: claude + implementationModel: {type: string, minLength: 1} + required: + - role + - session + - assignment + additionalProperties: false +--- + + + + + + + + +{request}{request} diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Run.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Run.md new file mode 100644 index 000000000..9e4fbcf14 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Run.md @@ -0,0 +1,152 @@ +--- +description: >- + Run one phase attempt, preserve the raw reply and return its validated result. Use . +props: + type: object + properties: + phase: + enum: + - discovery + - implementation + - review + role: + enum: + - architect + - planner + - implementor + session: + type: string + minLength: 1 + inputs: + type: array + items: {type: object} + default: [] + responseProfile: + type: object + properties: + kind: {enum: [phase, ticket, delivery-editorial]} + knownDocuments: {type: array, items: {type: string}} + establishedPath: {type: string} + appliedPath: {type: string} + required: [kind, knownDocuments] + additionalProperties: false + default: {kind: phase, knownDocuments: []} + assignment: + type: object + attempt: + type: string + minLength: 1 + initialize: + type: boolean + default: false + plannerProvider: {enum: [claude, codex], default: claude} + implementationProvider: + enum: [claude, codex] + default: claude + implementationModel: {type: string, minLength: 1} + maxResponseCorrections: + type: integer + minimum: 0 + maximum: 3 + default: 3 + nextRole: + anyOf: + - enum: [architect, planner, implementor] + - type: 'null' + default: null + successor: + anyOf: + - enum: + - discovery + - implementation + - review + - ready + - type: 'null' + default: null + required: + - phase + - role + - session + - assignment + - attempt + additionalProperties: false +returns: + type: object +--- + + + + + + + + + 12}> + + + + + + + + + + + + + + + + + + + + part === ".." || part === ".")}> +```bash exec as="workspace" +pwd -P +``` + + + + + + + + + + + + + + +```bash exec as="reservation" +mkdir -- {quotedAttempt} +``` + + + + + + + +{raw} + + + + + + + + + + +```bash exec as="hashes" +shasum -a 256 -- {rawQuoted} {resultQuoted} +``` + + + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Continue.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Continue.md new file mode 100644 index 000000000..3e4dd8eaf --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Continue.md @@ -0,0 +1,24 @@ +--- +props: + type: object + properties: + record: {type: object} + maxSteps: {type: integer, minimum: 1} + implementationModel: {type: string, minLength: 1} + implementationModelEvidence: {type: string, pattern: '^/'} + required: [record] + additionalProperties: false +returns: {type: object} +--- + + + + + + + + + + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Schema.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Schema.md new file mode 100644 index 000000000..b5cdffcdf --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Schema.md @@ -0,0 +1,247 @@ +--- +description: >- + Read the resolved ticket manifest contract. Use . +props: {type: object, additionalProperties: false} +returns: {type: object} +--- + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/SelectModel.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/SelectModel.md new file mode 100644 index 000000000..af78f14cd --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/SelectModel.md @@ -0,0 +1,54 @@ +--- +description: >- + Select the model of an unused original Implementor at a confirmed paused implementation + handoff and publish the amended continuation without calling a role. Use + , + then continue the returned envelope normally. +props: + type: object + properties: + record: {type: object} + model: {type: string, minLength: 1} + evidence: {type: string, pattern: '^/'} + required: [record, model, evidence] + additionalProperties: false +returns: {type: object} +--- + +The amendment covers one boundary: the confirmed, dispatchable, paused implementation +gate whose original Implementor has no initialization standing, no call of any status, +no identity receipt and no occupied next call reservation. The provider, sessions, +source anchor, captured inputs, call ordinals and consumed allowances stay as recorded. +The caller's authorization text enters the retained documents under a fresh reference +before a new continuation records the selection and links the one it replaces. + + + + + + call.role === "implementor")}> + + + + + "'" + path.replaceAll("'","'\"'\"'") + "'").join(" ")} /> +```bash exec as="unstarted" +for path in {unstartedPaths}; do if test -e "$path" || test -L "$path"; then exit 1; fi; done +``` + + + + + + + + + + + + + + + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Step.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Step.md new file mode 100644 index 000000000..58e10a2e8 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Step.md @@ -0,0 +1,90 @@ +--- +description: >- + Run the next original role and publish its settled continuation. Use + inside the ticket loop. +props: + type: object + properties: + record: {type: object} + previous: {type: [object, 'null'], default: null} + required: [record] + additionalProperties: false +returns: {type: object} +--- + +A held or completed ticket returns without invoking a role. Otherwise check its +inputs, run one phase and preserve the returned execution before settlement. + + + + + + + +```bash exec as="reserved" +mkdir -- {recordDirectory} +``` + + + + + + + + + + +{preflight.output} + + + + + + record.documents[input.path]),preparation:prepared.receipt}} /> + + + + + + + + + + {resultText} + + + +{canonical.output} + + + +{deliveryCapture.output} +{deliveryText} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/control.ts b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/control.ts new file mode 100644 index 000000000..8b58655bc --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/control.ts @@ -0,0 +1,249 @@ +import { z } from "zod"; +import { descriptor, snapshot, stateLimit } from "./text-storage.ts"; + +const role = z.enum(["architect", "planner", "implementor"]); +const revision = z + .string() + .regex(/^[0-9a-f]{40}$/) + .nullable(); +const jsonObject = z.record(z.string(), z.json()); +const provider = z.enum(["codex", "claude"]); +const profile = z + .object({ provider, model: z.string().min(1), effort: z.string().min(1) }) + .strict(); +const identity = z + .object({ + session: z.string().min(1), + provider, + initialized: z.boolean(), + }) + .strict(); +const implementorIdentity = identity.extend({ model: z.string().min(1).optional() }).strict(); +const modelSelection = z + .object({ + previousContinuation: descriptor, + previousModel: z.string().min(1).nullable(), + model: z.string().min(1), + evidence: snapshot, + }) + .strict(); +export const envelope = z + .object({ + schema: z.literal("ticket-return.v1"), + work: z.string(), + source: revision, + status: z.string(), + revision, + publication: z.enum(["confirmed", "held"]), + continuation: descriptor.nullable(), + pending: z + .object({ result: z.string(), execution: z.string(), call: z.string() }) + .strict() + .nullable(), + hold: z.string().nullable(), + delivery: z + .object({ status: z.enum(["review_pending", "feedback_pending"]), record: z.string() }) + .strict() + .optional(), + remainingRequiredDeliveryWork: z.array(z.string()).optional(), + nextAction: z + .object({ + entry: z.string(), + record: z.string().optional(), + gate: z.string().nullable().optional(), + action: z.string(), + result: z.string().optional(), + input: z.literal("ticket-decision.v1").optional(), + }) + .strict() + .optional(), + failure: z + .object({ name: z.string(), message: z.string(), data: z.json().nullable() }) + .strict() + .optional(), + }) + .strict(); +export const state = z + .object({ + schema: z.literal("ticket-state.v1"), + manifest: z + .object({ + schema: z.literal("ticket-workflow.v2"), + work: z.string(), + directory: z.string().startsWith("/"), + identityDirectory: z.string().startsWith("/").optional(), + assignment: jsonObject, + roles: z + .object({ architect: identity, planner: identity, implementor: implementorIdentity }) + .strict(), + acceptedInputs: z.array(snapshot), + roleInputs: z.partialRecord(role, z.array(snapshot)).optional(), + deliveredInputs: z.record(z.string(), z.array(z.string())).optional(), + maxCorrections: z.number().int(), + maxApiRepairs: z.number().int(), + maxResponseCorrections: z.number().int(), + api: jsonObject.optional(), + delivery: jsonObject.optional(), + implementationModelSelection: modelSelection.optional(), + }) + .strict(), + checkpoint: z + .object({ + reviewPolicy: z + .object({ + kind: z.enum(["feature", "correction"]), + assessment: jsonObject, + reviewers: z.array(z.enum(["architect", "planner"])), + model: z.literal("gpt-6.1-sol"), + effort: z.enum(["medium", "high"]), + }) + .strict(), + work: z.string(), + status: z.string(), + dispatchable: z.boolean(), + round: z.number().int().nonnegative(), + gate: z.string(), + revision, + assignment: jsonObject, + reviews: z.record(z.string(), z.string()), + feedback: z.array(z.string()), + initialized: z + .object({ architect: z.boolean(), planner: z.boolean(), implementor: z.boolean() }) + .strict(), + hold: z + .object({ + kind: z.string(), + reason: z.string(), + receipt: z.string().optional(), + next: z.object({ phase: z.string(), role: role.nullable() }).strict().optional(), + execution: z.literal("failed").optional(), + }) + .strict() + .nullable(), + plannerCall: z.string().startsWith("/").nullable().optional(), + feedbackInputs: z.array(z.string()).optional(), + discovery: z.array(jsonObject).optional(), + exactApproval: z.json().optional(), + exactReview: z.json().optional(), + decisions: z.array(z.string()).optional(), + }) + .strict(), + calls: z.array( + z + .object({ + id: z.string(), + attempt: z.string(), + record: z.string(), + gate: z.string(), + round: z.number().int(), + role, + session: z.string(), + provider, + initialize: z.boolean(), + assignment: jsonObject, + inputs: z.array(snapshot), + status: z.string(), + result: z.string().nullable().optional(), + execution: z.string(), + artifactDocumentRecord: z.string(), + documentRecord: z.string(), + observation: z.string().optional(), + validation: z.string().optional(), + source: z.string().optional(), + preparation: z.string().optional(), + delivery: z.string().nullable().optional(), + profile: profile.nullable().optional(), + }) + .strict(), + ), + documents: z.record(z.string(), snapshot), + deliveredInputs: z.record(z.string(), z.array(z.string())).default({}), + }) + .strict(); + +export function confirmLinks(saved: z.infer, selected: z.infer) { + if ( + saved.manifest.work !== selected.work || + saved.checkpoint.work !== selected.work || + saved.manifest.assignment.revision !== selected.source || + saved.checkpoint.revision !== selected.revision || + saved.checkpoint.status !== selected.status || + selected.continuation === null || + selected.continuation.utf8Bytes > stateLimit + ) { + throw new Error("Ticket continuation identity does not match its confirmed return."); + } + for (const [index, call] of saved.calls.entries()) { + const original = saved.manifest.roles[call.role]; + const id = String(index).padStart(4, "0"); + if ( + call.id !== id || + call.session !== original.session || + call.provider !== original.provider || + call.assignment.work !== selected.work || + call.assignment.repository !== saved.manifest.assignment.repository || + call.attempt !== saved.manifest.directory + "/attempts/" + id || + call.record !== saved.manifest.directory + "/calls/" + id || + call.execution !== call.record + "/execution.json" || + call.documentRecord !== call.record + "/documents.json" || + call.artifactDocumentRecord !== call.record + "/artifact-documents.json" || + (call.preparation !== undefined && + call.preparation !== saved.manifest.directory + "/preparations/" + id + "/receipt.json") || + (call.delivery !== undefined && + call.delivery !== null && + call.delivery !== call.attempt + "/delivery.json") || + (call.profile !== undefined && + call.profile !== null && + (call.profile.provider !== call.provider || + (call.role === "implementor" && + saved.manifest.roles.implementor.model !== undefined && + call.profile.model !== saved.manifest.roles.implementor.model))) || + (call.result !== undefined && + call.result !== null && + call.result !== call.attempt + "/result.json") || + call.inputs.some( + (input) => JSON.stringify(saved.documents[input.path]) !== JSON.stringify(input), + ) + ) { + throw new Error("Ticket call identity changed."); + } + } + const selection = saved.manifest.implementationModelSelection; + if ( + selection !== undefined && + (selection.model !== saved.manifest.roles.implementor.model || + !selection.previousContinuation.path.startsWith( + saved.manifest.directory + "/continuations/", + ) || + JSON.stringify(saved.documents[selection.evidence.path]) !== + JSON.stringify(selection.evidence)) + ) { + throw new Error("Ticket Implementor model selection changed."); + } + const receipt = saved.checkpoint.hold?.receipt; + if ( + receipt !== undefined && + (saved.checkpoint.hold?.kind !== "input_preparation" || + receipt !== + saved.manifest.directory + + "/preparations/" + + String(saved.calls.length).padStart(4, "0") + + "/receipt.json") + ) { + throw new Error("Ticket preparation hold names another call."); + } + const decisions = saved.manifest.directory + "/decisions/"; + for (const reservation of saved.checkpoint.decisions ?? []) { + if ( + !reservation.startsWith(decisions) || + !/^[0-9a-f]{64}$/.test(reservation.slice(decisions.length)) + ) { + throw new Error("Ticket decision receipt names another ticket."); + } + } + for (const [key, document] of Object.entries(saved.documents)) { + if (key !== document.path) { + throw new Error("Ticket original reference changed."); + } + } +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/native-node.ts b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/native-node.ts new file mode 100644 index 000000000..f54d6f80c --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/native-node.ts @@ -0,0 +1,80 @@ +import { ensure, scoped, until } from "effection"; +import type { Operation } from "effection"; +import { createHash } from "node:crypto"; +import { mkdir, open } from "node:fs/promises"; +interface NativeTextHandle { + read( + buffer: Uint8Array, + offset: number, + length: number, + position: null, + ): Promise<{ bytesRead: number }>; + close(): Promise; +} + +export function readFinite( + path: string, + limit: number, + acquire: (path: string) => Promise = (selected) => open(selected, "r"), +): Operation { + return scoped(function* () { + let opening: Promise | undefined; + let reading: Promise | undefined; + yield* ensure(function* () { + if (opening === undefined) { + return; + } + if (reading !== undefined) { + yield* until(reading.then(ignore, ignore)); + } + const handle = yield* until(opening.then((value) => value, ignore)); + if (handle !== undefined) { + yield* until(handle.close()); + } + }); + // @effectionx/fs has no incremental handle reader. + opening = acquire(path); + const handle = yield* until(opening); + const buffer = new Uint8Array(limit + 1); + let offset = 0; + while (offset < buffer.length) { + const pending = handle.read(buffer, offset, Math.min(65_536, buffer.length - offset), null); + reading = pending; + const result = yield* until(pending); + reading = undefined; + if (result.bytesRead === 0) { + break; + } + offset += result.bytesRead; + } + if (offset > limit) { + throw new Error("Ticket text exceeds its UTF-8 capacity."); + } + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( + buffer.subarray(0, offset), + ); + }); +} + +function ignore(): undefined { + return undefined; +} + +export function digest(bytes: Uint8Array): string { + return createHash("sha256").update(bytes).digest("hex"); +} + +export function createDirectory(path: string): Operation { + return scoped(function* () { + let pending: Promise | undefined; + yield* ensure(function* () { + if (pending !== undefined) { + yield* until(pending.then(ignore, ignore)); + } + }); + // @effectionx/fs only offers recursive creation. Join this uncancellable + // native mutation before settlement, including when its caller is halted. + pending = mkdir(path); + yield* until(pending); + }); +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/text-storage.ts b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/text-storage.ts new file mode 100644 index 000000000..93b5e6b9e --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/text-storage.ts @@ -0,0 +1,109 @@ +import { API, parseFilesFailure, parseFileWriteSuccess } from "@executablemd/runtime"; +import { scanSecrets, secretPolicy } from "@executablemd/core"; +import { scoped } from "effection"; +import type { Operation } from "effection"; +import { z } from "zod"; +import { digest, readFinite } from "./native-node.ts"; + +export const textLimit = 8_388_608; +export const stateLimit = 1_048_576; +export const descriptor = z + .object({ + path: z.string().min(1), + utf8Bytes: z.number().int().min(0).max(textLimit), + sha256: z.string().regex(/^[0-9a-f]{64}$/), + }) + .strict(); +export const snapshot = descriptor + .extend({ snapshot: z.string().startsWith("/"), observation: z.enum(["file", "supplied"]) }) + .strict(); + +export function describe(path: string, text: string) { + const bytes = new TextEncoder().encode(text); + return { path, utf8Bytes: bytes.length, sha256: digest(bytes) }; +} + +export function* clear(text: string): Operation { + if (!(yield* secretPolicy()).enabled || (yield* scanSecrets(text)).length !== 0) { + throw new Error("Ticket text did not clear enabled protection."); + } +} + +function address(repository: string, path: string) { + if (!path.startsWith("/")) { + return { cwd: repository, path }; + } + const slash = path.lastIndexOf("/"); + return { cwd: path.slice(0, slash) || "/", path: path.slice(slash + 1) }; +} + +export function read(repository: string, path: string, limit = textLimit): Operation { + return scoped(function* () { + yield* API.Fs.around({ + *readTextFile([selected]) { + return yield* readFinite(selected, limit); + }, + }); + const result = yield* API.Files.operations.readTextFile(address(repository, path)); + if (!result.ok) { + throw result.error; + } + yield* clear(result.value); + return result.value; + }); +} + +export function* write(repository: string, path: string, text: string): Operation { + yield* clear(text); + const result = yield* API.Files.operations.writeTextFile({ + ...address(repository, path), + content: text, + }); + if (!result.ok) { + throw result.error; + } + if (parseFileWriteSuccess(result.value)?.publication !== "host-committed") { + throw new Error("Ticket publication requires a confirmed native host write."); + } +} + +export function unused(repository: string, path: string): Operation { + return scoped(function* () { + yield* API.Fs.around({ + *readTextFile([selected]) { + return yield* readFinite(selected, 1); + }, + }); + const result = yield* API.Files.operations.readTextFile(address(repository, path)); + return !result.ok && parseFilesFailure(result.error)?.reason === "missing"; + }); +} + +export function same( + left: { path: string; utf8Bytes: number; sha256: string }, + right: { path: string; utf8Bytes: number; sha256: string }, +) { + return ( + left.path === right.path && left.utf8Bytes === right.utf8Bytes && left.sha256 === right.sha256 + ); +} + +export function* readBounded(path: string, limit: number): Operation { + try { + return yield* read("/", path, limit); + } catch (error) { + const failure = parseFilesFailure(error); + if (failure === undefined) { + throw error; + } + throw new Error( + "Cannot read " + + path + + " within " + + limit + + " UTF-8 bytes under current File permission: " + + failure.reason + + ". No resolution was recorded.", + ); + } +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/continue.md b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/continue.md new file mode 100644 index 000000000..2b0136c83 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/continue.md @@ -0,0 +1,13 @@ +--- +props: + type: object + properties: + record: {type: string, minLength: 1} + steps: {type: integer, minimum: 1, default: 1} + implementationModel: {type: string, minLength: 1} + implementationModelEvidence: {type: string, pattern: '^/'} + required: [record] + additionalProperties: false +--- + + diff --git a/packages/cli/tests/fixtures/joined-response-owner/git-boundary.ts b/packages/cli/tests/fixtures/joined-response-owner/git-boundary.ts new file mode 100644 index 000000000..3e9b47f1b --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/git-boundary.ts @@ -0,0 +1,77 @@ +import { registerComponents } from "@executablemd/core"; +import { Component, Plugin } from "@executablemd/core/api"; +import { API, cwd } from "@executablemd/runtime"; +import { z } from "zod"; +import RecoveryOwner, { + props as ownerProps, +} from "../../../../../examples/adversarial-implementation/recovery/components/Ticket/RecoveryOwner.ts"; + +export default Plugin({ + name: "test://joined-response-source-boundary", + *install() { + yield* Component.around({ + *expand([request], next) { + if (request.expansion.name === "Ticket.SelectModel") { + throw new Error("UnexpectedModelSelection"); + } + yield* next(request); + }, + }); + yield* registerComponents([ + { + name: "Fixture.Owner", + props: ownerProps, + returns: { type: "object" }, + fn: RecoveryOwner, + origin: "test://joined-response", + }, + { + name: "Git.Changes", + origin: "test://joined-response", + props: { type: "object" }, + returns: { type: "object" }, + fn: observeChanges, + }, + ]); + return undefined; + }, +}); + +export function* observeChanges(value: unknown) { + const input = z + .object({ + compare: z.enum(["staged", "unstaged", "commits"]), + base: z.string().optional(), + head: z.string().optional(), + }) + .parse(value); + const repository = yield* cwd(); + const head = yield* API.Process.operations.exec({ + command: ["git", "rev-parse", "HEAD"], + cwd: repository, + }); + if (head.exitCode !== 0) { + throw new Error(head.stderr); + } + const args = + input.compare === "commits" + ? [input.base ?? "", input.head ?? ""] + : input.compare === "staged" + ? ["--cached"] + : []; + const paths = yield* API.Process.operations.exec({ + command: ["git", "diff", "--name-only", "-z", ...args], + cwd: repository, + }); + if (paths.exitCode !== 0) { + throw new Error(paths.stderr); + } + return { + comparison: { base: (head.stdout ?? "").trim() }, + changes: (paths.stdout ?? "") + .split("\0") + .filter(Boolean) + .map((path) => ({ path, status: "modified" })), + next: null, + }; +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/manifest.json b/packages/cli/tests/fixtures/joined-response-owner/manifest.json new file mode 100644 index 000000000..a414b81c0 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/manifest.json @@ -0,0 +1,601 @@ +{ + "schema": "joined-response-owner-fixture.v1", + "pin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "files": [ + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Discovery/Schema.md", + "sha256": "f08f829f769b9e6a774548abc9395a3d515bf4b688967a10344aa220234a7f69", + "source": "examples/adversarial-implementation/components/Discovery/Schema.md", + "fixturePath": "examples/adversarial-implementation/components/Discovery/Schema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Entry/Continue.md", + "sha256": "67bf5781961f1c37e9d6e34ace821ffc8e3a5fc3ed617e2a07ef4daf71748c0a", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Entry/Continue.md", + "fixturePath": "examples/adversarial-implementation/components/Entry/Continue.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Covers.md", + "sha256": "8fb2bd86c58aac747369909427073630de879203332ace54f933f54a34a1b28c", + "source": "examples/adversarial-implementation/components/ExactCorrection/Covers.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Covers.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Patch.md", + "sha256": "f6e9f1b944bca791053b7cb348d3c3e9a9ff354df8ec509bede9ddcec4008d47", + "source": "examples/adversarial-implementation/components/ExactCorrection/Patch.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Patch.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Prepare.md", + "sha256": "d58bcf1ae7d3e12bf2127b496f8436451743290b76e31fd615e99cad397ef2d5", + "source": "examples/adversarial-implementation/components/ExactCorrection/Prepare.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Prepare.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Schema.md", + "sha256": "f5015bec880d382ca2933cad67d2685ed6a7fcdea484cd190266f605d0c59dde", + "source": "examples/adversarial-implementation/components/ExactCorrection/Schema.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Schema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Validate.md", + "sha256": "95d41f8b1ac514d7ff114fbc5638ef9e5b124974006bf280a80eb84d06bd51e4", + "source": "examples/adversarial-implementation/components/ExactCorrection/Validate.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Validate.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ExactCorrection/Verify.md", + "sha256": "71c8614c80029fe3fedb812baf8e301f82d3d864df78d74e44e944bfdea39326", + "source": "examples/adversarial-implementation/components/ExactCorrection/Verify.md", + "fixturePath": "examples/adversarial-implementation/components/ExactCorrection/Verify.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Guide/ExactCorrection.md", + "sha256": "3dae3b5fc7bb2613b0298b611e4b42f6a04d32cf5a7e5831b365c8f9c8ef93f8", + "source": "examples/adversarial-implementation/components/Guide/ExactCorrection.md", + "fixturePath": "examples/adversarial-implementation/components/Guide/ExactCorrection.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Accept.md", + "sha256": "ae72b0171f776331bf728d9fce7e0785366dc1c1d871ddabd34196c9ffe6ed3f", + "source": "examples/adversarial-implementation/components/Phase/Accept.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Accept.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Checkout.md", + "sha256": "21c89d2c0421ef928f61b39717c12a52508b77124ac549b2e6f3ef6b76d2c279", + "source": "examples/adversarial-implementation/components/Phase/Checkout.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Checkout.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Correct.md", + "sha256": "5f8eed09ef6fa2a15c5045db9e90d318ec48f799269279d0eef8b17c9ffca4be", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Correct.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Correct.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/CorrectionInstructions.md", + "sha256": "5589587a8f9b2e8265290d600f6722f095c988aa50009b4660d4c6d952c091ac", + "source": "examples/adversarial-implementation/components/Phase/CorrectionInstructions.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/CorrectionInstructions.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Correspondence.md", + "sha256": "d75f7b3180da48b71ca9d4cb3fd3129191890fa0531906db8710140ee9920b53", + "source": "examples/adversarial-implementation/components/Phase/Correspondence.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Correspondence.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Event.md", + "sha256": "238a772ccea1283fc2946819db1be06b563f43fd78d57e01c1b384ce33230367", + "source": "examples/adversarial-implementation/components/Phase/Event.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Event.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Extract.ts", + "sha256": "8de344d6ee37606d06957ed2d2be0a45329cf6a990435907fba6eb0fdefb7fdf", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Extract.ts", + "fixturePath": "examples/adversarial-implementation/components/Phase/Extract.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Instructions.md", + "sha256": "4b648162eccdede9cefd5dbfe15cb83164f91b5316e122b385eb98e7567ecb9e", + "source": "examples/adversarial-implementation/components/Phase/Instructions.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Instructions.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Metadata.md", + "sha256": "baf32787bab4c965f83b01977ec12612933a5756fc2a5ec1796cc60db92e3a02", + "source": "examples/adversarial-implementation/components/Phase/Metadata.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Metadata.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Next.md", + "sha256": "1a06ce6d03560f7fac048036cba859686489ff124ffee967d10988fb0185faf0", + "source": "examples/adversarial-implementation/components/Phase/Next.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Next.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Preparation.md", + "sha256": "3dbab788a55ef98dfcd155a2ae4fdab7865154deb9c1b930090731f06d01237a", + "source": "examples/adversarial-implementation/components/Phase/Preparation.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Preparation.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Profile.md", + "sha256": "85754051c70528df34a94830cc26a8c933b7206d7ea3e714c519e3769d87d0ca", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Profile.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Profile.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/ProviderName.md", + "sha256": "696352b81ff6daba38604e9a8f22223854eee61d5daefce425f6b990683c885c", + "source": "examples/adversarial-implementation/components/Phase/ProviderName.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/ProviderName.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Request.md", + "sha256": "86778e41de6a1563beae7ae82a57ff98f8f393c61de449ff82114440ffd2b458", + "source": "examples/adversarial-implementation/components/Phase/Request.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Request.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Response.md", + "sha256": "71d663448ec5a14536a5f064b64271f58646d8f7acd28e3ec28053b664118848", + "source": "examples/adversarial-implementation/components/Phase/Response.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Response.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Revisions.md", + "sha256": "93efcadd4ee50d6f87e3620e2272379bb36500262f40b5251403eceb8d90cfe8", + "source": "examples/adversarial-implementation/components/Phase/Revisions.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Revisions.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Role.md", + "sha256": "865b4fac72473da9f92e6b1a3297696398b975a2d18ea6e146bf909f08a12f0a", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Role.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Role.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Route.md", + "sha256": "fdb83a859dc5aabd09328545c779edefa657c508145b79a989b8a6c92deb483d", + "source": "examples/adversarial-implementation/components/Phase/Route.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Route.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Run.md", + "sha256": "35a791c79e030e8356cf4a0d31d54674a825bab2d2b401a3149e6b9ada3b720f", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Phase/Run.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Run.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Schema.md", + "sha256": "44516b83059b58d8d993b5159bb656ec66cc034ba5f74e77bbd482e4092f3b91", + "source": "examples/adversarial-implementation/components/Phase/Schema.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/Schema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/Session.ts", + "sha256": "e431956e16c66887220c28abab5a8cb8c05a02b2c230a54bc147523a082fb889", + "source": "examples/adversarial-implementation/components/Phase/Session.ts", + "fixturePath": "examples/adversarial-implementation/components/Phase/Session.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/SubmissionGuide.ts", + "sha256": "55d1cfe2e933d8bcee9a32142447b1ea3cb9e25ead42c2b9acd3a3015816c88f", + "source": "examples/adversarial-implementation/components/Phase/SubmissionGuide.ts", + "fixturePath": "examples/adversarial-implementation/components/Phase/SubmissionGuide.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Phase/SubmissionInstructions.md", + "sha256": "68132cba32087118bfc1143ffa5c4e6256f5ab822f8de4d6e9c1eaf52a30b528", + "source": "examples/adversarial-implementation/components/Phase/SubmissionInstructions.md", + "fixturePath": "examples/adversarial-implementation/components/Phase/SubmissionInstructions.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ReviewPolicy.md", + "sha256": "716c0bc7aae6dfec69be0542d08f38523cbfce2450000c0b6de7c862cb173447", + "source": "examples/adversarial-implementation/components/ReviewPolicy.md", + "fixturePath": "examples/adversarial-implementation/components/ReviewPolicy.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/ReviewPolicy/Schema.md", + "sha256": "21c7de9d570b9c1c789b99257808f76874722b1058be9c8a422b2d67eb55703a", + "source": "examples/adversarial-implementation/components/ReviewPolicy/Schema.md", + "fixturePath": "examples/adversarial-implementation/components/ReviewPolicy/Schema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Advance.md", + "sha256": "2259e4e81a0453332d1552120298871a76bc322c15cdab72d55313a71b31ea06", + "source": "examples/adversarial-implementation/components/Ticket/Advance.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Advance.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Capacity.ts", + "sha256": "fd2cc39a777977622e508622ecd13f1b21c20ac0a7914a7de962a07a080f198d", + "source": "examples/adversarial-implementation/components/Ticket/Capacity.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Capacity.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Capture.ts", + "sha256": "a306e09f3fba64966a02495ec200480f46ae7f202809c76a638aaa5ab178f023", + "source": "examples/adversarial-implementation/components/Ticket/Capture.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Capture.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/ChangedPaths.md", + "sha256": "cd19df8ef6a67f284fb4d3ac0d36f60b8218545950e370fea518f9af5bb128df", + "source": "examples/adversarial-implementation/components/Ticket/ChangedPaths.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/ChangedPaths.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Check.md", + "sha256": "05cfafd675f418baab04478a5e09e9e505e652e4a267cd3b83f3737cc7e59240", + "source": "examples/adversarial-implementation/components/Ticket/Check.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Check.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/CheckText.ts", + "sha256": "4d5ae233148c39690f942c0f6545cb1ae8ce31c0b9f9e9670023825dd95ca26d", + "source": "examples/adversarial-implementation/components/Ticket/CheckText.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/CheckText.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Checkout.md", + "sha256": "fc30e10bcba49ebd00bd6db0a9b5bb3bc9ddf97b511940612a390c6e95dd831d", + "source": "examples/adversarial-implementation/components/Ticket/Checkout.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Checkout.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Continue.md", + "sha256": "f730cecc802aca20a32e7a55be51e939489c38ad68e7d03edf292c8d73b72f5f", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Continue.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Continue.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/DocumentCapacity.ts", + "sha256": "0073d960ada11091c17071c1532712c84d707a29c6537e526f95fffa55deff80", + "source": "examples/adversarial-implementation/components/Ticket/DocumentCapacity.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/DocumentCapacity.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Documents.md", + "sha256": "6bbba9ba587e38e64b6fd0fd21b8fae7d40fe6e33a9671ce8fcb3e60d092d25b", + "source": "examples/adversarial-implementation/components/Ticket/Documents.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Documents.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Envelope.ts", + "sha256": "3f54544a3b6c8180c38858a44092456172e6a4dacb747d15fa4f3f19fcfc014b", + "source": "examples/adversarial-implementation/components/Ticket/Envelope.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Envelope.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Fingerprint.ts", + "sha256": "8cd19559ffa816648fda7f697a32b57f7f590650798e792be72611a4f8d09357", + "source": "examples/adversarial-implementation/components/Ticket/Fingerprint.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Fingerprint.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Finite.ts", + "sha256": "9f8242e38bdf9f887b52940ad635073e944cd5dd6802066daf6b800dd2b17411", + "source": "examples/adversarial-implementation/components/Ticket/Finite.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Finite.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Gate.md", + "sha256": "061bb6d4722f1f68c58b74118ed0be81d10d3f39b37dddc1dd5eb0532cec07e7", + "source": "examples/adversarial-implementation/components/Ticket/Gate.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Gate.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Hydrate.md", + "sha256": "10c8b338033d2119dcabd175c56beff7556e1cce0e5c99f8ab3153940b1632b4", + "source": "examples/adversarial-implementation/components/Ticket/Hydrate.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Hydrate.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Inputs.md", + "sha256": "6b474aaf3e6eb7e2a3b9e7a54e576d525d9b64ebed7941b228258b36e2de1a73", + "source": "examples/adversarial-implementation/components/Ticket/Inputs.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Inputs.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Load.md", + "sha256": "bb21a2acda3624f6b448fd1d617c3f0da123d736f29634592576f1ccad295540", + "source": "examples/adversarial-implementation/components/Ticket/Load.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Load.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/LoadState.ts", + "sha256": "c59a6d497196ce23c451b3f295d95d358f6fd56a3e672327f8a7c2846993f602", + "source": "examples/adversarial-implementation/components/Ticket/LoadState.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/LoadState.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Material.md", + "sha256": "89399ce1ca166163b5e28bc2809399cf39c00286efc5fb880a87e7a18750932d", + "source": "examples/adversarial-implementation/components/Ticket/Material.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Material.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Outward.ts", + "sha256": "0540ca885d7e752552eddfcfd224ed29437039611018683feebebf721152f727", + "source": "examples/adversarial-implementation/components/Ticket/Outward.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Outward.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/PreparationPrompt.md", + "sha256": "e4445f765f49f30c98308ca7ccb7053f3a9c58f3ffce5bf6b26216eda6789c39", + "source": "examples/adversarial-implementation/components/Ticket/PreparationPrompt.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/PreparationPrompt.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/PreparationSchema.md", + "sha256": "e2754b9771c8f8a70a486ca5a7156aee3ebde3604de971320bd963a85593e6bb", + "source": "examples/adversarial-implementation/components/Ticket/PreparationSchema.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/PreparationSchema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Prepare.md", + "sha256": "a0577bc67da39a6c4ac0e7664ecd32baec98370bd25dcbb185adb2a5699b857e", + "source": "examples/adversarial-implementation/components/Ticket/Prepare.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Prepare.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Preservation.ts", + "sha256": "a1e1d34e64da095477b9c2c1246f6d5a1c89c973edd562a23cf95e131870678b", + "source": "examples/adversarial-implementation/components/Ticket/Preservation.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Preservation.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Publish.ts", + "sha256": "7d48a02f9c0a4c2a575ba984f1b3139512f805e44968cb4aef0439b1851404fd", + "source": "examples/adversarial-implementation/components/Ticket/Publish.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Publish.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Read.ts", + "sha256": "8e97b62892f01938788a253550d0c4427d910eb2c5d26568387143a66e9c8622", + "source": "examples/adversarial-implementation/components/Ticket/Read.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Read.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/ReserveDecision.ts", + "sha256": "d5d2d56f41180bf5744e377f7c8e0e710e99ae1cad85eeb1fdc32d3d32ec72f5", + "source": "examples/adversarial-implementation/components/Ticket/ReserveDecision.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/ReserveDecision.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Reviewed.md", + "sha256": "1284460cdc1811768ea8d2dded2b6e0d5f7522a810458a2f5c14aa38ba88839c", + "source": "examples/adversarial-implementation/components/Ticket/Reviewed.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Reviewed.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Run.md", + "sha256": "f80444d42c3cebcc7ee626957b94b5cf0984b15278880e52c846d3dafdd51305", + "source": "examples/adversarial-implementation/components/Ticket/Run.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Run.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/SaveDocuments.ts", + "sha256": "3362a9c7b69be15760cb578197856c2e9ea8ff9b564b565f15a16832344842de", + "source": "examples/adversarial-implementation/components/Ticket/SaveDocuments.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/SaveDocuments.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/SaveMetadata.ts", + "sha256": "11644e3d52cac5c38f454aadf047b95e750a8a770a98abb45a738dca4dee1dc0", + "source": "examples/adversarial-implementation/components/Ticket/SaveMetadata.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/SaveMetadata.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Schema.md", + "sha256": "53bf508acfc3701a0b31f803b859c1de9753a2642d804deb1a875d1b43b587a1", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Schema.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Schema.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/SelectModel.md", + "sha256": "cb280e46a96a9ab8e44085357d47aca6186a26e202859d96aef8f118cfef93ec", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/SelectModel.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/SelectModel.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Selected.md", + "sha256": "0eb8e3fe917741ea955456ffeba5f37c7223d9bb593127999f4c6ea4745fec6c", + "source": "examples/adversarial-implementation/components/Ticket/Selected.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Selected.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Settle.md", + "sha256": "62eca8cb1889298c5da74e703757f6208158a4b8f25bf427925727f73c00b77b", + "source": "examples/adversarial-implementation/components/Ticket/Settle.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Settle.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Signature.md", + "sha256": "d704c3a3d6ab8b2177b9b3a74952872c76399aca7284d9989df3393aea29dc55", + "source": "examples/adversarial-implementation/components/Ticket/Signature.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Signature.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Snapshot.ts", + "sha256": "bb65375c447503435a890d94a5a0cd1446eef63d4bcc01a63b420d321bd807d0", + "source": "examples/adversarial-implementation/components/Ticket/Snapshot.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Snapshot.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/SnapshotSchema.ts", + "sha256": "2847ccff1db554e56068c08f0321d6e83568e2ae90f3e1e8c335f51ae5b8137a", + "source": "examples/adversarial-implementation/components/Ticket/SnapshotSchema.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/SnapshotSchema.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Start.md", + "sha256": "415c88ac7f0dcdd7269097f97a073c7dd8762e15f3f54d88539fbe878eccc0cc", + "source": "examples/adversarial-implementation/components/Ticket/Start.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Start.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Step.md", + "sha256": "9947b54dbecf7a61f2fb34bf8e0bce7e5b7685f545eb08d0813edc820da25398", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/Step.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Step.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Text.md", + "sha256": "8e9743bdf98ea8d0ff832d251093b7d3872d6099e44c3f419183002812d4f4af", + "source": "examples/adversarial-implementation/components/Ticket/Text.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Text.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Walk.md", + "sha256": "0a8346fc6ceb47c0762e3bd46af2a1119338391eb7707428b2cab54676307c07", + "source": "examples/adversarial-implementation/components/Ticket/Walk.md", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Walk.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/Windows.ts", + "sha256": "51fd9427580f6aba33f735ca9b05fce0982af2513e320ab507698a764d69f4c8", + "source": "examples/adversarial-implementation/components/Ticket/Windows.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/Windows.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/WorkflowSource.ts", + "sha256": "f01b7aa7faf328174dc22b2847691c41c97f9800bcff9317008c8bbdfd2d9a58", + "source": "examples/adversarial-implementation/components/Ticket/WorkflowSource.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/WorkflowSource.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/control.ts", + "sha256": "e50d9d5c70703797c218cd0ab6028fd6110097ce23ffee17a2c6addbd333e5a3", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/control.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/control.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/json-size.ts", + "sha256": "f5f500fccc98f74ec7dd5238f2aa6b41da6573991d3b04e3cadf44222b51c1c4", + "source": "examples/adversarial-implementation/components/Ticket/json-size.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/json-size.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/native-node.ts", + "sha256": "fc3a787e0359598e9acad45dc3b59d8a48ad8e50b0fcf1db145fa782f5941ddd", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/native-node.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/native-node.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/outward-size.ts", + "sha256": "ed2b66a4385634ea33be402060d1d7ab0d2989b63255560b6c15f80607575d93", + "source": "examples/adversarial-implementation/components/Ticket/outward-size.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/outward-size.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/components/Ticket/text-storage.ts", + "sha256": "84e2eb0341f1e3cdf4fb0a42358f88492f0fc29d3618758073638d3c8bf75939", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/components/Ticket/text-storage.ts", + "fixturePath": "examples/adversarial-implementation/components/Ticket/text-storage.ts" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "examples/adversarial-implementation/continue.md", + "sha256": "e203e3a5b44f91aff27950f11a7f75af14077625c2e3a7cc1cbdb84c6e035ffa", + "source": "packages/cli/tests/fixtures/joined-response-owner/examples/adversarial-implementation/continue.md", + "fixturePath": "examples/adversarial-implementation/continue.md" + }, + { + "originPin": "eda5c08a9fbcc4a308537b17f0b9547108fbc748", + "originalPath": "package.json", + "sha256": "7e2eb9c1ae606757f241d3fb3517ba0570375c189d9fd1620111e898e24cad8c", + "source": "package.json", + "fixturePath": "package.json" + } + ] +} diff --git a/packages/cli/tests/fixtures/joined-response-owner/no-dispatch.ts b/packages/cli/tests/fixtures/joined-response-owner/no-dispatch.ts new file mode 100644 index 000000000..a789a15e2 --- /dev/null +++ b/packages/cli/tests/fixtures/joined-response-owner/no-dispatch.ts @@ -0,0 +1,31 @@ +import { Component, Plugin } from "@executablemd/core/api"; +import { Agent } from "@executablemd/agent/api"; + +export default Plugin({ + name: "test://joined-response-no-dispatch", + *install() { + yield* Agent.around({ + *prompt() { + throw new Error("ForbiddenReconciliationPrompt"); + }, + }); + yield* Component.around({ + *expand([request], next) { + if ( + [ + "Ticket.Step", + "Ticket.Continue", + "Ticket.SelectModel", + "Phase.Run", + "Phase.Role", + "Prompt", + ].includes(request.expansion.name) + ) { + throw new Error("ForbiddenReconciliationDispatch: " + request.expansion.name); + } + yield* next(request); + }, + }); + return undefined; + }, +}); diff --git a/packages/cli/tests/joined-response-recovery.test.ts b/packages/cli/tests/joined-response-recovery.test.ts new file mode 100644 index 000000000..f691af78d --- /dev/null +++ b/packages/cli/tests/joined-response-recovery.test.ts @@ -0,0 +1,615 @@ +import { describe, it } from "@executablemd/test-support/bdd"; +import { expect } from "@executablemd/test-support/expect"; +import { ensureDir, readTextFile, writeTextFile, rm } from "@effectionx/fs"; +import { API } from "@executablemd/runtime"; +import { z } from "zod"; +import { join } from "node:path"; +import { parseDurableEvent } from "@executablemd/durable-streams"; +import { git } from "../../git/tests/support/git-remotes.ts"; +import { originalFeedback } from "./support/joined-response-feedback.ts"; +import { cuts, interruptedRecovery, contenders } from "./support/joined-response-interruption.ts"; +import { recoveryFixture, reconcile, directRecovery } from "./support/joined-response-recovery.ts"; +import type { RecoveryFixture } from "./support/joined-response-recovery.ts"; +import { describe as descriptor } from "../../../examples/adversarial-implementation/components/Ticket/text-storage.ts"; + +const envelope = z.object({ + status: z.string(), + publication: z.string(), + hold: z.string().nullable(), + failure: z.json().optional(), + continuation: z.object({ path: z.string() }), +}); +function* originalFiles(directory: string) { + const files: Record = {}; + function* walk(path: string): import("effection").Operation { + for (const item of yield* API.Fs.operations.readDirectory(path)) { + const name = join(path, item.name); + if (item.isDirectory) { + yield* walk(name); + } else if (item.isFile) { + files[name] = descriptor(name, yield* readTextFile(name)).sha256; + } + } + } + yield* walk(directory); + return files; +} +function* unchanged(files: Record) { + for (const [path, hash] of Object.entries(files)) { + expect(descriptor(path, yield* readTextFile(path)).sha256).toBe(hash); + } +} +function* accepted(fixture: RecoveryFixture, runtime: "deno" | "node" = "deno") { + const before = yield* originalFiles(fixture.ticket); + const oldState = JSON.parse( + yield* readTextFile(envelope.parse(fixture.record).continuation.path), + ); + const calls = fixture.native.host.fake.prompts.length; + const run = yield* reconcile(fixture, runtime); + if (run.exitCode !== 0) { + throw new Error(run.stderr || run.stdout); + } + const recovered = envelope.parse(JSON.parse(run.stdout)); + expect(recovered).toMatchObject({ status: "paused", publication: "confirmed", hold: null }); + yield* unchanged(before); + expect(fixture.native.host.fake.prompts.length).toBe(calls); + const state = JSON.parse(yield* readTextFile(recovered.continuation.path)); + expect(state.manifest).toEqual(oldState.manifest); + expect(state.calls).toEqual(oldState.calls); + expect(state.deliveredInputs).toEqual(oldState.deliveredInputs); + expect(state.checkpoint.round).toBe(0); + expect(state.manifest.maxCorrections).toBe(3); + expect(state.manifest.maxApiRepairs).toBe(3); + expect(state.manifest.maxResponseCorrections).toBe(2); + expect(state.checkpoint.dispatchable).toBe(true); + expect(state.calls.at(-1).status).toBe("failed_without_result"); + expect(state.calls.at(-1).result).toBe(undefined); + expect(state.checkpoint.feedbackInputs).toContain(fixture.note); + const resultPath = state.checkpoint.feedback.find((path: string) => + path.endsWith("/result.json"), + ); + const result = JSON.parse(yield* readTextFile(resultPath)); + for (const key of [ + "outcome", + "revision", + "summary", + "handoff", + "assessment", + "artifacts", + "evidence", + "findings", + ]) { + expect(result[key]).toEqual(fixture.result[key]); + } + const journal = (yield* readTextFile(run.journal)) + .trim() + .split("\n") + .map((line) => parseDurableEvent(line)); + const paths = journal.flatMap((item) => + item.ok && + item.value.type === "yield" && + item.value.description.type === "import_component" && + item.value.result.status === "ok" + ? [JSON.stringify(item.value.result.value)] + : [], + ); + for (const name of ["Ticket/ReconcileResponse.md", "Phase/Extract.ts"]) { + expect(paths.some((path) => path.includes("/recovery/components/" + name))).toBe(true); + } + expect( + paths.some( + (path) => + path.includes(fixture.ownerComponents + "/Ticket/LoadState.ts") && + path.includes("./control.ts"), + ), + ).toBe(true); + const returned = JSON.parse(run.stdout); + const recordPath = join(fixture.directory, "confirmed-return.json"); + yield* writeTextFile(recordPath, JSON.stringify(returned)); + return { returned, state, recordPath, resultPath }; +} + +describe("joined original response recovery", () => { + it("P3/P5: the native file entry preserves history and the original Haiku allocation", function* () { + const fixture = yield* recoveryFixture(); + const success = yield* accepted(fixture); + expect(success.state.checkpoint.gate).toBe("planner-review"); + expect(success.state.manifest.roles.implementor.model).toBe("haiku"); + }); + it("P9: an actual Node CLI loads the composed entry and TypeScript forwarding module", function* () { + yield* accepted(yield* recoveryFixture(), "node"); + }); + it("P3: a current-shaped matching owner uses the same direct native component", function* () { + const fixture = yield* recoveryFixture({ historical: false }); + const returned = yield* directRecovery(fixture); + expect(returned).toMatchObject({ status: "paused", publication: "confirmed" }); + }); + for (const route of ["absent", "predicted", "actual"] satisfies ( + | "absent" + | "predicted" + | "actual" + )[]) { + it("P3: actual Architect-first policy accepts the " + route + " routing form", function* () { + const fixture = yield* recoveryFixture({ architecture: true, route }); + const success = yield* accepted(fixture); + expect(success.state.checkpoint.gate).toBe("architect-review"); + expect(success.state.checkpoint.reviewPolicy.reviewers).toEqual(["architect", "planner"]); + }); + } + it("P6: a confirmed repeat uses snapshots after origins disappear, while the old hold stays held", function* () { + const fixture = yield* recoveryFixture(); + const success = yield* accepted(fixture); + const before = yield* originalFiles(fixture.ticket); + const proof = JSON.parse(yield* readTextFile(fixture.proof)); + for (const path of [ + fixture.proof, + proof.amendment.path, + proof.provenance.path, + proof.join.path, + fixture.note, + ]) { + yield* rm(path); + } + const repeated = yield* reconcile(fixture, "deno", success.recordPath); + expect(JSON.parse(repeated.stdout)).toEqual(success.returned); + yield* unchanged(before); + const old = yield* reconcile(fixture); + expect(JSON.parse(old.stdout)).toMatchObject({ + publication: "held", + continuation: fixture.record.continuation, + }); + yield* unchanged(before); + }); + for (const architectFirst of [false, true]) { + it( + "P3: ordinary original " + + (architectFirst ? "Architect/Sol" : "Sol") + + " feedback preserves Haiku correction", + function* () { + const fixture = yield* recoveryFixture({ architecture: architectFirst }); + const success = yield* accepted(fixture); + const feedback = yield* originalFeedback(fixture, success.returned, architectFirst); + expect(feedback.solReceivedNote).toBe(true); + expect(feedback.sourceRound).toBe(1); + expect(feedback.prompts.at(-1)?.configuration?.model).toBe("haiku"); + }, + ); + } +}); + +interface Refusal { + name: string; + options?: Parameters[0]; + mutate?(fixture: RecoveryFixture): import("effection").Operation; + reservation: boolean; +} + +function* changeJoin(f: RecoveryFixture, kind: string) { + const p = JSON.parse(yield* readTextFile(f.proof)); + const report = JSON.parse(yield* readTextFile(p.join.path)); + const lines = (yield* readTextFile(report.journal.path)).trimEnd().split("\n"); + const event = JSON.parse(lines[report.journal.line - 1]); + if (kind === "failed" || kind === "cancelled" || kind === "started") { + event.result.value.status = kind; + } + if (kind === "withheld") { + event.result.value.text = ""; + event.result.value.withheld = true; + } + if (kind === "request") { + event.description.input += "changed"; + } + if (kind === "source") { + event.description["executablemd.source-owner"].index = 999999; + } + if (kind === "session-key") { + event.result.value.sessionKey = "foreign"; + } + lines[report.journal.line - 1] = JSON.stringify(event); + yield* writeTextFile(report.journal.path, lines.join("\n") + "\n"); + yield* writeTextFile(report.retainedEvent, lines[report.journal.line - 1]); + const d = descriptor(report.journal.path, lines[report.journal.line - 1] + "\n"); + report.journal.lineDescriptor = { utf8Bytes: d.utf8Bytes, sha256: d.sha256 }; + if (kind === "unjoined" || kind === "execution") { + const native = (yield* readTextFile(report.nativeFinishedSource.path)).trimEnd().split("\n"); + const finished = JSON.parse(native[report.nativeFinishedSource.line - 1]); + if (kind === "unjoined") { + finished.joined = false; + } else { + finished.submission.execution = "foreign"; + } + native[report.nativeFinishedSource.line - 1] = JSON.stringify(finished); + yield* writeTextFile(report.nativeFinishedSource.path, native.join("\n") + "\n"); + report.nativeFinishedSource = { + ...descriptor( + report.nativeFinishedSource.path, + yield* readTextFile(report.nativeFinishedSource.path), + ), + line: report.nativeFinishedSource.line, + }; + } + yield* writeTextFile(p.join.path, JSON.stringify(report)); + p.join = descriptor(p.join.path, yield* readTextFile(p.join.path)); + yield* writeTextFile(f.proof, JSON.stringify(p)); +} + +const refusals: Refusal[] = [ + { + name: "changed whole native log bytes", + reservation: true, + *mutate(f) { + const proof = JSON.parse(yield* readTextFile(f.proof)); + const report = JSON.parse(yield* readTextFile(proof.join.path)); + yield* writeTextFile( + report.nativeFinishedSource.path, + (yield* readTextFile(report.nativeFinishedSource.path)) + "changed\n", + ); + }, + }, + { + name: "changed framed prompt descriptor", + reservation: true, + *mutate(f) { + const proof = JSON.parse(yield* readTextFile(f.proof)); + const report = JSON.parse(yield* readTextFile(proof.join.path)); + report.journal.lineDescriptor.sha256 = "0".repeat(64); + yield* writeTextFile(proof.join.path, JSON.stringify(report)); + proof.join = descriptor(proof.join.path, yield* readTextFile(proof.join.path)); + yield* writeTextFile(f.proof, JSON.stringify(proof)); + }, + }, + ...[ + "failed", + "cancelled", + "started", + "withheld", + "request", + "source", + "session-key", + "unjoined", + "execution", + ].map((kind) => ({ + name: "native proof " + kind, + reservation: true, + *mutate(f: RecoveryFixture) { + yield* changeJoin(f, kind); + }, + })), + { + name: "metadata capacity", + reservation: true, + options: { + reply: (r) => { + const entry = Array.isArray(r.evidence) ? r.evidence[0] : null; + return ( + 'Names ["title","body"].\n' + + JSON.stringify({ ...r, evidence: Array.from({ length: 7000 }, () => entry) }) + ); + }, + }, + }, + { + name: "unconfirmed envelope", + reservation: false, + *mutate(f) { + yield* writeTextFile(f.recordPath, JSON.stringify({ ...f.record, publication: "held" })); + }, + }, + { + name: "foreign work", + reservation: false, + *mutate(f) { + yield* writeTextFile(f.recordPath, JSON.stringify({ ...f.record, work: "foreign" })); + }, + }, + { + name: "changed continuation digest", + reservation: false, + *mutate(f) { + const r = JSON.parse(yield* readTextFile(f.recordPath)); + r.continuation.sha256 = "0".repeat(64); + yield* writeTextFile(f.recordPath, JSON.stringify(r)); + }, + }, + { + name: "missing assignment", + reservation: true, + *mutate(f) { + yield* rm(join(f.ticket, "attempts/0000/assignment.json")); + }, + }, + ...["attempts", "preparations"].map((part) => ({ + name: "occupied later " + part, + reservation: true, + *mutate(f: RecoveryFixture) { + yield* ensureDir(join(f.ticket, part, "0001")); + }, + })), + { + name: "wrong selected owning schema", + reservation: false, + *mutate(f) { + const original = yield* readTextFile( + "examples/adversarial-implementation/components/Ticket/Schema.md", + ); + yield* writeTextFile(join(f.ownerComponents, "Ticket/Schema.md"), original); + }, + }, + { + name: "changed final call", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "calls/0000/call.json"); + const call = JSON.parse(yield* readTextFile(p)); + call.initialize = !call.initialize; + yield* writeTextFile(p, JSON.stringify(call)); + }, + }, + { + name: "occupied later call", + reservation: true, + *mutate(f) { + yield* ensureDir(join(f.ticket, "calls/0001")); + }, + }, + { + name: "changed owning definition", + reservation: false, + *mutate(f) { + const p = join(f.ownerComponents, "Ticket/LoadState.ts"); + yield* writeTextFile(p, (yield* readTextFile(p)) + "\n"); + }, + }, + { + name: "changed frozen guide", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "attempts/0000/submission-guide.md"); + yield* writeTextFile(p, (yield* readTextFile(p)) + "changed"); + }, + }, + { + name: "changed selected snapshot", + reservation: true, + *mutate(f) { + const s = JSON.parse(yield* readTextFile(envelope.parse(f.record).continuation.path)); + yield* writeTextFile(s.calls[0].inputs[0].snapshot, "changed"); + }, + }, + { + name: "wrong delivery model", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "attempts/0000/delivery.json"); + const d = JSON.parse(yield* readTextFile(p)); + d.profile.model = "opus"; + yield* writeTextFile(p, JSON.stringify(d)); + }, + }, + { + name: "wrong native identity", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "sessions/original-haiku.json"); + const d = JSON.parse(yield* readTextFile(p)); + d.identity.value = "foreign"; + yield* writeTextFile(p, JSON.stringify(d)); + }, + }, + { + name: "wrong native identity kind", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "sessions/original-haiku.json"); + const d = JSON.parse(yield* readTextFile(p)); + d.identity.kind = "foreign"; + d.started.identity.kind = "foreign"; + yield* writeTextFile(p, JSON.stringify(d)); + }, + }, + { + name: "corrupt mandatory unproved-acceptance note", + reservation: false, + *mutate(f) { + yield* writeTextFile(f.note, "changed"); + }, + }, + { + name: "failure outside extraction", + reservation: true, + *mutate(f) { + const p = join(f.ticket, "attempts/0000/response-disposition.json"); + const d = JSON.parse(yield* readTextFile(p)); + d.lastRejection.code = "schema"; + yield* writeTextFile(p, JSON.stringify(d)); + }, + }, + { + name: "existing canonical result", + reservation: true, + *mutate(f) { + yield* writeTextFile(join(f.ticket, "attempts/0000/result.json"), JSON.stringify(f.result)); + }, + }, + { + name: "competing result objects", + reservation: true, + options: { + reply: (r) => + "Progress.\n" + JSON.stringify(r) + "\n" + JSON.stringify({ ...r, work: "wrong" }), + }, + }, + { + name: "wrong explicit work", + reservation: true, + options: { + reply: (r) => 'Names ["title","body"].\n' + JSON.stringify({ ...r, work: "wrong" }), + }, + }, + { name: "unrelated explicit route", reservation: true, options: { route: "wrong" } }, + { + name: "missing role-guide required arrays", + reservation: true, + options: { + reply: (r) => { + const { discoveryRequests, discoveryGaps, ...rest } = r; + return 'Names ["title","body"].\n' + JSON.stringify(rest); + }, + }, + }, + { + name: "dirty source", + reservation: true, + *mutate(f) { + yield* writeTextFile(join(f.repository, "tracked"), "dirty"); + }, + }, + { + name: "wrong resulting HEAD", + reservation: true, + *mutate(f) { + git(["reset", "--hard", f.launch], f.repository, f.directory); + }, + }, + { name: "signed non-descendant", reservation: true, options: { source: "unrelated" } }, + { name: "invalid signature", reservation: true, options: { source: "unsigned" } }, + { name: "changed migration-owned path", reservation: true, options: { apiOwned: true } }, + { + name: "unreadable proof", + reservation: false, + *mutate(f) { + yield* rm(f.proof); + }, + }, + { + name: "descriptor mismatch", + reservation: false, + *mutate(f) { + const p = JSON.parse(yield* readTextFile(f.proof)); + p.amendment.sha256 = "0".repeat(64); + yield* writeTextFile(f.proof, JSON.stringify(p)); + }, + }, + { + name: "over-bound handoff references", + reservation: false, + *mutate(f) { + const p = JSON.parse(yield* readTextFile(f.proof)); + p.handoffInputs = Array.from({ length: 13 }, () => p.handoffInputs[0]); + yield* writeTextFile(f.proof, JSON.stringify(p)); + }, + }, + { + name: "duplicate handoff references", + reservation: false, + *mutate(f) { + const p = JSON.parse(yield* readTextFile(f.proof)); + p.handoffInputs.push(p.handoffInputs[0]); + yield* writeTextFile(f.proof, JSON.stringify(p)); + }, + }, + { + name: "missing mandatory unproved-acceptance note", + reservation: false, + *mutate(f) { + const p = JSON.parse(yield* readTextFile(f.proof)); + p.handoffInputs = []; + yield* writeTextFile(f.proof, JSON.stringify(p)); + }, + }, +]; + +describe("joined recovery conjunctive refusals", () => { + for (const row of refusals) { + it("P4/P5: " + row.name, function* () { + const fixture = yield* recoveryFixture(row.options); + if (row.mutate !== undefined) { + yield* row.mutate(fixture); + } + const before = yield* originalFiles(fixture.ticket); + const prompts = fixture.native.host.fake.prompts.length; + const run = yield* reconcile(fixture); + let value: unknown = null; + try { + value = JSON.parse(run.stdout); + } catch { + /* A root prop refusal need not return JSON. */ + } + const returned = envelope.safeParse(value); + expect(returned.success && returned.data.publication === "confirmed").toBe(false); + expect(run.stderr + run.stdout).not.toContain("ForbiddenReconciliation"); + expect(fixture.native.host.fake.prompts.length).toBe(prompts); + yield* unchanged(before); + const reservation = join( + fixture.ticket, + "reconciliations", + z.object({ continuation: z.object({ sha256: z.string() }) }).parse(fixture.record) + .continuation.sha256, + ); + expect((yield* API.Fs.operations.stat(reservation)).exists).toBe(row.reservation); + if (row.reservation) { + expect( + JSON.parse(yield* readTextFile(join(reservation, "disposition.json"))), + ).toMatchObject({ status: "refused" }); + const saved = yield* originalFiles(fixture.ticket); + const again = yield* reconcile(fixture); + expect(envelope.parse(JSON.parse(again.stdout)).publication).toBe("held"); + yield* unchanged(saved); + } + }); + } +}); + +describe("joined recovery publication boundaries", () => { + for (const cut of cuts) { + it("P6: " + cut + " never adopts matching files or repeats publication", function* () { + const fixture = yield* recoveryFixture(); + const before = yield* originalFiles(fixture.ticket); + const prompts = fixture.native.host.fake.prompts.length; + const interrupted = yield* interruptedRecovery(fixture, cut); + expect(interrupted.injected).toBe(true); + expect(interrupted.laterWrites).toEqual([]); + if (interrupted.returned !== undefined) { + expect(interrupted.returned).not.toMatchObject({ publication: "confirmed" }); + } else { + expect(interrupted.failure).not.toBe(null); + } + yield* unchanged(before); + const retained = yield* originalFiles(fixture.ticket); + const old = yield* directRecovery(fixture); + expect(old).toMatchObject({ publication: "held", continuation: fixture.record.continuation }); + yield* unchanged(retained); + expect(fixture.native.host.fake.prompts.length).toBe(prompts); + }); + } + it("P6: one real exclusive reservation wins against a concurrent contender", function* () { + const fixture = yield* recoveryFixture(); + const result = yield* contenders(fixture); + expect(result.requests).toBe(1); + expect(result.winner).toMatchObject({ publication: "confirmed", status: "paused" }); + expect(result.second).toMatchObject({ + publication: "held", + continuation: fixture.record.continuation, + }); + }); +}); + +describe("joined recovery missing call member", () => { + it("P4: a removed original receipt member refuses against the complete retained call", function* () { + const fixture = yield* recoveryFixture(); + const path = join(fixture.ticket, "calls/0000/call.json"); + const call = JSON.parse(yield* readTextFile(path)); + delete call.initialize; + yield* writeTextFile(path, JSON.stringify(call)); + const before = yield* originalFiles(fixture.ticket); + const prompts = fixture.native.host.fake.prompts.length; + const run = yield* reconcile(fixture); + expect(JSON.parse(run.stdout)).toMatchObject({ + publication: "held", + continuation: fixture.record.continuation, + }); + expect(run.stdout).toContain("original final call receipt changed"); + expect(fixture.native.host.fake.prompts.length).toBe(prompts); + yield* unchanged(before); + }); +}); diff --git a/packages/cli/tests/support/headless-repl.ts b/packages/cli/tests/support/headless-repl.ts index 155a181c6..ad0f7ca8a 100644 --- a/packages/cli/tests/support/headless-repl.ts +++ b/packages/cli/tests/support/headless-repl.ts @@ -290,13 +290,15 @@ export function* useHeadlessFixture( dataRoot?: string, native?: { formCapable?: boolean; + advertiseNativeLaunch?: readonly string[]; + advertiseClientNativeAttachment?: readonly string[]; event?(event: AcpRuntimeEvent): void; /** Replace one raw ACP runtime event before `consumeTurn` reads it. */ transform?(event: AcpRuntimeEvent): AcpRuntimeEvent; permission?(request: AcpPermissionRequest): void; beforeClose?(): Operation; }, - profileFacts: Pick = {}, + profileFacts: Pick = {}, plugins: readonly Plugin[] = [], ) { const scope = yield* useScope(); @@ -342,6 +344,12 @@ export function* useHeadlessFixture( observeChildRoot: (root) => children.push(root), acp: { sessionStore: store, + ...(native?.advertiseNativeLaunch === undefined + ? {} + : { advertiseNativeLaunch: native.advertiseNativeLaunch }), + ...(native?.advertiseClientNativeAttachment === undefined + ? {} + : { advertiseClientNativeAttachment: native.advertiseClientNativeAttachment }), agentRegistry: makeRegistry({ [MOUNTED_AGENT]: `${MOUNTED_AGENT}-cmd` }), createRuntime(options) { const configured = diff --git a/packages/cli/tests/support/joined-response-boundaries.ts b/packages/cli/tests/support/joined-response-boundaries.ts new file mode 100644 index 000000000..860e37e8c --- /dev/null +++ b/packages/cli/tests/support/joined-response-boundaries.ts @@ -0,0 +1,169 @@ +import { readTextFile, writeTextFile } from "@effectionx/fs"; +import { API, Permissions } from "@executablemd/runtime"; +import { scoped } from "effection"; +import { join } from "node:path"; +import { expect } from "@executablemd/test-support/expect"; +import { describe } from "../../../../examples/adversarial-implementation/components/Ticket/text-storage.ts"; +import { directRecovery, recoveryFixture, reconcile } from "./joined-response-recovery.ts"; + +export function proofBoundary(scenario: string) { + return scoped(function* () { + const fixture = yield* recoveryFixture(); + let writes = 0; + let sourceCommands = 0; + let denied = false; + let proofChanged = false; + const namedProof = JSON.parse(yield* readTextFile(fixture.proof)); + const before = fixture.native.host.fake.prompts.length; + if (scenario === "selected-capacity") { + yield* writeTextFile( + fixture.note, + "Unproved A6/A4/A8/A2/A7 and unfinished-root.\n" + "witness ".repeat(9000), + ); + const proof = JSON.parse(yield* readTextFile(fixture.proof)); + proof.handoffInputs = [describe(fixture.note, yield* readTextFile(fixture.note))]; + yield* writeTextFile(fixture.proof, JSON.stringify(proof)); + } + if (scenario.startsWith("repeat-")) { + const accepted = yield* directRecovery(fixture); + expect(accepted).toMatchObject({ publication: "confirmed", status: "paused" }); + const continuation = accepted.continuation; + if ( + continuation === null || + Array.isArray(continuation) || + typeof continuation !== "object" || + typeof continuation.path !== "string" + ) { + throw new Error("Missing confirmed descriptor."); + } + yield* API.Files.around({ + *writeTextFile([input], next) { + writes++; + return yield* next(input); + }, + }); + yield* API.Process.around({ + *exec([input], next) { + sourceCommands++; + return yield* next(input); + }, + }); + if (scenario === "repeat-proof") { + expect(yield* directRecovery(fixture, accepted)).toEqual(accepted); + expect(writes).toBe(0); + expect(sourceCommands).toBe(0); + } + const state = JSON.parse(yield* readTextFile(continuation.path)); + if (scenario === "repeat-proof") { + fixture.proof = join(fixture.directory, "different-proof.json"); + } else if (scenario === "repeat-snapshot") { + yield* writeTextFile(state.documents[fixture.proof].snapshot, "corrupt retained proof"); + } else { + const path = state.checkpoint.feedback.find((path: string) => + path.endsWith("/disposition.json"), + ); + const disposition = JSON.parse(yield* readTextFile(path)); + disposition.derivative.sha256 = "0".repeat(64); + // A descriptor-valid contradictory disposition still cannot change its derivative link. + const text = JSON.stringify(disposition); + yield* writeTextFile(state.documents[path].snapshot, text); + Object.assign(state.documents[path], describe(path, text)); + const retained = join(fixture.directory, "contradictory-continuation.json"); + const retainedText = JSON.stringify(state); + yield* writeTextFile(retained, retainedText); + accepted.continuation = describe(retained, retainedText); + } + const repeated = yield* directRecovery(fixture, accepted); + expect(repeated).toMatchObject({ publication: "held", continuation: accepted.continuation }); + expect(writes).toBe(0); + expect(sourceCommands).toBe(0); + const reason = JSON.stringify(repeated); + expect(reason).toContain( + scenario === "repeat-proof" + ? "proof reference" + : scenario === "repeat-linkage" + ? "linkage changed" + : "Retained ticket text changed", + ); + } else if (scenario === "public-props") { + for (const name of ["role", "model", "revision", "candidate", "raw", "permission"]) { + const child = yield* reconcile(fixture, "deno", fixture.recordPath, [ + "--props-" + name, + "unauthorized", + ]); + expect(child.exitCode).not.toBe(0); + let failed = false; + try { + yield* directRecovery(fixture, fixture.record, { [name]: "unauthorized" }); + } catch { + failed = true; + } + expect(failed).toBe(true); + } + expect((yield* API.Fs.operations.stat(join(fixture.ticket, "reconciliations"))).exists).toBe( + false, + ); + } else { + yield* API.Files.around({ + *readTextFile([input], next) { + if (scenario === "current-permission" && join(input.cwd, input.path) === fixture.proof) { + return yield* scoped(function* () { + denied = true; + yield* Permissions.around({ + files: ([verb], pass) => (verb === "read" ? false : pass(verb)), + }); + return yield* next(input); + }); + } + return yield* next(input); + }, + *writeTextFile([input], next) { + if (scenario === "final-source" && input.path.endsWith("disposition.json")) { + yield* writeTextFile( + join(fixture.repository, "tracked"), + "source changed before publication\n", + ); + } + const written = yield* next(input); + if ( + scenario === "late-proof" && + !proofChanged && + input.path.endsWith("disposition.json") + ) { + proofChanged = true; + yield* writeTextFile( + namedProof.amendment.path, + "Changed after validation before snapshots.\n", + ); + } + return written; + }, + }); + const result = yield* directRecovery(fixture); + expect(result).toMatchObject({ + publication: "held", + continuation: fixture.record.continuation, + }); + const reservation = join(fixture.ticket, "reconciliations"); + if (scenario === "current-permission") { + expect(denied).toBe(true); + expect((yield* API.Fs.operations.stat(reservation)).exists).toBe(false); + } else { + const children = yield* API.Fs.operations.readDirectory(reservation); + const refusal = JSON.parse( + yield* readTextFile(join(reservation, children[0].name, "publication-refusal.json")), + ); + expect(refusal.status).toBe("refused"); + expect(refusal.reason).toContain( + scenario === "final-source" + ? "Source changed" + : scenario === "late-proof" + ? "recovery input changed" + : "input capacity", + ); + } + } + expect(fixture.native.host.fake.prompts.length).toBe(before); + return { scenario, refused: true, writes, sourceCommands, noProviderCalls: true }; + }); +} diff --git a/packages/cli/tests/support/joined-response-feedback.ts b/packages/cli/tests/support/joined-response-feedback.ts new file mode 100644 index 000000000..516ced2b6 --- /dev/null +++ b/packages/cli/tests/support/joined-response-feedback.ts @@ -0,0 +1,219 @@ +import { readTextFile, writeTextFile } from "@effectionx/fs"; +import { Ok, suspend } from "effection"; +import { join } from "node:path"; +import { z } from "zod"; +import { parseDurableEvent } from "@executablemd/durable-streams"; +import type { PromptRecord } from "@executablemd/agent/host"; +import { parsePromptRecord } from "@executablemd/agent/host"; +import { runReplSubmit } from "../../src/sidekick-acp/submit.ts"; +import { SubmitRecord } from "../../src/sidekick-acp/protocol.ts"; +import { git } from "../../../git/tests/support/git-remotes.ts"; +import type { RecoveryFixture } from "./joined-response-recovery.ts"; +import type { Json } from "@executablemd/core"; + +function* nativeStep(fixture: RecoveryFixture, record: Record) { + const records: SubmitRecord[] = []; + const source = + "---\nreturns: {type: object}\n---\n'; + const status = yield* runReplSubmit( + ["repl", "submit", "--attach", fixture.native.reference.sessionId, "-"], + function* () { + return Ok(source); + }, + suspend(), + function* (record) { + records.push(record); + }, + (message) => { + throw new Error(message); + }, + ); + const final = records.at(-1); + if ( + status !== 0 || + final?.kind !== "finished" || + final.outcome !== "completed" || + final.result === null || + final.submission === null + ) { + throw new Error("Ordinary native continuation did not join: " + JSON.stringify(final)); + } + const returned = z.record(z.string(), z.json()).parse(final.result.value); + yield* writeTextFile( + join(fixture.directory, "continuation-" + final.submission.entry + ".jsonl"), + records.map((record) => JSON.stringify(record)).join("\n") + "\n", + ); + return returned; +} + +export function* originalFeedback( + fixture: RecoveryFixture, + record: Record, + architectFirst: boolean, +) { + const originalSession = fixture.native.host.fake.turns[0]?.handle.sessionKey; + const base = { + schema: "phase-result.v2", + phase: "review", + work: "controlled-recovery", + revision: fixture.revision, + summary: "Reconcile the recorded controlled acceptance rows.", + handoff: "Original Implementor: supply the missing controlled witness.", + artifacts: [fixture.note], + evidence: [], + findings: [], + discoveryRequests: [], + discoveryGaps: [], + }; + let current = record; + if (architectFirst) { + fixture.native.host.fake.script({ + reply: JSON.stringify({ + ...base, + outcome: "pass", + next: { phase: "review", role: "planner" }, + }), + }); + current = yield* nativeStep(fixture, current); + } + fixture.native.host.fake.script({ + reply: JSON.stringify({ + ...base, + outcome: "missing_evidence", + assessment: { + mechanical: false, + architecture: false, + acceptance: true, + risk: null, + reason: "Supply the controlled missing acceptance witness.", + evidence: [fixture.note], + }, + next: { phase: "implementation", role: "implementor" }, + }), + }); + current = yield* nativeStep(fixture, current); + const solPrompt = fixture.native.host.fake.prompts.at(-1) ?? ""; + const note = yield* readTextFile(fixture.note); + if (!solPrompt.includes(fixture.revision) || !solPrompt.includes(JSON.stringify(note))) { + throw new Error( + "Original Sol did not receive the exact feedback SHA and separately selected complete note.", + ); + } + const state = z.object({ continuation: z.object({ path: z.string() }) }).parse(current); + const before = JSON.parse(yield* readTextFile(state.continuation.path)); + if ( + before.calls.at(-1).session !== "original-sol" || + before.checkpoint.gate !== "implementation" || + before.checkpoint.round !== 1 + ) { + throw new Error("Missing evidence did not retain the original Sol/correction route."); + } + yield* writeTextFile( + join(fixture.repository, "tracked"), + "controlled missing witness supplied\n", + ); + git(["add", "tracked"], fixture.repository, fixture.directory); + git(["commit", "-qm", "controlled correction"], fixture.repository, fixture.directory); + const corrected = git(["rev-parse", "HEAD"], fixture.repository, fixture.directory).trim(); + git(["reset", "--hard", fixture.revision], fixture.repository, fixture.directory); + const fake = fixture.native.host.fake; + const create = fake.create.bind(fake); + let changed = false; + fake.create = (options) => { + const runtime = create(options); + const start = runtime.startTurn.bind(runtime); + return { + ...runtime, + startTurn(input) { + if (!changed) { + changed = true; + git(["reset", "--hard", corrected], fixture.repository, fixture.directory); + } + return start(input); + }, + }; + }; + fixture.native.host.fake.script({ + reply: JSON.stringify({ + ...fixture.result, + revision: corrected, + assessment: { + mechanical: false, + architecture: false, + acceptance: true, + risk: null, + reason: "Supplied the controlled missing acceptance witness.", + evidence: [fixture.note], + }, + evidence: [ + { + revision: corrected, + command: "controlled correction check", + outcome: "passed", + artifact: fixture.note, + }, + ], + next: { phase: "review", role: "planner" }, + }), + }); + current = yield* nativeStep(fixture, current); + const after = JSON.parse( + yield* readTextFile( + z.object({ continuation: z.object({ path: z.string() }) }).parse(current).continuation.path, + ), + ); + if ( + after.calls.at(-1).session !== "original-haiku" || + after.calls.at(-1).profile?.model !== "haiku" || + after.manifest.roles.implementor.model !== "haiku" || + after.checkpoint.round !== 1 || + after.manifest.maxCorrections !== 3 || + after.manifest.maxApiRepairs !== 3 || + after.manifest.maxResponseCorrections !== 2 || + fixture.native.host.fake.turns.at(-1)?.handle.sessionKey !== originalSession + ) { + throw new Error( + "The correction changed its original Implementor identity, model or allowance.", + ); + } + const child = fixture.native.children[0]; + if (child === undefined) { + throw new Error("Original native child unavailable."); + } + const journal = yield* readTextFile( + join(fixture.native.host.root, "v1", child.execution, "entries.jsonl"), + ); + const prompts: Pick[] = []; + for (const line of journal.trimEnd().split("\n")) { + const event = parseDurableEvent(line); + if (!event.ok) { + throw event.error; + } + if (event.value.type === "yield") { + if (event.value.description.name === "Ticket.SelectModel") { + throw new Error("Ordinary continuation selected another model."); + } + if (event.value.description.type === "agent_prompt" && event.value.result.status === "ok") { + const prompt = parsePromptRecord(event.value.result.value); + if (prompt !== undefined) { + prompts.push({ + agent: prompt.agent, + sessionKey: prompt.sessionKey, + status: prompt.status, + configuration: prompt.configuration, + }); + } + } + } + } + return { + record: current, + corrected, + prompts, + solReceivedNote: true, + originalSession, + sourceRound: after.checkpoint.round, + }; +} diff --git a/packages/cli/tests/support/joined-response-interruption.ts b/packages/cli/tests/support/joined-response-interruption.ts new file mode 100644 index 000000000..4af2f8771 --- /dev/null +++ b/packages/cli/tests/support/joined-response-interruption.ts @@ -0,0 +1,130 @@ +import { Component } from "@executablemd/core/api"; +import { API } from "@executablemd/runtime"; +import { scoped, spawn, withResolvers } from "effection"; +import { join } from "node:path"; +import { directRecovery } from "./joined-response-recovery.ts"; +import type { RecoveryFixture } from "./joined-response-recovery.ts"; + +export const cuts = [ + "after-reservation", + "derivative-before-commit", + "derivative-unknown", + "after-derivative", + "continuation-before-commit", + "continuation-unknown", + "confirmation-before-write", + "confirmation-unknown", + "native-return-unavailable", +]; + +export function interruptedRecovery(fixture: RecoveryFixture, cut: string) { + return scoped(function* () { + let injected = false; + const writes: string[] = []; + const laterWrites: string[] = []; + function stop() { + injected = true; + throw new Error("ControlledRecoveryCut: " + cut); + } + yield* API.Files.around({ + *writeTextFile([input], next) { + const path = join(input.cwd, input.path); + if (path.startsWith(fixture.ticket + "/")) { + writes.push(path); + if (injected) { + laterWrites.push(path); + } + if ( + !injected && + ((cut === "after-reservation" && path.endsWith("/request.json")) || + (cut === "after-derivative" && path.endsWith("/disposition.json")) || + (cut === "confirmation-before-write" && path.endsWith("/confirmation.json"))) + ) { + stop(); + } + } + return yield* next(input); + }, + }); + yield* API.Fs.around({ + *rename([source, destination], next) { + const selected = + destination.startsWith(fixture.ticket + "/") && + ((cut.startsWith("derivative-") && + /\/reconciliations\/[a-f0-9]{64}\/result.json$/.test(destination)) || + (cut.startsWith("continuation-") && destination.includes("/continuations/")) || + (cut === "confirmation-unknown" && destination.endsWith("/confirmation.json"))); + if (!injected && selected && cut.endsWith("before-commit")) { + stop(); + } + yield* next(source, destination); + if (!injected && selected) { + stop(); + } + }, + }); + yield* Component.around({ + *expand([request], next) { + yield* next(request); + if ( + !injected && + cut === "native-return-unavailable" && + request.expansion.name === "Ticket.ReconcileResponse" + ) { + stop(); + } + }, + }); + let returned: unknown; + let failure: unknown; + try { + returned = yield* directRecovery(fixture); + } catch (error) { + failure = error; + } + return { + injected, + writes, + laterWrites, + returned, + failure: failure instanceof Error ? failure.message : null, + }; + }); +} + +export function contenders(fixture: RecoveryFixture) { + return scoped(function* () { + const reached = withResolvers(); + const release = withResolvers(); + let entered = false; + let requests = 0; + yield* API.Files.around({ + *writeTextFile([input], next) { + if ( + join(input.cwd, input.path).startsWith(fixture.ticket + "/reconciliations/") && + input.path.endsWith("request.json") + ) { + requests++; + if (!entered) { + entered = true; + reached.resolve(); + yield* release.operation; + } + } + return yield* next(input); + }, + }); + const first = yield* spawn(function* () { + return yield* directRecovery(fixture); + }); + let second; + try { + yield* reached.operation; + second = yield* directRecovery(fixture); + } finally { + release.resolve(); + } + const winner = yield* first; + return { requests, winner, second }; + }); +} diff --git a/packages/cli/tests/support/joined-response-recovery.ts b/packages/cli/tests/support/joined-response-recovery.ts new file mode 100644 index 000000000..395fab992 --- /dev/null +++ b/packages/cli/tests/support/joined-response-recovery.ts @@ -0,0 +1,484 @@ +import { ensureDir, readTextFile, writeTextFile } from "@effectionx/fs"; +import { until, Ok, suspend, scoped } from "effection"; +import { symlink, mkdtemp } from "node:fs/promises"; +import { join, resolve, dirname } from "node:path"; +import { useComponentModuleLoader } from "@executablemd/test-support/host"; +import { useTempDirectory } from "@executablemd/test-support/temp"; +import { z } from "zod"; +import { Agent } from "@executablemd/agent/api"; +import type { Json } from "@executablemd/core"; +import { collect, useNormalizedOutput } from "@executablemd/core"; +import { executeInstalled } from "@executablemd/core/host"; +import { useHostFiles } from "@executablemd/runtime"; +import { InMemoryStream, parseDurableEvent } from "@executablemd/durable-streams"; +import { API, realpath, env, Permissions } from "@executablemd/runtime"; +import { git } from "../../../git/tests/support/git-remotes.ts"; +import { runReplSubmit } from "../../src/sidekick-acp/submit.ts"; +import { SubmitRecord } from "../../src/sidekick-acp/protocol.ts"; +import { useHeadlessFixture } from "./headless-repl.ts"; +import { describe } from "../../../../examples/adversarial-implementation/components/Ticket/text-storage.ts"; +import sourceBoundary from "../fixtures/joined-response-owner/git-boundary.ts"; + +const root = resolve("."); +const overlay = join(root, "examples/adversarial-implementation/recovery/components"); +const entry = join(root, "examples/adversarial-implementation/reconcile-response.md"); +const manifestPath = join(root, "packages/cli/tests/fixtures/joined-response-owner/manifest.json"); +const manifestSchema = z.object({ + files: z.array(z.object({ originalPath: z.string(), source: z.string(), sha256: z.string() })), +}); +const object = z.record(z.string(), z.json()); + +export function* recoveryFixture( + options: { + architecture?: boolean; + route?: "absent" | "predicted" | "actual" | "wrong"; + source?: "unsigned" | "unrelated"; + apiOwned?: boolean; + historical?: boolean; + reply?: (result: Record) => string; + } = {}, +) { + const evidenceDirectory = yield* env("XMD_RECOVERY_EVIDENCE_DIRECTORY"); + if (evidenceDirectory !== undefined) { + yield* ensureDir(evidenceDirectory); + } + const temporary = + evidenceDirectory === undefined + ? yield* useTempDirectory("joined-response-") + : yield* until(mkdtemp(join(evidenceDirectory, "fixture-"))); + const directory = (yield* realpath(temporary)) ?? temporary; + const repository = join(directory, "source"); + const owner = join(directory, "owner"); + yield* ensureDir(repository); + yield* ensureDir(owner); + const manifest = manifestSchema.parse(JSON.parse(yield* readTextFile(manifestPath))); + for (const file of manifest.files) { + if (options.historical === false && file.originalPath.endsWith("Ticket/SelectModel.md")) { + continue; + } + const sourcePath = + options.historical === false && !file.originalPath.endsWith("Phase/Extract.ts") + ? file.originalPath + : file.source; + const text = yield* readTextFile(join(root, sourcePath)); + if (sourcePath === file.source && describe(file.source, text).sha256 !== file.sha256) { + throw new Error("Changed fixture source: " + file.source); + } + const target = join(owner, file.originalPath); + yield* ensureDir(dirname(target)); + yield* writeTextFile(target, text); + } + yield* until(symlink(join(root, "node_modules"), join(owner, "node_modules"))); + yield* writeTextFile(join(owner, ".gitignore"), "node_modules\n"); + const signing = yield* API.Process.operations.exec({ + command: ["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", join(directory, "signer")], + }); + if (signing.exitCode !== 0) { + throw new Error(signing.stderr); + } + yield* writeTextFile( + join(directory, "allowed-signers"), + "fixture " + (yield* readTextFile(join(directory, "signer.pub"))), + ); + for (const selected of [repository, owner]) { + git(["init", "-q"], selected, directory); + for (const [key, value] of Object.entries({ + "user.name": "Fixture", + "user.email": "fixture@example.test", + "commit.gpgsign": "true", + "gpg.format": "ssh", + "user.signingkey": join(directory, "signer"), + "gpg.ssh.allowedSignersFile": join(directory, "allowed-signers"), + })) { + git(["config", key, value], selected, directory); + } + } + yield* writeTextFile(join(repository, "AGENTS.md"), "Use only controlled fixture evidence.\n"); + yield* ensureDir(join(repository, ".agents")); + for (const role of ["implementor", "planner", "architect"]) { + yield* writeTextFile( + join(repository, ".agents", role + ".md"), + "Return the controlled " + role + " fixture result.\n", + ); + } + yield* writeTextFile(join(repository, "tracked"), "launch\n"); + for (const selected of [repository, owner]) { + git(["add", "."], selected, directory); + git(["commit", "-qm", "fixture launch"], selected, directory); + } + const launch = git(["rev-parse", "HEAD"], repository, directory).trim(); + yield* writeTextFile(join(repository, "tracked"), "implementation\n"); + git(["add", "tracked"], repository, directory); + git( + [ + ...(options.source === "unsigned" ? ["-c", "commit.gpgsign=false"] : []), + "commit", + "-qm", + "fixture implementation", + ], + repository, + directory, + ); + const revision = + options.source === "unrelated" + ? git( + [ + "commit-tree", + git(["rev-parse", "HEAD^{tree}"], repository, directory).trim(), + "-S", + "-m", + "unrelated fixture", + ], + repository, + directory, + ).trim() + : git(["rev-parse", "HEAD"], repository, directory).trim(); + git(["reset", "--hard", launch], repository, directory); + const evidence = join(directory, "focused.txt"); + yield* writeTextFile(evidence, "Controlled focused evidence.\n"); + const note = join(directory, "known-unmet-acceptance.md"); + yield* writeTextFile( + note, + "A6/A4/A8/A2/A7 and unfinished-root replay remain unproved. Original Sol must reconcile every frozen row; original Haiku owns corrections.\n", + ); + const assessment = { + mechanical: false, + architecture: false, + acceptance: true, + risk: null, + reason: "Controlled accepted behavior.", + evidence: [evidence], + }; + const result: Record = { + schema: "phase-result.v2", + outcome: "complete", + revision, + summary: "Controlled implementation.", + handoff: "Planner: reconcile A6/A4/A8/A2/A7 and unfinished-root replay.", + artifacts: [evidence], + evidence: [ + { revision, command: "controlled focused check", outcome: "passed", artifact: evidence }, + ], + findings: ["A6/A4/A8/A2/A7 and unfinished-root replay remain unproved."], + assessment: { ...assessment, architecture: options.architecture ?? false }, + next: + options.route === "wrong" + ? { phase: "hold", role: null } + : options.route === "actual" && options.architecture + ? { phase: "review", role: "architect" } + : { phase: "review", role: "planner" }, + discoveryRequests: [], + discoveryGaps: [], + }; + if (options.route === "absent") { + delete result.next; + } + const ticket = join(directory, "ticket"); + const ownerComponents = join(owner, "examples/adversarial-implementation/components"); + const manifestFile = join(directory, "manifest.json"); + yield* writeTextFile( + manifestFile, + JSON.stringify({ + schema: "ticket-workflow.v2", + work: "controlled-recovery", + directory: ticket, + assignment: { + phase: "implementation", + work: "controlled-recovery", + repository, + revision: launch, + priorRevision: null, + request: "Implement the controlled accepted plan.", + changedPaths: [], + artifacts: [evidence], + evidence: [], + findings: [], + issue: null, + contract: null, + assessment, + reviewKind: "feature", + recipient: "implementor", + continuation: { phase: "review", role: "planner" }, + }, + roles: { + implementor: { + session: "original-haiku", + provider: "claude", + initialized: false, + ...(options.historical === false ? {} : { model: "haiku" }), + }, + planner: { session: "original-sol", provider: "codex", initialized: false }, + architect: { session: "original-architect", provider: "codex", initialized: false }, + }, + acceptedInputs: [{ path: evidence, content: "Controlled focused evidence.\n" }], + maxCorrections: 3, + maxApiRepairs: 3, + maxResponseCorrections: 2, + ...(options.apiOwned ? { api: { ownedPaths: ["tracked"] } } : {}), + }), + ); + yield* API.Env.around( + { + *cwd() { + return directory; + }, + }, + { at: "min" }, + ); + yield* Permissions.around({ files: () => true }, { at: "min" }); + let moved = false; + yield* Agent.around({ + *prompt(args, next) { + if (!moved) { + moved = true; + git(["reset", "--hard", revision], repository, directory); + } + return yield* next(...args); + }, + }); + yield* useComponentModuleLoader(); + const native = yield* useHeadlessFixture( + undefined, + undefined, + join(directory, "native"), + { advertiseNativeLaunch: [], advertiseClientNativeAttachment: [] }, + { includes: [ownerComponents] }, + [sourceBoundary], + ); + native.host.fake.configuration({ + model: { selected: "haiku", choices: ["haiku", "gpt-6.1-sol", "opus"].map((id) => ({ id })) }, + effort: Object.fromEntries( + ["haiku", "gpt-6.1-sol", "opus"].map((model) => [ + model, + { selected: "high", choices: ["high", "medium"].map((id) => ({ id })) }, + ]), + ), + }); + native.host.fake.script({ + reply: + options.reply?.(result) ?? 'The selection names ["title","body"].\n' + JSON.stringify(result), + }); + const nativeRecords: SubmitRecord[] = []; + const source = + "---\nreturns: {type: object}\n---\n'; + const status = yield* runReplSubmit( + ["repl", "submit", "--attach", native.reference.sessionId, "-"], + function* () { + return Ok(source); + }, + suspend(), + function* (record) { + nativeRecords.push(record); + }, + (message) => { + throw new Error(message); + }, + ); + if (status !== 0) { + console.error("Native fixture failure retained at " + directory); + const child = native.children[0]; + if (child !== undefined) { + const failed = yield* child.session.join(); + if (!failed.ok) { + console.error(failed.error); + } + } + throw new Error( + "The original native entry did not join: " + JSON.stringify(nativeRecords.at(-1)), + ); + } + const finished = nativeRecords.at(-1); + if (finished?.kind !== "finished" || finished.result === null || finished.submission === null) { + throw new Error("Missing actual native completed return."); + } + const record = object.parse(finished.result.value); + const recordPath = join(directory, "original-return.json"); + yield* writeTextFile(recordPath, JSON.stringify(record)); + const journal = join(native.host.root, "v1", finished.submission.execution, "entries.jsonl"); + const journalText = yield* readTextFile(journal); + const lines = journalText.trimEnd().split("\n"); + for (const line of lines) { + const event = parseDurableEvent(line); + if ( + event.ok && + event.value.type === "yield" && + event.value.description.type === "import_component" && + ["Fixture.Owner", "Ticket.Advance"].includes(event.value.description.name) + ) { + throw new Error("The natural extraction-failed entry preloaded an unentered recovery owner."); + } + } + const promptIndex = lines.findIndex((line) => { + const event = parseDurableEvent(line); + return ( + event.ok && event.value.type === "yield" && event.value.description.type === "agent_prompt" + ); + }); + if (promptIndex < 0) { + throw new Error("No original prompt event."); + } + const retainedEvent = join(directory, "original-event.json"); + yield* writeTextFile(retainedEvent, lines[promptIndex]); + const nativeFile = join(directory, "original-native.jsonl"); + yield* writeTextFile( + nativeFile, + nativeRecords.map((record) => JSON.stringify(record)).join("\n") + "\n", + ); + const joinFile = join(directory, "join.json"); + const promptDescriptor = describe(journal, lines[promptIndex] + "\n"); + const nativeDescriptor = describe(nativeFile, yield* readTextFile(nativeFile)); + yield* writeTextFile( + joinFile, + JSON.stringify({ + journal: { + path: journal, + line: promptIndex + 1, + lineDescriptor: { utf8Bytes: promptDescriptor.utf8Bytes, sha256: promptDescriptor.sha256 }, + }, + retainedEvent, + nativeFinishedSource: { ...nativeDescriptor, line: nativeRecords.length }, + }), + ); + const amendment = join(directory, "amendment.md"); + const provenance = join(directory, "provenance.md"); + yield* writeTextFile( + amendment, + "Controlled fixture for the approved no-provider joined-response amendment.\n", + ); + yield* writeTextFile(provenance, "Controlled fixture; no human authority is created.\n"); + const references: ReturnType[] = []; + for (const path of [amendment, provenance, joinFile, note]) { + references.push(describe(path, yield* readTextFile(path))); + } + const proof = join(directory, "proof.json"); + yield* writeTextFile( + proof, + JSON.stringify({ + schema: "joined-response-proof.v1", + amendment: references[0], + provenance: references[1], + join: references[2], + handoffInputs: [references[3]], + }), + ); + return { + directory, + repository, + owner, + ownerComponents, + revision, + launch, + ticket, + record, + recordPath, + proof, + native, + note, + result, + runs: 0, + }; +} + +export type RecoveryFixture = + ReturnType extends import("effection").Operation ? T : never; +export function* reconcile( + fixture: RecoveryFixture, + runtime: "deno" | "node" = "deno", + recordPath = fixture.recordPath, + extra: string[] = [], +) { + const command = + runtime === "node" + ? [ + "node", + join(root, "node_modules/tsx/dist/cli.mjs"), + "--tsconfig", + join(root, "tsconfig.node.json"), + join(root, "packages/cli/src/node.ts"), + ] + : [ + "deno", + "run", + "--allow-all", + "--node-modules-dir=manual", + "--cached-only", + "--frozen", + join(root, "packages/cli/src/deno.ts"), + ]; + const ordinal = fixture.runs++; + const journal = join(fixture.directory, "recovery-" + runtime + "-" + ordinal + ".jsonl"); + const result = yield* API.Process.operations.exec({ + command: [ + ...command, + "run", + "--allow-absolute", + entry, + "--props-record", + recordPath, + "--props-proof", + fixture.proof, + "--include", + overlay, + "--include", + fixture.ownerComponents, + ...(runtime === "node" + ? ["--include", join(root, "packages/cli/tests/fixtures/joined-response-owner/boundary")] + : []), + "--plugin", + join(root, "packages/cli/tests/fixtures/joined-response-owner/no-dispatch.ts"), + "--journal", + journal, + "--raw", + ...extra, + ], + cwd: fixture.repository, + }); + const captured = { + command: [...command, "run", entry], + exitCode: result.exitCode, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + journal, + }; + yield* writeTextFile( + join(fixture.directory, "recovery-" + runtime + "-" + ordinal + "-receipt.json"), + JSON.stringify(captured), + ); + return captured; +} + +export function directRecovery( + fixture: RecoveryFixture, + record: Record = fixture.record, + extra: Record = {}, +) { + return scoped(function* () { + yield* useHostFiles(); + yield* Permissions.around({ files: () => true }, { at: "min" }); + yield* useComponentModuleLoader(); + yield* useNormalizedOutput(); + const install = sourceBoundary.install; + if (install !== undefined) { + yield* install({ command: "run", args: [] }); + } + const path = join(fixture.directory, "direct-recovery.md"); + yield* writeTextFile( + path, + "', + ); + const execution = yield* executeInstalled( + { path, includes: [overlay, fixture.ownerComponents], stream: new InMemoryStream() }, + [], + ); + return object.parse(JSON.parse(z.string().parse(yield* collect(execution)))); + }); +} diff --git a/specs/decisions.md b/specs/decisions.md index a6e8e8095..a214edde5 100644 --- a/specs/decisions.md +++ b/specs/decisions.md @@ -885,3 +885,36 @@ selection and user-approval escalation policy. Existing host containment remains in force with its stable-namespace limitation; #227 owns concurrent path-replacement hardening. Deferring those decisions does not defer File or Glob reads. #679 remains separate evaluation work after product delivery. + +## Joined implementation replies retain their original failure during explicit revalidation + +The joined-phase-result-recovery-1396 amendment permits explicit revalidation of +an unchanged, proven-completed original implementation reply after an extraction +hold. The canonical extractor's rejection of incidental inline arrays is an +implementation defect. Historical revalidation is a separately approved +user-directed amendment: it grants no correction allowance or acceptance waiver. + +The approved decision and delegation are retained at +`/private/tmp/xmd-joined-phase-recovery-1396/approved-decision/decision.md` and +`/private/tmp/xmd-joined-phase-recovery-1396/approved-decision/provenance.md`. +The bounded consumer is the original #1400 hold +`f816aad386057df21b95730b19c6e919673e98615d0c1b93caf2876374d149f6`; +controlled fixtures exercise the same mechanism. Its supported owning workflow +already understands the historical model allocation, so an adapter is unnecessary. + +The [recovery action](../examples/adversarial-implementation/recovery/README.md) +checks the confirmed record, original assignment and frozen guide, selected +inputs, completed provider prompt, joined native entry and clean signed source. +It reserves one append-only reconciliation, records a derivative and disposition, +and confirms publication before returning the original policy's paused feedback +gate. The actual failed execution remains failed; original calls, receipts, +conversations, models and all allowance consumption remain unchanged. No provider +or role runs during reconciliation. The original Sol feedback and Haiku correction +sequence retains A6/A4/A8/A2/A7 and unfinished-root replay as unproved work. + +A confirmed repeat uses the actual returned successor and retained snapshots. +The old hold after a reservation stays held, including when publication or its +confirmation may have committed without acknowledgment. Matching files do not +supply that acknowledgment. This adds no operator-disposition path, compatibility +framework, model selection, interrupted-guide replay, review waiver or merge +permission.