@yaag/runtime 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent.ts +29 -17
  3. package/src/agent/fork.ts +40 -12
  4. package/src/agent/host-fork.ts +85 -0
  5. package/src/agent/spawn-definition-request.ts +38 -3
  6. package/src/agent/spawn-open.ts +43 -103
  7. package/src/agent/spawn-plan.ts +114 -0
  8. package/src/agent/spawn-request.ts +16 -2
  9. package/src/agent/spawn.ts +20 -3
  10. package/src/ask/ask-exchange-options.ts +3 -6
  11. package/src/ask/ask-exchange.ts +48 -108
  12. package/src/ask/ask-guard.ts +207 -0
  13. package/src/ask/ask-timing.ts +12 -0
  14. package/src/ask/index.ts +1 -0
  15. package/src/cassette/cassette-loader.ts +9 -20
  16. package/src/cassette/cassette-schema.ts +10 -1
  17. package/src/cassette/cassette.ts +11 -34
  18. package/src/cassette/checkpoint.ts +306 -0
  19. package/src/cassette/index.ts +16 -7
  20. package/src/cassette/parked-asks.ts +38 -0
  21. package/src/cassette/replay-divergence.ts +7 -102
  22. package/src/cassette/resume-identity.ts +5 -1
  23. package/src/cassette/resume-preconditions.ts +14 -0
  24. package/src/cassette/resume-transport.ts +26 -32
  25. package/src/cassette/run-identity.ts +109 -0
  26. package/src/cassette/session-answer.ts +51 -114
  27. package/src/cassette/spawn-identity.ts +318 -0
  28. package/src/contract/error-codes.ts +1 -0
  29. package/src/contract/index.ts +1 -0
  30. package/src/contract/spawn-options.ts +33 -2
  31. package/src/error-factories.ts +8 -0
  32. package/src/events.ts +4 -2
  33. package/src/index.ts +4 -0
  34. package/src/pi-session/append-tool-result.ts +165 -0
  35. package/src/pi-session/index.ts +30 -0
  36. package/src/pi-session/pi-session-error.ts +34 -0
  37. package/src/pi-session/session-copy.ts +113 -0
  38. package/src/pi-session/session-entries.ts +130 -0
  39. package/src/question-summary/index.ts +4 -8
  40. package/src/question-summary/summarize-question.ts +1 -1
  41. package/src/question-summary/summary-policy.ts +5 -2
  42. package/src/run/agent-questions.ts +82 -0
  43. package/src/run/answers.ts +22 -1
  44. package/src/run/host-session.ts +233 -0
  45. package/src/run/index.ts +7 -0
  46. package/src/run/run-context.ts +3 -0
  47. package/src/run/run.ts +191 -181
  48. package/src/transport/live-transport.ts +19 -0
  49. package/src/transport/pi-state.ts +10 -1
  50. package/src/transport/transport.ts +13 -9
  51. package/src/types.ts +1 -0
  52. package/src/cassette/checkpoint-flush.ts +0 -101
  53. package/src/cassette/run-checkpoint.ts +0 -272
  54. package/src/question-summary/session-copy.ts +0 -169
