@maheidem/pi-delegate 0.1.4 → 0.2.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.
package/README.md CHANGED
@@ -32,9 +32,12 @@ is performed by this package.
32
32
  tree-stable; active tool set becomes
33
33
  ['delegate'])
34
34
  /delegate off disable strict coordinator mode
35
- /delegate status mode, active/last run, tool registration
35
+ /delegate status mode, active/last run, tool registration,
36
+ executing version (R7)
36
37
  /delegate inspect [runId] metadata + bounded transcript/stderr
37
38
  /delegate cancel [runId] cancel the active (or named) run
39
+ /delegate resume <runId> <task> continue a prior run's child session in the
40
+ SAME context (R3) — no cold re-explanation
38
41
  /delegate paths config/run-store locations
39
42
  /delegate doctor honest environment checks
40
43
  /delegate help syntax + examples
@@ -70,6 +73,88 @@ the same base-timeout line.
70
73
  Tool (`delegate`) is available to models: same semantics, JSON result with
71
74
  `ok`/`handoff`/`details` (usage, paths, state) or structured `error`.
72
75
 
76
+ ### Timeout semantics (read this before long validation/benchmark runs)
77
+
78
+ Effective budgets per run, resolved as `per-invocation > project > user`:
79
+
80
+ - **Hard** — wall-clock cap for the whole run (`hardTimeoutMs`, default 30 m).
81
+ - **Idle** — no child output at all, with **no tool call in flight**
82
+ (`inactivityTimeoutMs`, default 5 m), **capped at hard/2** for any source.
83
+ - **Stuck-tool** — no child output **while a tool call is in flight**
84
+ (`stuckToolTimeoutMs`, default = the hard timeout). A silent 40-minute test
85
+ matrix inside one `bash` call is *activity*, not a stall: the watchdog
86
+ leaves it alone until the stuck-tool budget (or the hard cap) is reached.
87
+
88
+ Consequences worth internalizing:
89
+
90
+ - A single tool call longer than **min(idle, hard/2)** used to be
91
+ *guaranteed killed* — that was the single largest failure class in the
92
+ 2026-09-03 investigation (5 of 11 failures, 0 true positives). In-flight
93
+ tools now sit under the stuck-tool budget instead.
94
+ - Per-run `--timeout` / the `timeout` parameter raises the hard cap **and**
95
+ (through the hard/2 cap) the idle cap. For long validation or benchmark
96
+ work, set `timeout` ≥ 2× the longest expected single tool call.
97
+ - A genuinely silent child with no open tool still trips the idle watchdog
98
+ exactly as before.
99
+
100
+ ### Graceful timeout handoff (R2), durable sessions (R3), provider errors (R4)
101
+
102
+ - On a **timeout kill**, the runner no longer goes straight to SIGTERM: it
103
+ aborts the in-flight turn, sends a bounded termination-notice prompt
104
+ ("files changed / work remaining / last verification state — answer from
105
+ context, no tools"), waits `handoffGraceMs` (default 90 s), and captures
106
+ the answer as **`partialHandoff`** on the receipt and in the tool result.
107
+ Post-mortem inspection becomes "read the handoff", not "re-read the tree".
108
+ - Child sessions are **durable**: each run persists the child's pi session
109
+ under `<runsDir>/sessions/` and records `sessionPath` on the receipt.
110
+ `delegate({ resumeFrom: runId })` or `/delegate resume <runId> <task>`
111
+ re-enters that exact session — the new child sees all earlier turns, so a
112
+ killed run continues with **one prompt** instead of a cold re-explained
113
+ task. (Pre-0.2.0 runs have no session file and are not resumable.)
114
+ - Provider failures are diagnosed from the provider's own
115
+ `errorMessage` on the final message (`E_PROVIDER_ERROR`, verbatim text —
116
+ e.g. `Codex error: The usage limit has been reached`). Abort artifacts
117
+ (`This operation was aborted`) are classified as killed-by-watchdog rather
118
+ than blamed on the provider, and the stderr tail is no longer presented as
119
+ the cause.
120
+
121
+ ### The mandatory structured handoff (protocol, not prompt)
122
+
123
+ Anything the harness NEEDS from the child is a validated protocol step —
124
+ never free text we hope has the right shape:
125
+
126
+ - The delegate extension loads in child mode too and registers exactly one
127
+ tool: **`handoff`** (always in the child's tool ceiling). The child's run
128
+ does not complete until it submits a structured report:
129
+ `outcome` (`done|partial|blocked`), `summary`, `changes[]`
130
+ (`path`/`action`/`note`), `verification[]` (`command`/`result`/`note`),
131
+ `remaining[]` (required unless `done`), `risks[]`.
132
+ - **Malformed submissions fail as tool errors** listing every invalid field,
133
+ so the child retries with the exact problems named.
134
+ - A child that settles **without** submitting is re-prompted automatically
135
+ (bounded: 2 attempts, `handoffEnforceTimeoutMs` deadline — never the hard
136
+ cap), then its free-text ending is accepted with a diagnostic note
137
+ (older children without the tool still finish).
138
+ - The parent-facing handoff text is **rendered deterministically** from the
139
+ validated fields; the receipt stores the raw structured payload as
140
+ `handoffData`. The kill-time partial handoff (R2) uses the same tool, so a
141
+ timed-out child's last act is a machine-checkable report.
142
+
143
+ ### Model pinning (R5), git checkpoints (R6), version provenance (R7)
144
+
145
+ - `delegate({ model: "provider/model-id" })` pins the child model. Without
146
+ it the child silently inherits the parent's **current** model — if the
147
+ parent falls back mid-session (e.g. a usage limit), every child follows.
148
+ The resolved child model is echoed in live updates and the result header.
149
+ - When the cwd is a git worktree, every receipt records `gitBase` (HEAD at
150
+ run start), `gitStatus` (pre-run dirty files) and `gitDelta` (post-run
151
+ `git diff --stat HEAD` + untracked files). "What did the dead child
152
+ change?" is `git diff <gitBase>`.
153
+ - Every result header and `/delegate status` prints the **executing**
154
+ extension version. Extensions load at session start: newer installs only
155
+ apply after `/reload` in that session — the version line makes a stale
156
+ copy self-evident instead of indistinguishable from a regression.
157
+
73
158
  ## Safety model (selected invariants)
74
159
 
75
160
  - The delegated task travels over child **RPC stdin**, never argv.
@@ -80,8 +165,24 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
80
165
  ignored, never dropped.
81
166
  - Cancellation is idempotent (first wins): RPC abort → SIGTERM → SIGKILL;
82
167
  every finalization reaps the child exactly once.
168
+ - Startup orphan recovery only marks a nonterminal run `crashed` /
169
+ `E_ORPHANED_RUN` when its stored pid is dead or provably not a pi process
170
+ (recycled pid). A live pi process owns its runs — a concurrent pi session
171
+ (the multi-session pattern) never clobbers a run that another live pi
172
+ process is running or finalizing; live pids with unreadable command lines
173
+ are left alone (fail-safe, never clobber on doubt). This process never kills
174
+ a pid it finds in stale metadata.
175
+ - Every terminal failure state carries a specific error payload: timeout and
176
+ cancel states reached without one (timers, user cancels) synthesize
177
+ `E_TIMEOUT_IDLE` / `E_TIMEOUT_HARD` / `E_CANCELLED` with a descriptive
178
+ message at finalization, in both the receipt and the tool text — the error
179
+ line never degrades to `unknown failure`.
83
180
  - Run-store is `0700` with `0600` receipt/transcript/stderr files; corrupt
84
- config is preserved as evidence and defaults are loaded.
181
+ config is preserved as evidence and defaults are loaded. Manual data
182
+ repairs are recorded on the receipt in a `curationNote` field (one-time
183
+ 2026-09-03 repair: receipts clobbered by pre-0.1.5 orphan recovery and
184
+ later removed by retention were reconstructed from the parent sessions'
185
+ delegate tool results — see `.planning/`, excluded from the npm tarball).
85
186
  - Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
86
187
  persisted via session custom entries; persistence failures degrade loudly
87
188
  but never silently disable the gate.
@@ -94,6 +195,7 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
94
195
  npm run typecheck # strict tsc, no emit
95
196
  npm test # unit + runner (real RPC children) + application + UI + load
96
197
  npm run test:e2e # real pi session E2E (needs a working default model)
198
+ # E2E_SCENARIOS=D,F runs a targeted subset
97
199
  ```
98
200
 
99
201
  Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
package/application.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import * as fs from "node:fs";
11
+ import * as path from "node:path";
11
12
  import type {
12
13
  CancelResult,
13
14
  DelegateApplication,
@@ -205,6 +206,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
205
206
  // Config cascade: project .pi/delegate/config.json overlays the
206
207
  // user-wide (live) config per run; missing file = live config.
207
208
  let baseCfg: DelegateConfigV1 = this.liveConfig;
209
+ let projectSetsHard = false;
208
210
  if (request.projectRoot) {
209
211
  // Strip the overlay's diagnostic keys so only real config fields
210
212
  // reach the runner (a spurious key would survive into metadata).
@@ -213,6 +215,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
213
215
  projectOverrides: string[];
214
216
  projectCorrupt?: string;
215
217
  };
218
+ projectSetsHard = projectOverrides.includes("hardTimeoutMs");
216
219
  baseCfg = { ...(rest as unknown as DelegateConfigV1) } as DelegateConfigV1;
217
220
  }
218
221
 
@@ -225,7 +228,14 @@ export class DelegateApplicationImpl implements DelegateApplication {
225
228
  ...baseCfg,
226
229
  hardTimeoutMs: timeouts.hardMs,
227
230
  inactivityTimeoutMs: timeouts.inactivityMs,
231
+ stuckToolTimeoutMs: timeouts.stuckToolMs,
228
232
  };
233
+ // R7: timeout provenance for the result header, e.g.
234
+ // "hard 45m (per-run) · idle 22m30s · stuck-tool 45m".
235
+ const timeoutInfo =
236
+ `hard ${formatDuration(timeouts.hardMs)} (${request.timeoutMs !== undefined ? "per-run" : projectSetsHard ? "project" : "user"})` +
237
+ ` · idle ${formatDuration(timeouts.inactivityMs)}` +
238
+ ` · stuck-tool ${formatDuration(timeouts.stuckToolMs)}`;
229
239
 
230
240
  // 2. Validate task (line endings, blank, byte limit).
231
241
  const taskResult = validateTask(request.task, cfg.maxTaskBytes);
@@ -245,10 +255,29 @@ export class DelegateApplicationImpl implements DelegateApplication {
245
255
  return errorResult("", role.name, "E_PROJECT_UNTRUSTED", "Project is not trusted; a write-capable child cannot run. Approve trust or use the research role.");
246
256
  }
247
257
 
248
- // 5. Model inheritance.
249
- const model = request.parentModel?.trim();
258
+ // 5. Model resolution (R5): an explicit `model` pin wins; otherwise
259
+ // the parent's current model is inherited as before.
260
+ const model = request.model?.trim() || request.parentModel?.trim();
250
261
  if (!model) {
251
- return errorResult("", role.name, "E_MODEL_UNAVAILABLE", "No parent model available to inherit. Select or configure a model.");
262
+ return errorResult("", role.name, "E_MODEL_UNAVAILABLE", "No parent model available to inherit. Select or configure a model, or pass an explicit child model.");
263
+ }
264
+ const modelNote = request.model?.trim() && request.model!.trim() !== request.parentModel?.trim()
265
+ ? `child model pinned to ${request.model!.trim()} (parent model ${request.parentModel || "none"} not inherited)`
266
+ : undefined;
267
+
268
+ // R3: resume — re-enter a prior run's durable child session.
269
+ let resumeOf: string | undefined;
270
+ let sessionPath: string | undefined;
271
+ if (request.resumeFrom) {
272
+ const prior = readRunMetadata(agentDir, request.resumeFrom);
273
+ if (!prior) {
274
+ return errorResult("", role.name, "E_STORE", `resumeFrom: no receipt for run ${request.resumeFrom}.`);
275
+ }
276
+ if (!prior.sessionPath || !fs.existsSync(prior.sessionPath)) {
277
+ return errorResult("", role.name, "E_STORE", `resumeFrom: run ${request.resumeFrom} has no durable child session on disk (pre-0.2.0 runs are not resumable).`);
278
+ }
279
+ resumeOf = prior.runId;
280
+ sessionPath = prior.sessionPath;
252
281
  }
253
282
 
254
283
  // 6. Role prompt readability.
@@ -264,6 +293,17 @@ export class DelegateApplicationImpl implements DelegateApplication {
264
293
  return errorResult("", role.name, "E_STORE", `Run store could not initialize: ${(error as Error).message}`);
265
294
  }
266
295
 
296
+ // R3: durable session storage for new runs (resumed runs re-enter
297
+ // the prior session file directly).
298
+ const sessionDir = sessionPath ? undefined : path.join(opened.paths.runsDir, "sessions");
299
+ if (sessionDir) {
300
+ try {
301
+ fs.mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
302
+ } catch {
303
+ // session capture is best-effort; the run still proceeds
304
+ }
305
+ }
306
+
267
307
  // 8. Reservation NOW covers the child lifecycle.
268
308
  const runner = new DelegateRunner(
269
309
  opened,
@@ -277,6 +317,9 @@ export class DelegateApplicationImpl implements DelegateApplication {
277
317
  cwd: request.cwd,
278
318
  projectTrusted: request.projectTrusted,
279
319
  registeredTools: this.lastRegisteredTools,
320
+ ...(resumeOf ? { resumeOf } : {}),
321
+ ...(sessionPath ? { sessionPath } : {}),
322
+ ...(sessionDir ? { sessionDir } : {}),
280
323
  },
281
324
  cfg,
282
325
  hooks,
@@ -299,7 +342,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
299
342
  } catch {
300
343
  // cleanup failure is warning-only
301
344
  }
302
- return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel);
345
+ return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
303
346
  } catch (error) {
304
347
  this.activeRun = null;
305
348
  return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
@@ -609,6 +652,7 @@ function outcomeToRunResult(
609
652
  role: RoleName,
610
653
  model: string,
611
654
  thinkingLevel?: string,
655
+ provenance?: { timeoutInfo?: string; modelNote?: string },
612
656
  ): DelegateRunResult {
613
657
  const ok = outcome.state === "succeeded";
614
658
  const details: DelegateDetails = {
@@ -626,14 +670,20 @@ function outcomeToRunResult(
626
670
  usage: outcome.usage,
627
671
  outputBytes: outcome.outputBytes,
628
672
  outputTruncated: outcome.outputTruncated,
673
+ ...(outcome.partialHandoff ? { partialHandoff: outcome.partialHandoff } : {}),
674
+ ...(provenance?.timeoutInfo ? { timeoutInfo: provenance.timeoutInfo } : {}),
629
675
  transcriptPath: outcome.transcriptPath,
630
676
  stderrPath: outcome.stderrPath,
631
677
  displayItems: outcome.displayItems,
632
678
  };
679
+ const notes: string[] = [];
680
+ if (provenance?.modelNote) notes.push(provenance.modelNote);
681
+ if (outcome.partialHandoff) notes.push(`partial handoff captured (${Buffer.byteLength(outcome.partialHandoff, "utf8")} bytes) — inspect it before re-delegating or resume with resumeFrom: ${outcome.runId}`);
633
682
  return {
634
683
  ok,
635
684
  handoff: outcome.handoff,
636
685
  details,
686
+ ...(notes.length ? { modelNote: notes.join("; ") } : {}),
637
687
  ...(outcome.error ? { error: outcome.error } : {}),
638
688
  };
639
689
  }
package/commands.ts CHANGED
@@ -19,6 +19,7 @@ export type DelegateIntent =
19
19
  | { kind: "help" }
20
20
  | { kind: "cancel"; runId?: string }
21
21
  | { kind: "inspect"; runId?: string }
22
+ | { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
22
23
  | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
23
24
  | { kind: "invalid"; token: string; usage: string };
24
25
 
@@ -30,6 +31,7 @@ export const DELEGATE_USAGE = [
30
31
  "/delegate paths config and run-store paths",
31
32
  "/delegate doctor diagnostics (no LLM call)",
32
33
  "/delegate cancel [run-id] cancel the active (or matching) run",
34
+ "/delegate resume <run-id> <task...> continue a prior run's child session",
33
35
  "/delegate inspect [run-id] show run metadata (defaults to latest)",
34
36
  "/delegate run <general|research> <task...> run with an explicit role",
35
37
  "/delegate research <task...> research-role shorthand",
@@ -48,6 +50,7 @@ const RESERVED_FIRST_TOKENS = new Set([
48
50
  "help",
49
51
  "cancel",
50
52
  "inspect",
53
+ "resume",
51
54
  "run",
52
55
  "research",
53
56
  ]);
@@ -91,6 +94,15 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
91
94
  const rest = trimmed.slice("inspect".length).trim();
92
95
  return { kind: "inspect", runId: rest || undefined };
93
96
  }
97
+ case "resume": {
98
+ const rest = trimmed.slice("resume".length).trim();
99
+ if (!rest) return invalid("resume");
100
+ const { task, timeoutMs } = extractFlags(rest);
101
+ const runId = task.split(/\s+/)[0] ?? "";
102
+ const body = task.slice(runId.length).trim();
103
+ if (!runId || !body) return invalid("resume");
104
+ return { kind: "resume", runId, task: body, timeoutMs };
105
+ }
94
106
  case "run": {
95
107
  const rest = trimmed.slice("run".length).trim();
96
108
  if (!rest) return invalid("run");
@@ -124,7 +136,7 @@ function invalid(token: string): DelegateIntent {
124
136
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
125
137
  const words = (prefix ?? "").trimStart();
126
138
  const tokens = words.split(/\s+/);
127
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "run ", "research "];
139
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "resume ", "run ", "research "];
128
140
 
129
141
  const matches: string[] = [];
130
142
  if (tokens.length <= 1) {
@@ -138,7 +150,7 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
138
150
  for (const role of ROLE_NAMES) {
139
151
  if (role.startsWith(p)) matches.push(`${role} `);
140
152
  }
141
- } else if (tokens[0] === "cancel" || tokens[0] === "inspect") {
153
+ } else if (tokens[0] === "cancel" || tokens[0] === "inspect" || tokens[0] === "resume") {
142
154
  const p = tokens[1] ?? "";
143
155
  for (const id of recentRunIds) {
144
156
  if (id.startsWith(p)) matches.push(`${id} `);
package/config.ts CHANGED
@@ -16,6 +16,12 @@ export interface DelegateConfigV1 {
16
16
  inactivityTimeoutMs: number;
17
17
  hardTimeoutMs: number;
18
18
  killGraceMs: number;
19
+ /** R2: how long to wait for a killed child's final handoff answer. */
20
+ handoffGraceMs: number;
21
+ /** Bounded wait for the mandatory-handoff enforcement answer (default 60 s). */
22
+ handoffEnforceTimeoutMs: number;
23
+ /** R1: watchdog budget while a tool call is in flight (default: hard). */
24
+ stuckToolTimeoutMs?: number;
19
25
  maxRuns: number;
20
26
  maxRunAgeDays: number;
21
27
  updateThrottleMs: number;
@@ -29,6 +35,9 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
29
35
  inactivityTimeoutMs: 300_000,
30
36
  hardTimeoutMs: 1_800_000,
31
37
  killGraceMs: 5_000,
38
+ handoffGraceMs: 90_000,
39
+ handoffEnforceTimeoutMs: 60_000,
40
+ stuckToolTimeoutMs: undefined,
32
41
  maxRuns: 50,
33
42
  maxRunAgeDays: 30,
34
43
  updateThrottleMs: 100,
@@ -40,6 +49,9 @@ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
40
49
  inactivityTimeoutMs: 1_000,
41
50
  hardTimeoutMs: 1_000,
42
51
  killGraceMs: 100,
52
+ handoffGraceMs: 1_000,
53
+ handoffEnforceTimeoutMs: 1_000,
54
+ stuckToolTimeoutMs: 1_000,
43
55
  maxRuns: 1,
44
56
  maxRunAgeDays: 1,
45
57
  updateThrottleMs: 0,
@@ -51,6 +63,9 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
51
63
  inactivityTimeoutMs: 86_400_000,
52
64
  hardTimeoutMs: 604_800_000,
53
65
  killGraceMs: 60_000,
66
+ handoffGraceMs: 600_000,
67
+ handoffEnforceTimeoutMs: 600_000,
68
+ stuckToolTimeoutMs: 604_800_000,
54
69
  maxRuns: 10_000,
55
70
  maxRunAgeDays: 3650,
56
71
  updateThrottleMs: 5_000,
@@ -202,13 +217,21 @@ export function clampConfigField(key: string, value: number): number | null {
202
217
  export function resolveRunTimeouts(
203
218
  baseCfg: DelegateConfigV1,
204
219
  timeoutMs?: number,
205
- ): { hardMs: number; inactivityMs: number } {
206
- const hardMs = timeoutMs !== undefined ? clampTimeoutMs(timeoutMs) : baseCfg.hardTimeoutMs;
220
+ ): { hardMs: number; inactivityMs: number; stuckToolMs: number; hardSource: "per-run" | "config" } {
221
+ const perRun = timeoutMs !== undefined;
222
+ const hardMs = perRun ? clampTimeoutMs(timeoutMs!) : baseCfg.hardTimeoutMs;
207
223
  const inactivityMs = Math.min(
208
224
  baseCfg.inactivityTimeoutMs,
209
225
  Math.max(1_000, Math.floor(hardMs / 2)),
210
226
  );
211
- return { hardMs, inactivityMs };
227
+ // R1: while a tool call is in flight the watchdog uses the stuck-tool
228
+ // budget (default: the full hard timeout), so legitimate long-running
229
+ // tool calls (test matrices, benchmarks, soaks) are never idle-killed.
230
+ const stuckToolMs = Math.min(
231
+ baseCfg.stuckToolTimeoutMs ?? hardMs,
232
+ hardMs,
233
+ );
234
+ return { hardMs, inactivityMs, stuckToolMs, hardSource: perRun ? "per-run" : "config" };
212
235
  }
213
236
 
214
237
  /** Human-readable duration for TUI display and prefilled inputs. */
package/handoff.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * delegate — the mandatory structured handoff contract (child → parent).
3
+ *
4
+ * Principle: anything the harness NEEDS from a model must be a validated
5
+ * protocol step, never free text we hope has the right shape. The child's
6
+ * final report is submitted through the `handoff` tool with this schema;
7
+ * malformed submissions fail as tool errors and the child must retry, and a
8
+ * child that settles without submitting is re-prompted (bounded) by the
9
+ * runner before any free-text fallback is accepted.
10
+ *
11
+ * Pi-free: shared by the child-side tool registration (index.ts), the
12
+ * runner's stream capture + renderer, and the tests.
13
+ */
14
+
15
+ import { Type as t } from "typebox";
16
+
17
+ // ── Contract ──────────────────────────────────────────────────────────────
18
+
19
+ export const HANDOFF_OUTCOMES = ["done", "partial", "blocked"] as const;
20
+ export type HandoffOutcome = (typeof HANDOFF_OUTCOMES)[number];
21
+
22
+ export const HANDOFF_CHANGE_ACTIONS = ["created", "modified", "deleted"] as const;
23
+ export type HandoffChangeAction = (typeof HANDOFF_CHANGE_ACTIONS)[number];
24
+
25
+ export const HANDOFF_VERIFY_RESULTS = ["pass", "fail", "not_run"] as const;
26
+ export type HandoffVerifyResult = (typeof HANDOFF_VERIFY_RESULTS)[number];
27
+
28
+ export interface HandoffSubmission {
29
+ outcome: HandoffOutcome;
30
+ /** 1..2000 chars — the essential result statement. */
31
+ summary: string;
32
+ changes: Array<{ path: string; action: HandoffChangeAction; note?: string }>;
33
+ verification: Array<{ command: string; result: HandoffVerifyResult; note?: string }>;
34
+ /** Required when outcome is partial|blocked: precise next steps. */
35
+ remaining: string[];
36
+ risks: string[];
37
+ }
38
+
39
+ export interface HandoffValidation {
40
+ ok: boolean;
41
+ value?: HandoffSubmission;
42
+ errors: string[];
43
+ }
44
+
45
+ const LIMITS = {
46
+ summaryMax: 2000,
47
+ listMax: 50,
48
+ strMax: 500,
49
+ } as const;
50
+
51
+ function isRecord(v: unknown): v is Record<string, unknown> {
52
+ return !!v && typeof v === "object" && !Array.isArray(v);
53
+ }
54
+
55
+ function str(v: unknown): string | null {
56
+ return typeof v === "string" ? v : null;
57
+ }
58
+
59
+ function boundedString(v: unknown, max: number): string | null {
60
+ const s = str(v);
61
+ return s !== null && s.trim().length > 0 && s.length <= max ? s : null;
62
+ }
63
+
64
+ /**
65
+ * Validate a raw handoff submission. Returns every problem found (the child
66
+ * sees the full list and can fix all fields in one retry), plus the
67
+ * normalized value on success.
68
+ */
69
+ export function validateHandoffSubmission(input: unknown): HandoffValidation {
70
+ const errors: string[] = [];
71
+ if (!isRecord(input)) {
72
+ return { ok: false, errors: ["handoff: submission must be an object with the handoff tool's fields"] };
73
+ }
74
+
75
+ // outcome
76
+ const outcome = str(input.outcome);
77
+ if (!(HANDOFF_OUTCOMES as readonly string[]).includes(outcome ?? "")) {
78
+ errors.push(`handoff.outcome: must be one of ${HANDOFF_OUTCOMES.join("|")} (got ${JSON.stringify(input.outcome)})`);
79
+ }
80
+
81
+ // summary
82
+ let summary = boundedString(input.summary, LIMITS.summaryMax);
83
+ if (summary === null) {
84
+ if (typeof input.summary === "string" && input.summary.trim()) {
85
+ errors.push(`handoff.summary: ${input.summary.length} chars exceeds the ${LIMITS.summaryMax} limit`);
86
+ } else {
87
+ errors.push("handoff.summary: required, non-empty");
88
+ }
89
+ } else {
90
+ summary = summary.trim();
91
+ }
92
+
93
+ // changes
94
+ const changes: HandoffSubmission["changes"] = [];
95
+ if (input.changes !== undefined) {
96
+ if (!Array.isArray(input.changes)) {
97
+ errors.push("handoff.changes: must be an array");
98
+ } else if (input.changes.length > LIMITS.listMax) {
99
+ errors.push(`handoff.changes: ${input.changes.length} entries exceeds the ${LIMITS.listMax} limit`);
100
+ } else {
101
+ input.changes.forEach((c, i) => {
102
+ if (!isRecord(c)) {
103
+ errors.push(`handoff.changes[${i}]: must be an object {path, action, note?}`);
104
+ return;
105
+ }
106
+ const path = boundedString(c.path, LIMITS.strMax);
107
+ if (!path) errors.push(`handoff.changes[${i}].path: required non-empty path`);
108
+ const action = str(c.action);
109
+ if (!(HANDOFF_CHANGE_ACTIONS as readonly string[]).includes(action ?? "")) {
110
+ errors.push(`handoff.changes[${i}].action: must be one of ${HANDOFF_CHANGE_ACTIONS.join("|")}`);
111
+ }
112
+ if (path && action) {
113
+ const note = boundedString(c.note ?? "", LIMITS.strMax);
114
+ changes.push({
115
+ path: path.trim(),
116
+ action: action as HandoffChangeAction,
117
+ ...(note ? { note: note.trim() } : {}),
118
+ });
119
+ }
120
+ });
121
+ }
122
+ }
123
+
124
+ // verification
125
+ const verification: HandoffSubmission["verification"] = [];
126
+ if (input.verification !== undefined) {
127
+ if (!Array.isArray(input.verification)) {
128
+ errors.push("handoff.verification: must be an array");
129
+ } else if (input.verification.length > LIMITS.listMax) {
130
+ errors.push(`handoff.verification: ${input.verification.length} entries exceeds the ${LIMITS.listMax} limit`);
131
+ } else {
132
+ input.verification.forEach((v, i) => {
133
+ if (!isRecord(v)) {
134
+ errors.push(`handoff.verification[${i}]: must be an object {command, result, note?}`);
135
+ return;
136
+ }
137
+ const command = boundedString(v.command, LIMITS.strMax);
138
+ if (!command) errors.push(`handoff.verification[${i}].command: required non-empty`);
139
+ const result = str(v.result);
140
+ if (!(HANDOFF_VERIFY_RESULTS as readonly string[]).includes(result ?? "")) {
141
+ errors.push(`handoff.verification[${i}].result: must be one of ${HANDOFF_VERIFY_RESULTS.join("|")}`);
142
+ }
143
+ if (command && result) {
144
+ const note = boundedString(v.note ?? "", LIMITS.strMax);
145
+ verification.push({
146
+ command: command.trim(),
147
+ result: result as HandoffVerifyResult,
148
+ ...(note ? { note: note.trim() } : {}),
149
+ });
150
+ }
151
+ });
152
+ }
153
+ }
154
+
155
+ // remaining — REQUIRED unless outcome is done
156
+ const remaining: string[] = [];
157
+ if (input.remaining !== undefined) {
158
+ if (!Array.isArray(input.remaining)) {
159
+ errors.push("handoff.remaining: must be an array of strings");
160
+ } else if (input.remaining.length > LIMITS.listMax) {
161
+ errors.push(`handoff.remaining: ${input.remaining.length} entries exceeds the ${LIMITS.listMax} limit`);
162
+ } else {
163
+ input.remaining.forEach((r, i) => {
164
+ const s = boundedString(r, LIMITS.strMax);
165
+ if (!s) errors.push(`handoff.remaining[${i}]: must be a non-empty string`);
166
+ else remaining.push(s.trim());
167
+ });
168
+ }
169
+ }
170
+ if (outcome && outcome !== "done" && remaining.length === 0) {
171
+ errors.push(`handoff.remaining: REQUIRED when outcome is '${outcome}' — list the precise next steps`);
172
+ }
173
+
174
+ // risks
175
+ const risks: string[] = [];
176
+ if (input.risks !== undefined) {
177
+ if (!Array.isArray(input.risks)) {
178
+ errors.push("handoff.risks: must be an array of strings");
179
+ } else if (input.risks.length > LIMITS.listMax) {
180
+ errors.push(`handoff.risks: ${input.risks.length} entries exceeds the ${LIMITS.listMax} limit`);
181
+ } else {
182
+ input.risks.forEach((r, i) => {
183
+ const s = boundedString(r, LIMITS.strMax);
184
+ if (!s) errors.push(`handoff.risks[${i}]: must be a non-empty string`);
185
+ else risks.push(s.trim());
186
+ });
187
+ }
188
+ }
189
+
190
+ if (errors.length > 0 || !outcome || summary === null) {
191
+ return { ok: false, errors };
192
+ }
193
+ return {
194
+ ok: true,
195
+ errors: [],
196
+ value: { outcome: outcome as HandoffOutcome, summary, changes, verification, remaining, risks },
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Deterministic renderer: the parent-facing handoff text is ALWAYS built
202
+ * here from validated fields — never from model-formatted markdown.
203
+ */
204
+ export function renderHandoff(h: HandoffSubmission, opts?: { partial?: boolean }): string {
205
+ const lines: string[] = [];
206
+ lines.push(`## Outcome (${h.outcome}${opts?.partial ? " · captured at kill" : ""})`);
207
+ lines.push(h.summary);
208
+ lines.push("", "## Changes");
209
+ if (h.changes.length === 0) lines.push("none");
210
+ else for (const c of h.changes) lines.push(`- ${c.action} ${c.path}${c.note ? ` — ${c.note}` : ""}`);
211
+ lines.push("", "## Verification");
212
+ if (h.verification.length === 0) lines.push("none run");
213
+ else for (const v of h.verification) lines.push(`- ${v.result === "pass" ? "✓" : v.result === "fail" ? "✗" : "○"} ${v.command}${v.note ? ` — ${v.note}` : ""}`);
214
+ if (h.remaining.length > 0) {
215
+ lines.push("", "## Remaining");
216
+ for (const r of h.remaining) lines.push(`- ${r}`);
217
+ }
218
+ lines.push("", "## Risks and open questions");
219
+ if (h.risks.length === 0) lines.push("none");
220
+ else for (const r of h.risks) lines.push(`- ${r}`);
221
+ return lines.join("\n");
222
+ }
223
+
224
+ /** TypeBox parameter schema for the child-side `handoff` tool registration. */
225
+ export const HandoffToolParams = t.Object({
226
+ outcome: t.Union(
227
+ HANDOFF_OUTCOMES.map((o) => t.Literal(o)) as unknown as [ReturnType<typeof t.Literal>, ...Array<ReturnType<typeof t.Literal>>],
228
+ { description: "done | partial | blocked" },
229
+ ),
230
+ summary: t.String({
231
+ maxLength: LIMITS.summaryMax,
232
+ description: "The essential result statement (required, 1-2000 chars)",
233
+ }),
234
+ changes: t.Optional(
235
+ t.Array(
236
+ t.Object({
237
+ path: t.String({ maxLength: LIMITS.strMax }),
238
+ action: t.Union(
239
+ HANDOFF_CHANGE_ACTIONS.map((a) => t.Literal(a)) as unknown as [ReturnType<typeof t.Literal>, ...Array<ReturnType<typeof t.Literal>>],
240
+ ),
241
+ note: t.Optional(t.String({ maxLength: LIMITS.strMax })),
242
+ }),
243
+ { maxItems: LIMITS.listMax },
244
+ ),
245
+ ),
246
+ verification: t.Optional(
247
+ t.Array(
248
+ t.Object({
249
+ command: t.String({ maxLength: LIMITS.strMax }),
250
+ result: t.Union(
251
+ HANDOFF_VERIFY_RESULTS.map((r) => t.Literal(r)) as unknown as [ReturnType<typeof t.Literal>, ...Array<ReturnType<typeof t.Literal>>],
252
+ ),
253
+ note: t.Optional(t.String({ maxLength: LIMITS.strMax })),
254
+ }),
255
+ { maxItems: LIMITS.listMax },
256
+ ),
257
+ ),
258
+ remaining: t.Optional(
259
+ t.Array(t.String({ maxLength: LIMITS.strMax }), {
260
+ maxItems: LIMITS.listMax,
261
+ description: "REQUIRED when outcome is partial|blocked",
262
+ }),
263
+ ),
264
+ risks: t.Optional(t.Array(t.String({ maxLength: LIMITS.strMax }), { maxItems: LIMITS.listMax })),
265
+ });