@yaag/runtime 0.26.0 → 0.28.1

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 (66) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-name.ts +22 -0
  3. package/src/agent/agent-names.ts +5 -1
  4. package/src/agent/agent.ts +34 -17
  5. package/src/agent/define-agent.ts +4 -0
  6. package/src/agent/fork.ts +50 -12
  7. package/src/agent/host-fork.ts +85 -0
  8. package/src/agent/index.ts +1 -0
  9. package/src/agent/spawn-definition-request.ts +41 -6
  10. package/src/agent/spawn-open.ts +54 -107
  11. package/src/agent/spawn-parent.ts +64 -0
  12. package/src/agent/spawn-plan.ts +120 -0
  13. package/src/agent/spawn-request.ts +26 -6
  14. package/src/agent/spawn.ts +47 -6
  15. package/src/ask/ask-exchange-options.ts +3 -6
  16. package/src/ask/ask-exchange.ts +48 -108
  17. package/src/ask/ask-guard.ts +207 -0
  18. package/src/ask/ask-timing.ts +12 -0
  19. package/src/ask/index.ts +1 -0
  20. package/src/cassette/cassette-loader.ts +9 -20
  21. package/src/cassette/cassette-schema.ts +11 -1
  22. package/src/cassette/cassette.ts +16 -34
  23. package/src/cassette/checkpoint.ts +306 -0
  24. package/src/cassette/index.ts +16 -7
  25. package/src/cassette/parked-asks.ts +38 -0
  26. package/src/cassette/replay-divergence.ts +7 -102
  27. package/src/cassette/resume-identity.ts +5 -1
  28. package/src/cassette/resume-preconditions.ts +14 -0
  29. package/src/cassette/resume-transport.ts +26 -32
  30. package/src/cassette/run-identity.ts +109 -0
  31. package/src/cassette/session-answer.ts +51 -114
  32. package/src/cassette/spawn-identity.ts +328 -0
  33. package/src/contract/error-codes.ts +4 -0
  34. package/src/contract/group.ts +38 -0
  35. package/src/contract/index.ts +2 -0
  36. package/src/contract/spawn-options.ts +48 -7
  37. package/src/error-factories.ts +8 -0
  38. package/src/events.ts +22 -2
  39. package/src/index.ts +7 -0
  40. package/src/pi-session/append-tool-result.ts +165 -0
  41. package/src/pi-session/index.ts +30 -0
  42. package/src/pi-session/pi-session-error.ts +34 -0
  43. package/src/pi-session/session-copy.ts +113 -0
  44. package/src/pi-session/session-entries.ts +130 -0
  45. package/src/public-api.ts +2 -0
  46. package/src/question-summary/index.ts +4 -8
  47. package/src/question-summary/summarize-question.ts +1 -1
  48. package/src/question-summary/summary-policy.ts +5 -2
  49. package/src/run/agent-questions.ts +82 -0
  50. package/src/run/answers.ts +22 -1
  51. package/src/run/groups.ts +111 -0
  52. package/src/run/host-session.ts +233 -0
  53. package/src/run/index.ts +8 -0
  54. package/src/run/run-context.ts +15 -0
  55. package/src/run/run.ts +208 -182
  56. package/src/summary/index.ts +1 -0
  57. package/src/summary/summary-agent.ts +6 -0
  58. package/src/summary/summary-group.ts +31 -0
  59. package/src/summary/summary.ts +12 -0
  60. package/src/transport/live-transport.ts +19 -0
  61. package/src/transport/pi-state.ts +10 -1
  62. package/src/transport/transport.ts +20 -9
  63. package/src/types.ts +3 -0
  64. package/src/cassette/checkpoint-flush.ts +0 -101
  65. package/src/cassette/run-checkpoint.ts +0 -272
  66. package/src/question-summary/session-copy.ts +0 -169
package/src/run/run.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import type { TSchema } from "typebox";
3
3
  import type { Agent } from "../agent/index.ts";