@@ -0,0 +1,306 @@
1
+ import { unlink } from "node:fs/promises";
2
+ import type { RunOutcome } from "../events.ts";
3
+ import type {
4
+ Cassette,
5
+ CassetteAnswer,
6
+ CassetteQuestion,
7
+ CassetteRecorder,
8
+ CassetteRun,
9
+ CassetteSink,
10
+ } from "./cassette.ts";
11
+ import { publishCassette } from "./cassette-publish.ts";
12
+ import {
13
+ ensureCheckpointDirectory,
14
+ type RunIdentity,
15
+ writeRecordingDiagnostic,
16
+ } from "./run-identity.ts";
17
+
18
+ /** Every outcome a Run settles on; `interrupted` is written only by a flush. */
19
+ export type SettledOutcome = Exclude<RunOutcome, "interrupted">;
20
+
21
+ /**
22
+ * The wake payload of a paused or stopped Run (ADR-0021). It is settlement
23
+ * data, never invocation identity, so it travels beside `RunIdentity`.
24
+ */
25
+ export interface RunWakePayload {
26
+ readonly questions: readonly CassetteQuestion[];
27
+ /** Questions this Run resolved, plus every answer it inherited (ADR-0022). */
28
+ readonly answers?: readonly CassetteAnswer[];
29
+ readonly reason?: string;
30
+ }
31
+
32
+ /** Exactly what `run_end` needs, plus the error a lost promise displaces the Run with. */
33
+ export interface RunEnding {
34
+ readonly outcome: RunOutcome;
35
+ /** Path of the published Checkpoint a paused or stopped Run resumes from (ADR-0054). */
36
+ readonly checkpoint?: string;
37
+ /** Publication error text when a requested Checkpoint was lost (ADR-0021 amendment). */
38
+ readonly checkpointLost?: string;
39
+ /** Set only when a paused or stopped publication failed; the Run throws it after `run_end`. */
40
+ readonly displacedBy?: Error;
41
+ }
42
+
43
+ export interface CheckpointOptions {
44
+ /** Read at each flush and at settlement; its content becomes the artifact. */
45
+ readonly collector: CassetteSink;
46
+ /** Explicit `--record` destination, or undefined when the Run only checkpoints. */
47
+ readonly record: string | undefined;
48
+ /** Where this Run's artifact lives, in-flight and at settlement; fixed at Run start. */
49
+ readonly destination: string;
50
+ readonly identity: RunIdentity;
51
+ }
52
+
53
+ /**
54
+ * One Run's Checkpoint policy (ADR-0021/0031/0054): when the artifact flushes,
55
+ * what each outcome keeps, and what `run_end` may name.
56
+ */
57
+ export interface Checkpoint {
58
+ /** Hand this to the recording transport; it flushes at the four Ask boundaries. */
59
+ readonly sink: CassetteSink;
60
+ /**
61
+ * Records the Run's Host Source hash, once, before the first Agent opens
62
+ * (ADR-0068). It is late-bound on purpose: the Host Session pre-flight runs
63
+ * after `resolveRunIdentity`, so `ARGS_INVALID` and `RECORD_PATH_UNUSABLE`
64
+ * keep their precedence. No flush can precede it: the first flush is
65
+ * `recorder.opened`, and no Agent exists yet.
66
+ */
67
+ identifyHost(host: { readonly hostHash: string }): void;
68
+ /** Quiesce, then publish, then nothing. Idempotent: a second call returns the first ending. */
69
+ settle(outcome: SettledOutcome, wake?: RunWakePayload): Promise<RunEnding>;
70
+ /** Flushes that arrived after settlement; a test reads it, the Run does not. */
71
+ lateFlushes(): number;
72
+ }
73
+
74
+ /**
75
+ * Builds the Run's Checkpoint. No I/O happens here, so a Run that rejects
76
+ * before `run_start` still emits no event and writes no artifact.
77
+ */
78
+ export function createCheckpoint(options: CheckpointOptions): Checkpoint {
79
+ // Mutable, so `identifyHost` can add the run-level Host Source after the
80
+ // identity was resolved; every publication below reads this local.
81
+ let identity = options.identity;
82
+ let active: Promise<void> | null = null;
83
+ let requested = false;
84
+ let settled = false;
85
+ let late = 0;
86
+ let ending: Promise<RunEnding> | null = null;
87
+
88
+ /**
89
+ * Publishes the in-progress artifact (ADR-0031). Flushes never reject: losing
90
+ * this boundary costs one Ask of restorability, while failing the Run would
91
+ * cost the whole Run.
92
+ */
93
+ const publishInterrupted = async (): Promise<void> => {
94
+ try {
95
+ await ensureCheckpointDirectory(options.record, options.destination);
96
+ await publishCassette(
97
+ options.destination,
98
+ options.collector.cassette({ outcome: "interrupted", ...identity }),
99
+ );
100
+ } catch (error) {
101
+ writeRecordingDiagnostic(error);
102
+ }
103
+ };
104
+
105
+ // Only one publication runs at a time, so two Asks settling together cannot
106
+ // interleave two writes onto one destination. A request that arrives during a
107
+ // write is folded into exactly one follow-up write.
108
+ const pump = async (): Promise<void> => {
109
+ while (requested && !settled) {
110
+ requested = false;
111
+ await publishInterrupted();
112
+ }
113
+ active = null;
114
+ };
115
+
116
+ const flush = (): void => {
117
+ // No flush may land after the settled artifact, or an acknowledged Run would
118
+ // be overwritten by an `interrupted` one. The rule is code, not a comment.
119
+ if (settled) {
120
+ late += 1;
121
+ return;
122
+ }
123
+ requested = true;
124
+ active ??= pump();
125
+ };
126
+
127
+ const publishSettled = async (
128
+ outcome: SettledOutcome,
129
+ wake: RunWakePayload | undefined,
130
+ ): Promise<RunEnding> => {
131
+ settled = true;
132
+ while (active !== null) await active;
133
+ if (!keepsCheckpoint(outcome, options.record)) {
134
+ // A clean settlement without --record publishes nothing, so the in-flight
135
+ // artifact this Run flushed goes away with it (ADR-0031).
136
+ await discardCheckpoint(options.destination);
137
+ return { outcome };
138
+ }
139
+ try {
140
+ await ensureCheckpointDirectory(options.record, options.destination);
141
+ await publishCassette(
142
+ options.destination,
143
+ options.collector.cassette({
144
+ outcome,
145
+ ...identity,
146
+ ...wakePayload(outcome, wake),
147
+ }),
148
+ );
149
+ // A Run names a Checkpoint only when publication kept the artifact, and
150
+ // only a paused or stopped Run resumes from one (ADR-0054).
151
+ return namesCheckpoint(outcome) ? { outcome, checkpoint: options.destination } : { outcome };
152
+ } catch (error) {
153
+ return lostOrDisplaced(outcome, error);
154
+ }
155
+ };
156
+
157
+ return {
158
+ sink: flushingSink(options.collector, flush),
159
+ identifyHost: (host) => {
160
+ identity = { ...identity, host };
161
+ },
162
+ settle: (outcome, wake) => {
163
+ ending ??= publishSettled(outcome, wake);
164
+ return ending;
165
+ },
166
+ lateFlushes: () => late,
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Folds one failed publication into the Run's ending. A secondary publication
172
+ * failure must not displace a primary program error, so a failed and a completed
173
+ * Run keep their outcome and report the loss on `run_end` instead. A pausing or
174
+ * stopped Run promises restorability, and a Checkpoint that did not land makes
175
+ * that acknowledgement a lie, so the failure takes the outcome (ADR-0021).
176
+ */
177
+ function lostOrDisplaced(outcome: SettledOutcome, error: unknown): RunEnding {
178
+ if (outcome === "failed") {
179
+ writeRecordingDiagnostic(error);
180
+ return { outcome, checkpointLost: String(error) };
181
+ }
182
+ if (outcome === "completed") {
183
+ const message = `run completed but its Cassette could not be written: ${String(error)}`;
184
+ writeRecordingDiagnostic(message);
185
+ return { outcome, checkpointLost: message };
186
+ }
187
+ return {
188
+ outcome: "failed",
189
+ displacedBy: new Error(`run ${outcome} but is not restorable: ${String(error)}`, {
190
+ cause: error,
191
+ }),
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Whether a Run keeps its artifact: `--record` names a destination, or the Run
197
+ * paused or stopped. Every other Run discards the in-flight artifact, so it
198
+ * names no Checkpoint on `run_end` either (ADR-0054).
199
+ */
200
+ function keepsCheckpoint(outcome: SettledOutcome, record: string | undefined): boolean {
201
+ return record !== undefined || outcome === "stopped" || outcome === "paused";
202
+ }
203
+
204
+ /** Only a paused and a stopped Run resume from a Checkpoint, so only they name one. */
205
+ function namesCheckpoint(outcome: SettledOutcome): boolean {
206
+ return outcome === "paused" || outcome === "stopped";
207
+ }
208
+
209
+ /**
210
+ * The wake payload of a run block. Empty for every outcome other than `paused`
211
+ * and `stopped`, and minimal for a plain `ctx.pause()`, so an artifact that
212
+ * collected nothing keeps the bytes it had before this field existed.
213
+ */
214
+ function wakePayload(
215
+ outcome: SettledOutcome,
216
+ wake: RunWakePayload | undefined,
217
+ ): Pick<CassetteRun, "questions" | "answers" | "reason"> {
218
+ if (wake === undefined || !namesCheckpoint(outcome)) return {};
219
+ return {
220
+ ...(wake.questions.length === 0 ? {} : { questions: wake.questions }),
221
+ ...(wake.answers === undefined || wake.answers.length === 0 ? {} : { answers: wake.answers }),
222
+ ...(wake.reason === undefined ? {} : { reason: wake.reason }),
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Removes the in-progress artifact of a Run that publishes nothing. A missing
228
+ * file is the normal case: the Run may never have reached an Ask boundary. Any
229
+ * other failure is a diagnostic, because the file left behind states
230
+ * `interrupted` and a reader trusts that word (ADR-0031).
231
+ */
232
+ async function discardCheckpoint(destination: string): Promise<void> {
233
+ try {
234
+ await unlink(destination);
235
+ } catch (error) {
236
+ if (!isMissingFile(error)) writeRecordingDiagnostic(error);
237
+ }
238
+ }
239
+
240
+ function isMissingFile(error: unknown): boolean {
241
+ return (
242
+ typeof error === "object" &&
243
+ error !== null &&
244
+ "code" in error &&
245
+ (error as { readonly code?: unknown }).code === "ENOENT"
246
+ );
247
+ }
248
+
249
+ /**
250
+ * Wraps a sink so every Ask boundary publishes the Checkpoint: an Agent opened,
251
+ * an Ask begun, an Ask finished, an Agent closed (ADR-0031).
252
+ */
253
+ function flushingSink(sink: CassetteSink, flush: () => void): CassetteSink {
254
+ return {
255
+ cassette: (run) => sink.cassette(run),
256
+ reserve: (options): CassetteRecorder => {
257
+ const recorder = sink.reserve(options);
258
+ const boundary =
259
+ <Args extends unknown[]>(record: (...args: Args) => void) =>
260
+ (...args: Args): void => {
261
+ record(...args);
262
+ flush();
263
+ };
264
+ return {
265
+ ...recorder,
266
+ opened: boundary(recorder.opened),
267
+ beginAsk: boundary(recorder.beginAsk),
268
+ finishAsk: boundary(recorder.finishAsk),
269
+ closed: boundary(recorder.closed),
270
+ };
271
+ },
272
+ };
273
+ }
274
+
275
+ /** How a caller wants to read a Cassette back: a strict replay, or a resume. */
276
+ export type CassetteReadMode = "replay" | "resume";
277
+
278
+ export type CassetteReadable =
279
+ | { readonly ok: true; readonly warning?: string }
280
+ | { readonly ok: false; readonly reason: string };
281
+
282
+ /**
283
+ * The read-side half of the `interrupted` rule, so the write and the refusal
284
+ * cannot drift. A strict replay demands a settled Run: an `interrupted` artifact
285
+ * stops at the last Ask boundary, so its final Ask has no recorded settlement.
286
+ * A resume continues, with one warning (ADR-0031).
287
+ */
288
+ export function readableCassette(
289
+ cassette: Cassette,
290
+ path: string,
291
+ mode: CassetteReadMode,
292
+ ): CassetteReadable {
293
+ if (cassette.run.outcome !== "interrupted") return { ok: true };
294
+ if (mode === "replay") {
295
+ return {
296
+ ok: false,
297
+ reason: `cannot replay interrupted cassette "${path}": the Run died before it settled; use resume instead`,
298
+ };
299
+ }
300
+ return {
301
+ ok: true,
302
+ warning:
303
+ `resuming interrupted cassette "${path}": the Run died before it settled, ` +
304
+ "the recording stops at the last Ask boundary, and re-run tools can repeat their effects",
305
+ };
306
+ }
@@ -19,14 +19,26 @@ export {
19
19
  type CassetteSink,
20
20
  type CassetteSpawn,
21
21
  } from "./cassette.ts";
22
- export { assertReplayable, interruptedResumeWarning, loadCassette } from "./cassette-loader.ts";
22
+ export { assertReplayable, loadCassette } from "./cassette-loader.ts";
23
23
  export { publishCassette } from "./cassette-publish.ts";
24
+ export {
25
+ type CassetteReadable,
26
+ type CassetteReadMode,
27
+ type Checkpoint,
28
+ type CheckpointOptions,
29
+ createCheckpoint,
30
+ type RunEnding,
31
+ type RunWakePayload,
32
+ readableCassette,
33
+ type SettledOutcome,
34
+ } from "./checkpoint.ts";
24
35
  export {
25
36
  checkpointFileName,
26
37
  cleanStaleCheckpointTemp,
27
38
  resolveCheckpointDirectory,
28
39
  } from "./checkpoint-dir.ts";
29
- export { createCheckpointFlusher, flushingSink } from "./checkpoint-flush.ts";
40
+ export { type ParkedAsk, parkedAsks } from "./parked-asks.ts";
41
+ export { sha256Hex } from "./program-hash.ts";
30
42
  export { recordingTransport } from "./recording-transport.ts";
31
43
  export { replayMismatch } from "./replay-divergence.ts";
32
44
  export { replayTransport } from "./replay-transport.ts";
@@ -37,16 +49,13 @@ export {
37
49
  } from "./resume-identity.ts";
38
50
  export { type AskUserRestoration, resumeTransport } from "./resume-transport.ts";
39
51
  export {
40
- keepsCheckpoint,
41
52
  type ProgramIdentity,
42
53
  prepareRecordDestination,
43
- publishRunCheckpoint,
44
- type RunCheckpointResult,
54
+ type RunIdentity,
45
55
  type RunIdentityRequest,
46
- type RunWakePayload,
47
56
  resolveRunIdentity,
48
57
  writeRecordingDiagnostic,
49
- } from "./run-checkpoint.ts";
58
+ } from "./run-identity.ts";
50
59
  export {
51
60
  appendSessionAnswer,
52
61
  restoreSessionAnswers,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The parked Asks a Cassette records (ADR-0023).
3
+ *
4
+ * One concept: the way back from an incomplete-Ask marker to its Question. The
5
+ * marker walk lives here once, so the resume side reads the record and does not
6
+ * parse the frames again.
7
+ */
8
+ import type { Cassette } from "./cassette.ts";
9
+
10
+ /** One parked Ask of a resume source: the way back to its Question (ADR-0023). */
11
+ export interface ParkedAsk {
12
+ /** The Agent name, as `agent.spawn.name` records it. */
13
+ readonly agent: string;
14
+ /** The tool call id of the parked `request_user_input` call. */
15
+ readonly toolCallId: string;
16
+ /** The Question this Ask waits for. */
17
+ readonly questionId: string;
18
+ /** The pi session file of the Agent, when the Cassette holds one. */
19
+ readonly sessionFile?: string;
20
+ }
21
+
22
+ /** Every incomplete-Ask marker of a Cassette, in Agent then Ask order. */
23
+ export function parkedAsks(cassette: Cassette): readonly ParkedAsk[] {
24
+ const marks: ParkedAsk[] = [];
25
+ for (const agent of cassette.agents) {
26
+ for (const ask of agent.asks) {
27
+ const incomplete = ask.incomplete;
28
+ if (incomplete === undefined) continue;
29
+ marks.push({
30
+ agent: agent.spawn.name,
31
+ toolCallId: incomplete.toolCallId,
32
+ questionId: incomplete.questionId,
33
+ ...(agent.sessionFile === undefined ? {} : { sessionFile: agent.sessionFile }),
34
+ });
35
+ }
36
+ }
37
+ return marks;
38
+ }
@@ -6,7 +6,8 @@ import type {
6
6
  OpenOptions,
7
7
  RecordedSpawnSelection,
8
8
  } from "../transport/index.ts";
9
- import type { CassetteAgent, CassetteAsk, CassetteSpawn } from "./cassette.ts";
9
+ import type { CassetteAgent, CassetteAsk } from "./cassette.ts";
10
+ import * as spawnIdentity from "./spawn-identity.ts";
10
11
 
11
12
  /** A pure description of the first strict replay identity mismatch. */
12
13
  export interface ReplayMismatch {
@@ -33,11 +34,11 @@ export const replayMismatch = {
33
34
  kind: "unexpected-spawn",
34
35
  agent: actual.name,
35
36
  expectedHash: "<none>",
36
- actualHash: spawnHash(actual),
37
+ actualHash: spawnIdentity.hash(actual),
37
38
  };
38
39
  }
39
- const expectedHash = spawnHash(expected.spawn);
40
- const actualHash = spawnHash(actual);
40
+ const expectedHash = spawnIdentity.hash(expected.spawn);
41
+ const actualHash = spawnIdentity.hash(actual);
41
42
  return expectedHash === actualHash
42
43
  ? null
43
44
  : {
@@ -45,7 +46,7 @@ export const replayMismatch = {
45
46
  agent: actual.name,
46
47
  expectedHash,
47
48
  actualHash,
48
- changedFields: spawnChangedFields(expected.spawn, actual),
49
+ changedFields: spawnIdentity.changedFields(expected.spawn, actual),
49
50
  };
50
51
  },
51
52
 
@@ -141,23 +142,6 @@ function compactionAt(mismatch: ReplayMismatch): string | undefined {
141
142
  return `compaction #${mismatch.index}`;
142
143
  }
143
144
 
144
- /** The identity fields a changed spawn altered, for the Divergence report (ADR-0039). */
145
- function spawnChangedFields(expected: CassetteSpawn, actual: OpenOptions): readonly string[] {
146
- return changedAmong(SPAWN_OPEN_FIELDS, expected, actual);
147
- }
148
-
149
- /**
150
- * True when a live spawn matches the recorded one on every identity field
151
- * except the resolved model and thinking, so a resume may adopt the recorded
152
- * selection instead of re-running Model Resolution (ADR-0039).
153
- */
154
- export function spawnMatchesExceptModel(expected: CassetteSpawn, actual: OpenOptions): boolean {
155
- return (
156
- spawnHash({ ...expected, model: undefined, thinking: undefined }) ===
157
- spawnHash({ ...actual, model: undefined, thinking: undefined })
158
- );
159
- }
160
-
161
145
  /** The recorded resolved selection of one Agent, or `undefined` when none is recorded. */
162
146
  export function recordedSpawnSelection(
163
147
  agent: CassetteAgent | null,
@@ -169,47 +153,6 @@ export function recordedSpawnSelection(
169
153
  };
170
154
  }
171
155
 
172
- /**
173
- * The spawn fields both Divergence reports compare, so the two cannot drift
174
- * apart. Extensions are the deliberate exception: they identify the process
175
- * start, not an Ask, so they join only the open-request list below.
176
- */
177
- const SPAWN_IDENTITY_FIELDS = [
178
- "cwd",
179
- "model",
180
- "systemPrompt",
181
- "thinking",
182
- "appendSystemPrompt",
183
- "tools",
184
- "disallowedTools",
185
- "skills",
186
- "disallowedSkills",
187
- "worktree",
188
- ] as const;
189
-
190
- /** The spawn identity fields plus the Agent name, which only an open request carries. */
191
- const SPAWN_OPEN_FIELDS = [
192
- "name",
193
- ...SPAWN_IDENTITY_FIELDS,
194
- "declaredExtensions",
195
- "canAskUser",
196
- "parent",
197
- "origin",
198
- "forkOf",
199
- "forkAsks",
200
- ] as const;
201
-
202
- /** The listed fields whose canonical JSON differs between two identity records. */
203
- function changedAmong<Key extends string>(
204
- fields: readonly Key[],
205
- expected: { readonly [Field in Key]?: unknown },
206
- actual: { readonly [Field in Key]?: unknown },
207
- ): readonly Key[] {
208
- return fields.filter(
209
- (field) => JSON.stringify(expected[field]) !== JSON.stringify(actual[field]),
210
- );
211
- }
212
-
213
156
  function askMatches(expected: CassetteAsk, actual: AskMarker): boolean {
214
157
  return (
215
158
  expected.index === actual.index &&
@@ -223,7 +166,7 @@ function askMatches(expected: CassetteAsk, actual: AskMarker): boolean {
223
166
  function changedFields(expected: AskMarkerContext, actual: AskMarkerContext): readonly string[] {
224
167
  const fields: string[] = [];
225
168
  if (expected.prompt !== actual.prompt) fields.push("prompt");
226
- fields.push(...changedAmong(SPAWN_IDENTITY_FIELDS, expected.spawn, actual.spawn));
169
+ fields.push(...spawnIdentity.askContextChangedFields(expected.spawn, actual.spawn));
227
170
  for (const field of [
228
171
  "maxTurns",
229
172
  "maxToolCalls",
@@ -243,41 +186,3 @@ function changedFields(expected: AskMarkerContext, actual: AskMarkerContext): re
243
186
  }
244
187
  return fields;
245
188
  }
246
-
247
- function spawnHash(options: CassetteSpawn | OpenOptions): string {
248
- const hasher = new Bun.CryptoHasher("sha256");
249
- hasher.update(
250
- JSON.stringify({
251
- name: options.name,
252
- cwd: options.cwd,
253
- model: options.model ?? null,
254
- systemPrompt: options.systemPrompt ?? null,
255
- ...(options.tools === undefined ? {} : { tools: options.tools }),
256
- ...(options.disallowedTools === undefined
257
- ? {}
258
- : { disallowedTools: options.disallowedTools }),
259
- ...(options.skills === undefined ? {} : { skills: options.skills }),
260
- ...(options.disallowedSkills === undefined
261
- ? {}
262
- : { disallowedSkills: options.disallowedSkills }),
263
- ...(options.worktree === true ? { worktree: true } : {}),
264
- ...(options.thinking === undefined ? {} : { thinking: options.thinking }),
265
- ...(options.appendSystemPrompt === undefined
266
- ? {}
267
- : { appendSystemPrompt: options.appendSystemPrompt }),
268
- ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
269
- ? {}
270
- : { declaredExtensions: options.declaredExtensions }),
271
- // Conditional, so a Cassette recorded before ADR-0023 keeps its hash.
272
- // `askUserProtocol` is deliberately absent: a bumped protocol must refuse
273
- // the reactivation, and a hash mismatch would start a fresh Agent instead.
274
- ...(options.canAskUser === undefined ? {} : { canAskUser: options.canAskUser }),
275
- ...(options.parent === undefined ? {} : { parent: options.parent }),
276
- // Conditional, so a Cassette recorded before forking keeps its hash.
277
- ...(options.origin === undefined ? {} : { origin: options.origin }),
278
- ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
279
- ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
280
- }),
281
- );
282
- return hasher.digest("hex");
283
- }
@@ -6,12 +6,16 @@
6
6
  * resume: both warn once and let the Run continue. The Profile comparison of a
7
7
  * strict replay is not: it refuses the Run with `REPLAY_DIVERGED`, because a
8
8
  * strict replay re-executes one recorded invocation.
9
+ *
10
+ * The run-level Host Source is deliberately no third comparison here: a changed
11
+ * Host Session is spawn identity, and it is compared at the spawn seam as
12
+ * `hostHash` (ADR-0068). Do not add an advisory rule for it.
9
13
  */
10
14
  import { YaagError } from "../errors.ts";
11
15
  import type { Cassette } from "./cassette.ts";
12
16
  import { sha256Hex } from "./program-hash.ts";
13
17
  import { REPLAY_DOCS_POINTER } from "./replay-divergence.ts";
14
- import type { ProgramIdentity } from "./run-checkpoint.ts";
18
+ import type { ProgramIdentity } from "./run-identity.ts";
15
19
 
16
20
  /**
17
21
  * Warns when a resumed Cassette recorded another Profile than the one this Run
@@ -31,6 +31,20 @@ export async function checkResumePreconditions(agent: CassetteAgent): Promise<vo
31
31
  }
32
32
  if (!agent.sessionFile)
33
33
  refuse(name, "has no recorded session file; re-record this Run before resuming");
34
+ // Only a Host Fork: a resume re-opens it from this file and never re-forks it,
35
+ // and the Run holds no copy to fall back on (ADR-0068). A universal existence
36
+ // check would be a behaviour change outside this rule, so it is not made here.
37
+ if (agent.spawn.origin === "host-fork") {
38
+ const sessionFile = agent.sessionFile;
39
+ try {
40
+ await stat(sessionFile);
41
+ } catch {
42
+ refuse(
43
+ name,
44
+ `recorded host fork session "${sessionFile}" no longer exists; a Host Fork is never re-forked`,
45
+ );
46
+ }
47
+ }
34
48
  // A reactivated Agent restores a dangling `request_user_input` call, so the
35
49
  // two sides must speak one protocol (ADR-0023).
36
50
  const recorded = agent.spawn.askUserProtocol;