4
- import { makeSpawn } from "../agent/index.ts";
4
+ import { makeSpawn, resolveParent } from "../agent/index.ts";
5
5
  import {
6
6
  assertReplayable,
7
7
  assertReplayProfile,
@@ -10,17 +10,14 @@ import {
10
10
  type CassetteSink,
11
11
  checkpointFileName,
12
12
  cleanStaleCheckpointTemp,
13
- createCheckpointFlusher,
14
- flushingSink,
15
- interruptedResumeWarning,
16
- keepsCheckpoint,
13
+ createCheckpoint,
17
14
  loadCassette,
18
15
  type ProgramIdentity,
16
+ parkedAsks,
19
17
  prepareRecordDestination,
20
18
  profileIdentityWarning,
21
19
  programIdentityWarning,
22
- publishRunCheckpoint,
23
- type RunCheckpointResult,
20
+ readableCassette,
24
21
  recordingTransport,
25
22
  replayTransport,
26
23
  resolveCheckpointDirectory,
@@ -48,10 +45,13 @@ import {
48
45
  skillRestrictionTransport,
49
46
  worktreeTransport,
50
47
  } from "../transport/index.ts";
51
- import { createAgentQuestions } from "./agent-questions.ts";
48
+ import type { Group } from "../types.ts";
49
+ import { createAgentQuestions, seedFromResume } from "./agent-questions.ts";
52
50
  import { type AnswerLedger, createAnswerLedger, emptyAnswerLedger } from "./answers.ts";
53
51
  import { validateArgs } from "./args-validation.ts";
54
52
  import { type OrchestrationProgram, programDefinition } from "./define-run.ts";
53
+ import { createGroups } from "./groups.ts";
54
+ import { adoptedHostSource, type HostSessionOptions, prepareHostSource } from "./host-session.ts";
55
55
  import { createPauseRequests } from "./pause-questions.ts";
56
56
  import type { RunContext } from "./run-context.ts";
57
57
  import type { RunResult } from "./run-result.ts";
@@ -99,6 +99,14 @@ export interface RunOptions {
99
99
  readonly control?: RunController;
100
100
  /** Overrides the default checkpoint directory a stopped Run publishes into (ADR-0021). */
101
101
  readonly checkpointDir?: string;
102
+ /**
103
+ * The Host Session this Run was started from (ADR-0068). The runtime hashes
104
+ * the file, copies it once, and offers the copy as `ctx.host`.
105
+ *
106
+ * `toolCallId` is optional: a live Run requires it, because it must close
107
+ * that call in the copy; a --replay or --resume only hashes and compares.
108
+ */
109
+ readonly host?: HostSessionOptions;
102
110
  /**
103
111
  * Effective Config for this Run, read once by the launcher (ADR-0040). The
104
112
  * Run never loads it itself: omission runs config-free, so no Run picks up a
@@ -185,162 +193,216 @@ export async function executeRun<Args, Result>(
185
193
  args,
186
194
  ...(profile === undefined ? {} : { profile: profile.id }),
187
195
  });
188
- const checkpoint = { collector, record: options.record, destination, identity };
196
+ // The Checkpoint owns the whole publish policy: when the artifact flushes,
197
+ // what each outcome keeps, and what run_end may name (ADR-0021/0031/0054).
198
+ // Building it does no I/O, so the ARGS_INVALID "no events before rejection"
199
+ // rule still holds.
200
+ const checkpoint = createCheckpoint({
201
+ collector,
202
+ record: options.record,
203
+ destination,
204
+ identity,
205
+ });
189
206
  try {
190
207
  assertArgs<Args>(definition.args, args);
191
208
  } catch (error) {
192
209
  // The result is discarded on purpose: this rejection precedes run_start, and
193
210
  // no event may precede an ARGS_INVALID rejection, so a lost Checkpoint here
194
211
  // stays a stderr diagnostic (ticket 04).
195
- await publishRunCheckpoint({ outcome: "failed", ...checkpoint });
212
+ await checkpoint.settle("failed");
196
213
  throw error;
197
214
  }
198
215
  // The directory of the --record path is made before any Agent starts, so a Run
199
216
  // whose Cassette can never land does not do its work first and fail last.
200
217
  if (options.record !== undefined) await prepareRecordDestination(options.record);
218
+ // Before the first emit, so a HOST_SESSION_UNUSABLE refusal precedes every
219
+ // Lifecycle Event, exactly like RECORD_PATH_UNUSABLE. A strict replay makes no
220
+ // copy — no live child can consume it — and it needs no tool call id, while a
221
+ // live Run does (ADR-0068).
222
+ const recordedHost = replay?.run.host ?? resume?.run.host;
223
+ const host =
224
+ options.host !== undefined
225
+ ? await prepareHostSource({
226
+ host: options.host,
227
+ live: options.replay === undefined && options.resume === undefined,
228
+ copies: options.replay === undefined,
229
+ })
230
+ : recordedHost === undefined
231
+ ? undefined
232
+ : // A replay never spawns pi and a resume re-opens each Host Fork from
233
+ // its recorded session file, so the adopted source needs no copy path.
234
+ {
235
+ source: adoptedHostSource(recordedHost.hostHash),
236
+ remove: async (): Promise<void> => {},
237
+ };
238
+ if (host !== undefined) checkpoint.identifyHost({ hostHash: host.source.hostHash });
201
239
 
202
- let summary: RunSummary = initialSummary();
203
- const sink: StampedEventSink = options.events ?? (() => {});
204
- // Every event the Run emits also feeds the fold, so its own final accounting
205
- // is derived exactly the way an outside observer would derive it. `at` is
206
- // stamped here, once, so no individual emitter touches the wall clock.
207
- const emit: EventSink = (body) => {
208
- const event: LifecycleEvent = { ...body, at: Date.now() };
209
- summary = applyEvent(summary, event);
210
- sink(event);
211
- };
212
- const flusher = createCheckpointFlusher(checkpoint);
213
- // Built before the first Agent starts, so every refusal of the answer
214
- // contract precedes the Run's work (ADR-0022).
215
- const answers: AnswerLedger =
216
- resume === null
217
- ? emptyAnswerLedger()
218
- : createAnswerLedger({
219
- supplied: options.answers ?? {},
220
- questions: resume.run.questions ?? [],
221
- inherited: resume.run.answers ?? [],
222
- });
223
- // Every answered park is restored into its session before the first Agent
224
- // starts, so a conflicting answer refuses the resume before any work (ADR-0023).
225
- if (resume !== null) await restoreSessionAnswers(resume, (id) => answers.take(id));
226
- const factory = selectFactory({
227
- options,
228
- collector: flushingSink(collector, flusher),
229
- replay,
230
- resume,
231
- answers,
232
- });
233
- const agents: Agent[] = [];
234
- const startedAt = Date.now();
235
- const askAdmission = createAskAdmission();
236
- const agentQuestions = createAgentQuestions();
237
- const spawnGate = makeSpawn({
238
- factory,
239
- agents,
240
- emit,
241
- askAdmission,
242
- questions: agentQuestions,
243
- sessionDir: options.sessionDir,
244
- programFile: options.programFile,
245
- // The same value `run_start.program` carries, so an Agent's prompt names
246
- // the Run the reader sees in the Run record.
247
- runName: definition.name ?? "program",
248
- configExtensions: options.config?.extensions ?? EMPTY_EFFECTIVE_CONFIG.extensions,
249
- ...(profile === undefined ? {} : { profile }),
250
- });
240
+ // Everything below can throw with the copy already on disk — a refused
241
+ // resume, a failed session restore, a failed spawn gate — so the removal
242
+ // guards from here. Every exit path removes it; a killed process leaks it,
243
+ // and that is a stated limit (ADR-0068).
244
+ try {
245
+ let summary: RunSummary = initialSummary();
246
+ const sink: StampedEventSink = options.events ?? (() => {});
247
+ // Every event the Run emits also feeds the fold, so its own final accounting
248
+ // is derived exactly the way an outside observer would derive it. `at` is
249
+ // stamped here, once, so no individual emitter touches the wall clock.
250
+ const emit: EventSink = (body) => {
251
+ const event: LifecycleEvent = { ...body, at: Date.now() };
252
+ summary = applyEvent(summary, event);
253
+ sink(event);
254
+ };
255
+ // Built before the first Agent starts, so every refusal of the answer
256
+ // contract precedes the Run's work (ADR-0022).
257
+ const parked = resume === null ? [] : parkedAsks(resume);
258
+ const answers: AnswerLedger =
259
+ resume === null
260
+ ? emptyAnswerLedger()
261
+ : createAnswerLedger({
262
+ supplied: options.answers ?? {},
263
+ questions: resume.run.questions ?? [],
264
+ inherited: resume.run.answers ?? [],
265
+ parked,
266
+ });
267
+ // Every answered park is restored into its session before the first Agent
268
+ // starts, so a conflicting answer refuses the resume before any work (ADR-0023).
269
+ if (resume !== null) await restoreSessionAnswers(resume, (id) => answers.take(id));
270
+ const factory = selectFactory({
271
+ options,
272
+ collector: checkpoint.sink,
273
+ replay,
274
+ resume,
275
+ answers,
276
+ });
277
+ const agents: Agent[] = [];
278
+ const startedAt = Date.now();
279
+ const askAdmission = createAskAdmission();
280
+ const agentQuestions = createAgentQuestions();
281
+ // The open Questions of the Checkpoint are the Questions of this resume: a
282
+ // re-opened Question keeps its id, text, context and summary (ADR-0022/0023).
283
+ if (resume !== null) {
284
+ seedFromResume({ questions: agentQuestions, open: answers.open(), parked });
285
+ }
286
+ const spawnGate = makeSpawn({
287
+ factory,
288
+ agents,
289
+ emit,
290
+ askAdmission,
291
+ questions: agentQuestions,
292
+ sessionDir: options.sessionDir,
293
+ programFile: options.programFile,
294
+ // The same value `run_start.program` carries, so an Agent's prompt names
295
+ // the Run the reader sees in the Run record.
296
+ runName: definition.name ?? "program",
297
+ configExtensions: options.config?.extensions ?? EMPTY_EFFECTIVE_CONFIG.extensions,
298
+ // Late-bound on purpose, like `agents` below: the registry is built under
299
+ // this call, and no spawn can run before the program starts.
300
+ isGroup: (value): value is Group => groups.holds(value),
301
+ ...(profile === undefined ? {} : { profile }),
302
+ });
251
303
 
252
- const pauseRequests = createPauseRequests(answers);
253
- const ctx: RunContext<Args> = {
254
- args,
255
- spawn: spawnGate.spawn,
256
- askUser: pauseRequests.askUser,
257
- pause: pauseRequests.pause,
258
- ...(profile === undefined ? {} : { profile: { id: profile.id } }),
259
- };
260
- emit({
261
- type: "run_start",
262
- program: definition.name ?? "program",
263
- artifact: destination,
264
- ...(profile === undefined ? {} : { profile: profile.id }),
265
- });
304
+ // `agents` is the live array the spawn gate mutates, so a Handle spawned
305
+ // later is a valid Group parent.
306
+ const groups = createGroups({
307
+ emit,
308
+ assertOpen: spawnGate.assertOpen,
309
+ resolveAgentParent: (parent) => resolveParent(parent, agents),
310
+ hasName: spawnGate.hasName,
311
+ reserveName: spawnGate.reserveName,
312
+ });
266
313
 
267
- // The program's settlement is held rather than rethrown from a `finally`, so
268
- // publication can displace it when the checkpoint fails (ADR-0021).
269
- const settlement = await settleRun({
270
- program: () => definition.run(ctx),
271
- requests: controlRequests(options.control, options.signal),
272
- agents,
273
- closeAdmission: () => {
274
- askAdmission.close();
275
- spawnGate.close();
276
- },
277
- questionRaised: agentQuestions.raised,
278
- });
279
- const outcome: RunOutcome = settlement.outcome;
280
- const settled = heldSettlement(settlement);
281
- // Idempotent: a settlement that never drained has not closed admission yet.
282
- askAdmission.close();
283
- spawnGate.close();
284
- await reapAll({ agents, emit });
285
- // No flush may land after the settled artifact, or an acknowledged Run would
286
- // be overwritten by an `interrupted` one.
287
- await flusher.quiesce();
288
- // The summarizer runs here and nowhere else: after quiescence and after every
289
- // Agent is reaped, so it reads a session file pi has finished writing, and
290
- // before publication, so each summary is durable in the Cassette (ADR-0022).
291
- const summarized =
292
- outcome === "paused"
293
- ? await summarizeQuestions({
294
- questions: agentQuestions,
295
- agents,
296
- policy: questionSummaryOf(options.config),
297
- openAgent: spawnGate.openInternal,
298
- ...(options.replay === undefined ? {} : { replaying: true }),
299
- })
300
- : { warnings: [] };
301
- // Built once, after the summaries landed, so the wake payload and the returned
302
- // result carry the same questions. The program's own questions come first;
303
- // both registries are Run-scoped and neither can key a question of the other.
304
- const openQuestions = [...pauseRequests.questions, ...agentQuestions.questions];
305
- const pausedWarnings = [
306
- ...(settled.ok === "paused" ? settled.warnings : []),
307
- ...summarized.warnings,
308
- ];
309
- // run_end is the acknowledgement: nothing may report an outcome before the
310
- // checkpoint's destination-directory fsync has landed (ADR-0021).
311
- const publication = await publishRunCheckpoint({
312
- outcome,
313
- ...checkpoint,
314
- wake: {
314
+ const pauseRequests = createPauseRequests(answers);
315
+ const ctx: RunContext<Args> = {
316
+ args,
317
+ spawn: spawnGate.spawn,
318
+ group: groups.group,
319
+ askUser: pauseRequests.askUser,
320
+ pause: pauseRequests.pause,
321
+ ...(profile === undefined ? {} : { profile: { id: profile.id } }),
322
+ ...(host === undefined ? {} : { host: host.source }),
323
+ };
324
+ emit({
325
+ type: "run_start",
326
+ program: definition.name ?? "program",
327
+ artifact: destination,
328
+ ...(profile === undefined ? {} : { profile: profile.id }),
329
+ });
330
+
331
+ // The program's settlement is held rather than rethrown from a `finally`, so
332
+ // publication can displace it when the checkpoint fails (ADR-0021).
333
+ const settlement = await settleRun({
334
+ program: () => definition.run(ctx),
335
+ requests: controlRequests(options.control, options.signal),
336
+ agents,
337
+ closeAdmission: () => {
338
+ askAdmission.close();
339
+ spawnGate.close();
340
+ },
341
+ questionRaised: agentQuestions.raised,
342
+ });
343
+ const outcome: RunOutcome = settlement.outcome;
344
+ const settled = heldSettlement(settlement);
345
+ // Idempotent: a settlement that never drained has not closed admission yet.
346
+ askAdmission.close();
347
+ spawnGate.close();
348
+ await reapAll({ agents, emit });
349
+ // The summarizer runs here and nowhere else: after every Agent is reaped, so
350
+ // it reads a session file pi has finished writing, and before settlement, so
351
+ // each summary is durable in the Cassette (ADR-0022). `settle()` quiesces the
352
+ // in-flight flushes itself, so no flush can land after the settled artifact.
353
+ // The summarizer's own Agent runs before that quiescence, so it can flush one
354
+ // more `interrupted` artifact; the settled publication supersedes it.
355
+ const summarized =
356
+ outcome === "paused"
357
+ ? await summarizeQuestions({
358
+ questions: agentQuestions,
359
+ agents,
360
+ policy: questionSummaryOf(options.config),
361
+ openAgent: spawnGate.openInternal,
362
+ ...(options.replay === undefined ? {} : { replaying: true }),
363
+ })
364
+ : { warnings: [] };
365
+ // Built once, after the summaries landed, so the wake payload and the returned
366
+ // result carry the same questions. The program's own questions come first;
367
+ // both registries are Run-scoped and neither can key a question of the other.
368
+ const openQuestions = [...pauseRequests.questions, ...agentQuestions.questions];
369
+ const pausedWarnings = [
370
+ ...(settled.ok === "paused" ? settled.warnings : []),
371
+ ...summarized.warnings,
372
+ ];
373
+ // run_end is the acknowledgement: nothing may report an outcome before the
374
+ // checkpoint's destination-directory fsync has landed (ADR-0021).
375
+ const { displacedBy, ...ending } = await checkpoint.settle(outcome, {
315
376
  // The program's own Questions first, then the Agents': the same order the
316
377
  // RunResult carries, so an artifact and a reader agree (ADR-0022).
317
378
  questions: openQuestions,
318
379
  answers: answers.resolved(),
319
380
  ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
320
- },
321
- });
322
- const ending = endingFrom({ publication, outcome, destination, record: options.record });
323
- emitRunEnd({
324
- emit,
325
- durationMs: Date.now() - startedAt,
326
- summary,
327
- ...ending,
328
- ...(settled.ok === "paused" && pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
329
- });
330
- if (publication.kind === "displaced") throw publication.error;
331
- if (settled.ok === "paused") {
332
- // Built after publication, so `checkpoint` always names a file that is on
333
- // disk and fsynced (ADR-0021).
334
- return {
335
- outcome: "paused",
336
- questions: openQuestions,
337
- ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
338
- checkpoint: destination,
339
- ...(pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
340
- };
381
+ });
382
+ emitRunEnd({
383
+ emit,
384
+ durationMs: Date.now() - startedAt,
385
+ summary,
386
+ ...ending,
387
+ ...(settled.ok === "paused" && pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
388
+ });
389
+ if (displacedBy !== undefined) throw displacedBy;
390
+ if (settled.ok === "paused") {
391
+ // Built after publication, so `checkpoint` always names a file that is on
392
+ // disk and fsynced (ADR-0021).
393
+ return {
394
+ outcome: "paused",
395
+ questions: openQuestions,
396
+ ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
397
+ checkpoint: destination,
398
+ ...(pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
399
+ };
400
+ }
401
+ if (!settled.ok) throw settled.error;
402
+ return { outcome: "completed", value: settled.value };
403
+ } finally {
404
+ await host?.remove();
341
405
  }
342
- if (!settled.ok) throw settled.error;
343
- return { outcome: "completed", value: settled.value };
344
406
  }
345
407
 
346
408
  /**
@@ -370,8 +432,8 @@ async function loadResume(
370
432
  ): Promise<Cassette | null> {
371
433
  if (path === undefined) return null;
372
434
  const cassette = await loadCassette(path);
373
- const warning = interruptedResumeWarning(cassette, path);
374
- if (warning !== null) writeRecordingDiagnostic(warning);
435
+ const readable = readableCassette(cassette, path, "resume");
436
+ if (readable.ok && readable.warning !== undefined) writeRecordingDiagnostic(readable.warning);
375
437
  warnOnIdentity(cassette, path, program);
376
438
  return cassette;
377
439
  }
@@ -512,42 +574,6 @@ interface RunEndOptions {
512
574
  readonly warnings?: readonly string[];
513
575
  }
514
576
 
515
- /**
516
- * Folds one publication result into how the Run ends. A displaced publication
517
- * takes the outcome; a lost Checkpoint keeps it and reports the loss instead.
518
- */
519
- function endingFrom(options: {
520
- readonly publication: RunCheckpointResult;
521
- readonly outcome: RunOutcome;
522
- readonly destination: string;
523
- /** The `--record` destination, or undefined; it decides what is kept. */
524
- readonly record: string | undefined;
525
- }): {
526
- readonly outcome: RunOutcome;
527
- readonly checkpointLost?: string;
528
- readonly checkpoint?: string;
529
- } {
530
- const { publication, outcome, destination, record } = options;
531
- switch (publication.kind) {
532
- case "published":
533
- // A Run names a Checkpoint only when publication kept the artifact, and
534
- // only a paused or stopped Run resumes from one (ADR-0054). `keepsCheckpoint`
535
- // is the one rule for the first half, so no Run can name a file that
536
- // publication just deleted.
537
- return {
538
- outcome,
539
- ...((outcome === "paused" || outcome === "stopped") &&
540
- keepsCheckpoint({ outcome, ...(record === undefined ? {} : { record }) })
541
- ? { checkpoint: destination }
542
- : {}),
543
- };
544
- case "lost":
545
- return { outcome, checkpointLost: publication.message };
546
- case "displaced":
547
- return { outcome: "failed" };
548
- }
549
- }
550
-
551
577
  /** Emits the Run's acknowledgement, the last Lifecycle Event of every Run. */
552
578
  function emitRunEnd({
553
579
  emit,
@@ -23,3 +23,4 @@ export type {
23
23
  NodeInfo,
24
24
  SpawnOrigin,
25
25
  } from "./summary-agent.ts";
26
+ export type { GroupInfo } from "./summary-group.ts";
@@ -35,6 +35,8 @@ interface AgentInfoBase {
35
35
  readonly sessionFile: string | null;
36
36
  /** The Agent named as this one's parent (Parent Link), or null for a root Agent. */
37
37
  readonly parent: string | null;
38
+ /** The Group this Agent sits in, or null when it sits at its parent's level. */
39
+ readonly group: string | null;
38
40
  /** How the Agent came to be; "spawn" until forking ships. */
39
41
  readonly origin: SpawnOrigin;
40
42
  /** Id of the active Profile; absent unless this Agent came from a Profiled Definition. */
@@ -129,6 +131,7 @@ export function placeholderAgent(): IdleAgentInfo {
129
131
  branch: null,
130
132
  sessionFile: null,
131
133
  parent: null,
134
+ group: null,
132
135
  origin: "spawn",
133
136
  compactions: 0,
134
137
  lastCompaction: null,
@@ -163,6 +166,7 @@ export function spawnAgent(
163
166
  readonly branch?: string;
164
167
  readonly sessionFile?: string;
165
168
  readonly parent?: string;
169
+ readonly group?: string;
166
170
  readonly origin?: SpawnOrigin;
167
171
  readonly profile?: string;
168
172
  readonly role?: readonly string[];
@@ -178,6 +182,7 @@ export function spawnAgent(
178
182
  branch: identity.branch ?? null,
179
183
  sessionFile: identity.sessionFile ?? null,
180
184
  parent: identity.parent ?? null,
185
+ group: identity.group ?? null,
181
186
  origin: identity.origin ?? "spawn",
182
187
  ...(identity.profile === undefined ? {} : { profile: identity.profile }),
183
188
  ...(identity.role === undefined ? {} : { role: identity.role }),
@@ -195,6 +200,7 @@ export function spawnAgent(
195
200
  // spawn only fills what is still missing. `origin` has no missing value —
196
201
  // it defaults to "spawn" — so the spawn event is its only authority.
197
202
  parent: current.parent ?? identity.parent ?? null,
203
+ group: current.group ?? identity.group ?? null,
198
204
  origin: identity.origin ?? current.origin,
199
205
  ...((current.profile ?? identity.profile) === undefined
200
206
  ? {}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The Group table of the Run Summary (ADR-0070).
3
+ *
4
+ * A Group owns no process and never closes, so the fold has one operation:
5
+ * insert.
6
+ */
7
+
8
+ /** What one `group_open` event tells an observer about a Group. */
9
+ export interface GroupInfo {
10
+ readonly name: string;
11
+ /** The parent Agent name when the Group sits under an Agent; null in all other cases. */
12
+ readonly parent: string | null;
13
+ readonly openedAt: number | null;
14
+ }
15
+
16
+ /**
17
+ * Inserts one Group, keyed by its path. A Group path is unique in one Run
18
+ * (ADR-0070), so a repeated path can only be a repeated event: it is a no-op
19
+ * and the same object comes back.
20
+ */
21
+ export function openGroup(
22
+ groups: Readonly<Record<string, GroupInfo>>,
23
+ event: { readonly path: string; readonly name: string; readonly parent?: string },
24
+ at: number | null,
25
+ ): Readonly<Record<string, GroupInfo>> {
26
+ if (groups[event.path] !== undefined) return groups;
27
+ return {
28
+ ...groups,
29
+ [event.path]: { name: event.name, parent: event.parent ?? null, openedAt: at },
30
+ };
31
+ }
@@ -14,6 +14,7 @@ import {
14
14
  totalsFromAgents,
15
15
  } from "./summary-agent.ts";
16
16
  import { applyModelFallback } from "./summary-fallbacks.ts";
17
+ import { type GroupInfo, openGroup } from "./summary-group.ts";
17
18
  import { applyAgentModel } from "./summary-model.ts";
18
19
  import { applyNodeUpdate } from "./summary-nodes.ts";
19
20
 
@@ -30,6 +31,7 @@ export type {
30
31
  NodeInfo,
31
32
  SpawnOrigin,
32
33
  } from "./summary-agent.ts";
34
+ export type { GroupInfo } from "./summary-group.ts";
33
35
 
34
36
  /** The observer-facing lifecycle state of a Run. */
35
37
  export type RunState = "running" | "ended";
@@ -46,6 +48,11 @@ interface RunSummaryBase {
46
48
  /** Id of the active Profile, as `run_start` named it; absent without Profiles. */
47
49
  readonly profile?: string;
48
50
  readonly agents: Readonly<Record<string, AgentInfo>>;
51
+ /**
52
+ * The Groups this Run opened, keyed by Group path (ADR-0070), so an observer
53
+ * that holds a Summary alone can rebuild the tree.
54
+ */
55
+ readonly groups: Readonly<Record<string, GroupInfo>>;
49
56
  readonly asksStarted: number;
50
57
  readonly asksSettled: number;
51
58
  readonly cost: number;
@@ -112,6 +119,7 @@ export function initialSummary(): RunningRunSummary {
112
119
  startedAt: null,
113
120
  artifact: null,
114
121
  agents: {},
122
+ groups: {},
115
123
  asksStarted: 0,
116
124
  asksSettled: 0,
117
125
  cost: 0,
@@ -152,6 +160,10 @@ export function applyEvent(
152
160
  };
153
161
  case "agent_spawn":
154
162
  return withAgent(summary, event.agent, spawnAgent(summary.agents[event.agent], event, at));
163
+ case "group_open": {
164
+ const groups = openGroup(summary.groups, event, at);
165
+ return groups === summary.groups ? summary : { ...summary, groups };
166
+ }
155
167
  case "ask_start":
156
168
  return withAgent(
157
169
  { ...summary, asksStarted: summary.asksStarted + 1 },
@@ -36,12 +36,31 @@ export const liveTransport: TransportFactory = {
36
36
  options: OpenOptions,
37
37
  observeStartup?: TransportStartupObserver,
38
38
  ): Promise<AgentTransport> {
39
+ assertHostForkSource(options);
39
40
  const transport = new LiveTransport(options);
40
41
  await transport.ready(observeStartup);
41
42
  return transport;
42
43
  },
43
44
  };
44
45
 
46
+ /**
47
+ * Refuses a Host Fork that has no path to fork from, before any process work.
48
+ *
49
+ * The guard sits here and not at the spawn gate, because a replay legitimately
50
+ * holds no copy: it never spawns pi at all. Only a live open is a real `pi`
51
+ * process. A recorded `sessionFile` exempts the open: a resume continues a
52
+ * recorded Host Fork with `--session`, which is not a fork (ADR-0068).
53
+ */
54
+ function assertHostForkSource(options: OpenOptions): void {
55
+ if (options.origin !== "host-fork") return;
56
+ if (options.forkSession !== undefined || options.sessionFile !== undefined) return;
57
+ throw new YaagError(
58
+ "FORK_REFUSED",
59
+ `agent "${options.name}": this Run holds no host session copy to fork from`,
60
+ options.name,
61
+ );
62
+ }
63
+
45
64
  class LiveTransport implements AgentTransport {
46
65
  model = "";
47
66
 
@@ -23,7 +23,16 @@ import type {
23
23
 
24
24
  export type { AgentProgress } from "../contract/index.ts";
25
25
 
26
- /** The command line for one Agent. */
26
+ /**
27
+ * The command line for one Agent.
28
+ *
29
+ * Which fields may appear here is not decided in this file: the spawn field
30
+ * table (`cassette/spawn-identity.ts`) marks each row `argv: "flag"` or
31
+ * `argv: "never"`, and `open-options-classification.test.ts` fails when a row
32
+ * marked `never` reaches this command line. The direction of the dependency is
33
+ * deliberate: `transport/` must not import `cassette/` at runtime, so the test
34
+ * is the reader of the table, not this function.
35
+ */
27
36
  export function piCommand(options: OpenOptions, toolProbeExtensionPath?: string): string[] {
28
37
  const cmd = ["pi", "--mode", "rpc"];
29
38
  if (options.model) cmd.push("--model", options.model);