peaks-loop 4.0.29 → 4.0.30

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 (69) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cli/commands/_register.js +4 -0
  3. package/dist/cli/commands/dispatch-commands.d.ts +5 -41
  4. package/dist/cli/commands/dispatch-commands.js +35 -185
  5. package/dist/cli/commands/evidence-commands.d.ts +12 -0
  6. package/dist/cli/commands/evidence-commands.js +43 -0
  7. package/dist/cli/commands/fresh-context-commands.d.ts +15 -0
  8. package/dist/cli/commands/fresh-context-commands.js +24 -0
  9. package/dist/cli/commands/request-commands.js +2 -96
  10. package/dist/cli/commands/request-format-helpers.d.ts +19 -0
  11. package/dist/cli/commands/request-format-helpers.js +102 -0
  12. package/dist/cli/commands/worktree-auth-commands.js +2 -472
  13. package/dist/cli/commands/worktree-lease-commands.d.ts +21 -0
  14. package/dist/cli/commands/worktree-lease-commands.js +500 -0
  15. package/dist/services/artifacts/request-artifact-service.js +13 -3
  16. package/dist/services/code/auto-compact-lifecycle.d.ts +102 -0
  17. package/dist/services/code/auto-compact-lifecycle.js +235 -0
  18. package/dist/services/code/auto-compact-orchestrator.d.ts +1 -1
  19. package/dist/services/code/auto-compact-orchestrator.js +1 -222
  20. package/dist/services/context/build-dispatch-system-prompt.d.ts +26 -0
  21. package/dist/services/context/build-dispatch-system-prompt.js +38 -3
  22. package/dist/services/dispatch/dispatch-record-types.d.ts +278 -0
  23. package/dist/services/dispatch/dispatch-record-types.js +15 -0
  24. package/dist/services/dispatch/dispatch-record-upgrade.d.ts +5 -0
  25. package/dist/services/dispatch/dispatch-record-upgrade.js +230 -0
  26. package/dist/services/dispatch/dispatch-record-writer.d.ts +3 -278
  27. package/dist/services/dispatch/dispatch-record-writer.js +3 -245
  28. package/dist/services/dispatch/dispatch-sub-agent.d.ts +43 -0
  29. package/dist/services/dispatch/dispatch-sub-agent.js +55 -0
  30. package/dist/services/dispatch/isolation-lease.d.ts +43 -0
  31. package/dist/services/dispatch/isolation-lease.js +129 -0
  32. package/dist/services/evidence/evidence-generator.d.ts +26 -0
  33. package/dist/services/evidence/evidence-generator.js +349 -0
  34. package/dist/services/fresh-context/config.d.ts +1 -0
  35. package/dist/services/fresh-context/config.js +13 -0
  36. package/dist/services/fresh-context/fresh-context-block.d.ts +12 -0
  37. package/dist/services/fresh-context/fresh-context-block.js +40 -0
  38. package/dist/services/fresh-context/trigger-scan.d.ts +30 -0
  39. package/dist/services/fresh-context/trigger-scan.js +29 -0
  40. package/dist/services/skills/hooks-codegate-superpowers.d.ts +65 -0
  41. package/dist/services/skills/hooks-codegate-superpowers.js +204 -0
  42. package/dist/services/skills/hooks-settings-service.d.ts +2 -64
  43. package/dist/services/skills/hooks-settings-service.js +2 -215
  44. package/dist/services/skills/skill-statusline-renderer.d.ts +2 -34
  45. package/dist/services/skills/skill-statusline-renderer.js +1 -184
  46. package/dist/services/skills/statusline-palette.d.ts +62 -0
  47. package/dist/services/skills/statusline-palette.js +190 -0
  48. package/dist/services/slice/slice-decompose-import-edges.d.ts +8 -0
  49. package/dist/services/slice/slice-decompose-import-edges.js +102 -0
  50. package/dist/services/slice/slice-decompose-service.js +3 -198
  51. package/dist/services/slice/slice-decompose-tarjan.d.ts +8 -0
  52. package/dist/services/slice/slice-decompose-tarjan.js +108 -0
  53. package/dist/services/standards/project-standards-service.d.ts +1 -9
  54. package/dist/services/standards/project-standards-service.js +3 -232
  55. package/dist/services/standards/standards-render.d.ts +23 -0
  56. package/dist/services/standards/standards-render.js +238 -0
  57. package/dist/services/standards/ui-library-dispatch-block.d.ts +27 -0
  58. package/dist/services/standards/ui-library-dispatch-block.js +48 -0
  59. package/dist/services/workspace/reconcile-migrate.d.ts +77 -0
  60. package/dist/services/workspace/reconcile-migrate.js +230 -0
  61. package/dist/services/workspace/reconcile-service.d.ts +0 -72
  62. package/dist/services/workspace/reconcile-service.js +3 -220
  63. package/dist/services/workspace/workspace-service.js +13 -2
  64. package/dist/shared/incrementing-number.d.ts +11 -0
  65. package/dist/shared/incrementing-number.js +16 -3
  66. package/package.json +5 -5
  67. package/skills/peaks-code/SKILL.md +6 -2
  68. package/skills/peaks-code/references/fresh-context-preflight.md +81 -0
  69. package/skills/peaks-code/references/sub-agent-dispatch.md +27 -8
@@ -0,0 +1,278 @@
1
+ import type { SubAgentToolCall } from './sub-agent-dispatcher.js';
2
+ /** G6.3 Heartbeat entry — single update written by a running sub-agent. */
3
+ export interface Heartbeat {
4
+ readonly at: string;
5
+ readonly status: HeartbeatStatus;
6
+ readonly progress: number;
7
+ readonly note: string | null;
8
+ }
9
+ export type HeartbeatStatus = 'queued' | 'running' | 'finalizing' | 'done' | 'failed' | 'stale' | 'cancelled' | 'no-execution' | 'never-started' | 'unreadable';
10
+ export type DispatchRecordStatus = 'queued' | 'running' | 'finalizing' | 'done' | 'failed' | 'cancelled' | 'no-execution' | 'stale' | 'never-started' | 'unreadable';
11
+ export type DispatchOutcome = 'success' | 'failed' | 'timeout' | 'cancelled' | 'no-execution';
12
+ /** G2+G5+G6 dispatch record schema (AC-26 + AC-34). */
13
+ export interface DispatchRecord {
14
+ /**
15
+ * Slice 2026-07-29-worktree-l2-extended Part 4.C: schema v3 makes
16
+ * `leaseId` a structurally required field (was `leaseId?: string | null`
17
+ * in v2). The v3 upgrade is a "fill in" migration: every dispatch
18
+ * writer knows its lease id at construction time (Part 2.C's
19
+ * --isolation worktree spawns it; non-isolation dispatches stamp
20
+ * `null`). Readers tolerate both v2 and v3 on disk (see
21
+ * `upgradeRecord`); the `?` was a Part 4.A ergonomic concession
22
+ * to keep 4 unit-test literal sites from breaking the build. v3
23
+ * moves the optional off the type and adds the field to the
24
+ * 4 literal sites in one pass.
25
+ *
26
+ * Slice 2026-07-29-worktree-l2-extended Part 7: schema v3.1 adds
27
+ * `isolationStartedAt: string | null` for the L4 isolation
28
+ * bridge (Part 8 container POC). It's the ISO timestamp of
29
+ * when the isolation mode was set up (e.g. when the worktree
30
+ * was spawned). `null` means the dispatch did not request
31
+ * isolation. The `version` field stays at 3 because the
32
+ * v3 → v3.1 transition is additive; the new field is
33
+ * defaulted to `null` on read so v3 records upgrade cleanly.
34
+ */
35
+ /**
36
+ * Phase A Task 8: schema bumped to v4.1.0 (additive). The bump
37
+ * is purely additive — new fields (`mode`, `vendor`,
38
+ * `autoCompactEvents`, `tokenUsage`) all default safely on
39
+ * read for legacy v4.0.0 / v3.2 / v3.1 / v3 / v2 / v1 records.
40
+ * No existing field semantics changed.
41
+ */
42
+ readonly version: '4.1.0';
43
+ readonly createdAt: string;
44
+ readonly completedAt: string | null;
45
+ readonly outcome: DispatchOutcome;
46
+ readonly artifactPaths: readonly string[];
47
+ readonly disposed: boolean;
48
+ readonly disposedAt: string | null;
49
+ readonly role: string;
50
+ readonly requestId: string;
51
+ readonly sessionId: string;
52
+ readonly prompt: string;
53
+ readonly toolCall: SubAgentToolCall;
54
+ /** G5 batch id (AC-27) — uuid-like opaque token grouping one batch. */
55
+ readonly batchId: string;
56
+ /** G6 fields (AC-34) — backward compat: defaults on read. */
57
+ readonly heartbeats: readonly Heartbeat[];
58
+ readonly lastBeatAt: string | null;
59
+ readonly status: DispatchRecordStatus;
60
+ readonly stage: string | null;
61
+ /**
62
+ * Slice 2026-07-29-worktree-l2-extended Part 3.A + Part 4.C: the
63
+ * worktree lease id stamped on this dispatch (via `peaks sub-agent
64
+ * dispatch --isolation worktree`). The release hook (see
65
+ * markCompleted + `peaks sub-agent heartbeat --status done`)
66
+ * reads this field to auto-call `peaks worktree release` when
67
+ * the sub-agent finalizes. `null` means the dispatch did not
68
+ * request isolation and no release will fire. Persisted for
69
+ * audit + idempotency so a re-read of an old record still
70
+ * surfaces the lease id even if the on-disk lease file has since
71
+ * been gc'd.
72
+ *
73
+ * v3 (Part 4.C) makes this structurally required. v2 records
74
+ * missing the field upgrade to `null` on read (see
75
+ * `upgradeRecord`).
76
+ */
77
+ readonly leaseId: string | null;
78
+ /**
79
+ * Slice 2026-07-29-worktree-l2-extended Part 7: ISO timestamp of
80
+ * when the isolation mode was set up. For `--isolation worktree`
81
+ * this is the moment `peaks worktree spawn` returned; for
82
+ * `--isolation container` (Part 8) it's when the container
83
+ * runtime reported the container as running. `null` when the
84
+ * dispatch did not request isolation. Lets the dashboard
85
+ * compute isolation duration (now - isolationStartedAt) without
86
+ * cross-referencing the metrics stream.
87
+ */
88
+ readonly isolationStartedAt: string | null;
89
+ /**
90
+ * Slice 2026-08-01-subagent-merge-and-e2e (Task 7): v3.2 schema
91
+ * bump. One entry per pid the parent best-effort-killed during
92
+ * the service-shutdown phase of the merge-back pipeline (see
93
+ * src/services/dispatch/service-shutdown.ts). Empty array when
94
+ * the sub-agent did not register any services. The shape is the
95
+ * union of ServiceKillOutcome (skipped=false) and
96
+ * ServiceKillSkipped (skipped=true) — kept as a plain object
97
+ * here so the on-disk schema does not lock onto the helper's
98
+ * narrower union. The reader (merge-back-runner.ts) interprets
99
+ * each entry based on the `skipped` field.
100
+ */
101
+ readonly serviceKill: ReadonlyArray<{
102
+ readonly pid: number;
103
+ readonly name: string;
104
+ readonly signal: string;
105
+ readonly exitCode: number | null;
106
+ readonly skipped?: boolean;
107
+ readonly reason?: string;
108
+ }>;
109
+ /**
110
+ * Slice 2026-08-01-subagent-merge-and-e2e (Task 7): v3.2 schema
111
+ * bump. Counts how many merge attempts the parent session has
112
+ * made against this dispatch's branch. The conflict-replay
113
+ * orchestrator bumps this on each retry (bounded to ONE re-dispatch
114
+ * per merge attempt; multi-conflict cases escalate). Persisted so
115
+ * the dashboard can render the retry count without replaying the
116
+ * merge transcript.
117
+ */
118
+ readonly mergeBackAttempts: number;
119
+ /**
120
+ * Slice 4.0.8 RD §4 D4c (presence-lease-graph): the workflow id +
121
+ * graph node id + graphRef this dispatch is bound to. Persisted
122
+ * directly in the dispatch record (NOT in a sidecar) so the
123
+ * envelope-writer `markCompleted` can auto-transition the bound
124
+ * graph node to `envelope-received` with `ackStatus=pending` in
125
+ * one protected update.
126
+ *
127
+ * The schema bump from `3.2 → 4.0.0` is BREAKING in the sense
128
+ * that the literal type is narrowed. The optional `?` keeps back-
129
+ * compat for old records that pre-date the binding (the
130
+ * `upgradeRecord` reader defaults them to `null`).
131
+ */
132
+ readonly workflowId: string | null;
133
+ readonly graphNodeId: string | null;
134
+ readonly graphRef: string | null;
135
+ /**
136
+ * Phase A Task 8: dispatch execution mode. `in-process` is the
137
+ * current behavior (LLM-side runner, no separate OS process).
138
+ * `detached` is the new path: `peaks sub-agent dispatch --mode
139
+ * detached` spawns a real child OS process running a different
140
+ * LLM vendor (claude / codex / copilot) and reports back via
141
+ * the dispatch record. v4.1.0 is the additive bump; legacy v4.0.0
142
+ * records upgrade to `in-process` on read.
143
+ */
144
+ readonly mode: 'in-process' | 'detached';
145
+ /**
146
+ * Phase A Task 8: vendor id when `mode='detached'`. `null` when
147
+ * the dispatch is in-process. Reserved for future use; current
148
+ * detached sub-agents use `claude` but the schema also accepts
149
+ * `codex` and `copilot` for the vendor-neutral adapter layer.
150
+ */
151
+ readonly vendor: 'claude' | 'codex' | 'copilot' | null;
152
+ /**
153
+ * Phase A Task 8: G8 autoCompact events accumulated by the child
154
+ * LLM during a detached run. Each event records the threshold
155
+ * that fired (0.85 = first warning, 0.95 = second warning) plus
156
+ * token counts before/after. Empty for in-process dispatches
157
+ * and for legacy records upgraded on read.
158
+ */
159
+ readonly autoCompactEvents: ReadonlyArray<{
160
+ readonly at: number;
161
+ readonly threshold: '0.85' | '0.95';
162
+ readonly tokensBefore: number;
163
+ readonly tokensAfter: number;
164
+ readonly scratchFile?: string;
165
+ }>;
166
+ /**
167
+ * Phase A Task 8: G8 token-usage accounting for detached sub-agents.
168
+ * Detached runs have "unlimited spend but recorded" semantics —
169
+ * the cost is recorded for audit but not enforced. `null` when
170
+ * the dispatch is in-process (no detached accounting) or for
171
+ * legacy records upgraded on read.
172
+ */
173
+ readonly tokenUsage: {
174
+ readonly promptTokens: number;
175
+ readonly completionTokens: number;
176
+ readonly totalCostUsd?: number;
177
+ } | null;
178
+ }
179
+ /** Input for the initial write. */
180
+ export type WriteInitialDispatchInput = {
181
+ projectRoot: string;
182
+ sessionId: string;
183
+ requestId: string;
184
+ role: string;
185
+ prompt: string;
186
+ toolCall: SubAgentToolCall;
187
+ batchId: string;
188
+ /** Override the timestamp (testing). */
189
+ now?: () => Date;
190
+ /**
191
+ * Slice 2026-07-29-worktree-l2-extended Part 3.A: the worktree
192
+ * lease id this dispatch owns (set by `peaks sub-agent dispatch
193
+ * --isolation worktree`). Persisted so the finalize-time release
194
+ * hook in `markCompleted` can fire even after the dispatch
195
+ * process exits. Optional; absent when the dispatch did not
196
+ * request isolation.
197
+ */
198
+ leaseId?: string | null;
199
+ /**
200
+ * Slice 2026-07-29-worktree-l2-extended Part 7: ISO timestamp
201
+ * when the isolation mode was set up. Optional on the input
202
+ * (defaults to `null`); dispatch-commands.ts passes the spawn
203
+ * time when `--isolation` is requested.
204
+ */
205
+ isolationStartedAt?: string | null;
206
+ /**
207
+ * Slice 4.0.8: workflow graph binding for the dispatch. Defaults
208
+ * to `null` so a non-graph dispatch (legacy CLI flow, ad-hoc
209
+ * dispatch) still writes a v4.0.0 record.
210
+ */
211
+ workflowId?: string | null;
212
+ graphNodeId?: string | null;
213
+ graphRef?: string | null;
214
+ /**
215
+ * Phase A Task 8: dispatch execution mode. Default `'in-process'`
216
+ * preserves the current LLM-side runner behavior. `'detached'`
217
+ * triggers the new real-OS-process path via
218
+ * `peaks sub-agent dispatch --mode detached`.
219
+ */
220
+ mode?: 'in-process' | 'detached';
221
+ /**
222
+ * Phase A Task 8: vendor id when `mode='detached'`. Required by
223
+ * the adapter layer to know which CLI / runtime to spawn. The
224
+ * schema accepts the three vendors peaks-loop has adapters for
225
+ * (claude / codex / copilot). Ignored when `mode='in-process'`.
226
+ */
227
+ vendor?: 'claude' | 'codex' | 'copilot';
228
+ /**
229
+ * Phase A Task 8: G8 autoCompact events accumulated by the child
230
+ * LLM. Optional on input — most dispatches start with an empty
231
+ * array and the detached runner appends events as they fire.
232
+ */
233
+ autoCompactEvents?: Array<{
234
+ at: number;
235
+ threshold: '0.85' | '0.95';
236
+ tokensBefore: number;
237
+ tokensAfter: number;
238
+ scratchFile?: string;
239
+ }>;
240
+ /**
241
+ * Phase A Task 8: G8 token-usage accounting. Detached runs
242
+ * record spend for audit (unlimited, but persisted). Optional
243
+ * on input; the detached runner fills this in as it streams
244
+ * usage from the vendor API.
245
+ */
246
+ tokenUsage?: {
247
+ promptTokens: number;
248
+ completionTokens: number;
249
+ totalCostUsd?: number;
250
+ };
251
+ };
252
+ /** Heartbeat write input. */
253
+ export type AppendHeartbeatInput = {
254
+ recordPath: string;
255
+ status: HeartbeatStatus;
256
+ progress: number;
257
+ note?: string;
258
+ now?: () => Date;
259
+ };
260
+ /** Lifecycle transition input. */
261
+ export type LifecycleInput = {
262
+ recordPath: string;
263
+ outcome: DispatchOutcome;
264
+ status: DispatchRecordStatus;
265
+ artifactPaths?: readonly string[];
266
+ now?: () => Date;
267
+ /**
268
+ * Slice 2026-06-23-audit-4th #A4: trusted project root. Required
269
+ * so the active-dispatches index can be updated without deriving
270
+ * the root from the recordPath (the same anti-pattern that
271
+ * audit-3rd #1 fixed for heartbeat). The CLI / LLM-side runner
272
+ * passes this from `--project` or `process.cwd()`.
273
+ */
274
+ projectRoot?: string;
275
+ };
276
+ export declare const MAX_PROMPT_BYTES: number;
277
+ export declare const NOTE_MAX_CHARS = 200;
278
+ export declare const MS_PER_DAY: number;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * PRD-002b slice 2 — extract dispatch-record size budgets (max-prompt
3
+ * bytes, note truncation cap) + time-math primitives so the
4
+ * no-magic-numbers rule stops flagging the writer pipeline.
5
+ */
6
+ const BYTES_PER_KB = 1024;
7
+ const MAX_PROMPT_KB = 256;
8
+ export const MAX_PROMPT_BYTES = MAX_PROMPT_KB * BYTES_PER_KB;
9
+ export const NOTE_MAX_CHARS = 200;
10
+ const MS_PER_SECOND = 1_000;
11
+ const SECONDS_PER_MINUTE = 60;
12
+ const MINUTES_PER_HOUR = 60;
13
+ const HOURS_PER_DAY = 24;
14
+ export const MS_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;
15
+ const REDACTION_MAX_SCAN_DEPTH = 20;
@@ -0,0 +1,5 @@
1
+ import type { DispatchOutcome, DispatchRecord, DispatchRecordStatus } from './dispatch-record-types.js';
2
+ export declare function upgradeRecord(parsed: unknown): DispatchRecord;
3
+ declare function isDispatchStatus(v: unknown): v is DispatchRecordStatus;
4
+ declare function isOutcome(v: unknown): v is DispatchOutcome;
5
+ export { isDispatchStatus, isOutcome };
@@ -0,0 +1,230 @@
1
+ export function upgradeRecord(parsed) {
2
+ if (!isObject(parsed)) {
3
+ throw new Error('Dispatch record root must be an object');
4
+ }
5
+ const obj = parsed;
6
+ // Slice 4.0.8: 3.2 → 4.0.0 schema bump. Phase A Task 8: 4.0.0 → 4.1.0
7
+ // (additive). The literal type narrows to '4.1.0' but legacy v4.0.0 /
8
+ // v3.2 / v3.1 / 3 / 2 / 1 records are accepted transparently and
9
+ // upgraded on read.
10
+ const rawVersion = obj.version;
11
+ if (rawVersion !== '4.1.0' && rawVersion !== '4.0.0' && rawVersion !== '3.2' && rawVersion !== '3.1' && rawVersion !== 3 && rawVersion !== 2 && rawVersion !== 1) {
12
+ throw new Error(`Dispatch record version mismatch: expected '4.1.0', '4.0.0', '3.2', '3.1', 3, 2, or 1, got ${JSON.stringify(rawVersion)}. ` +
13
+ 'The v1 → v4.1.0 migration is in-file; records from much older or newer builds must be regenerated.');
14
+ }
15
+ const legacy = parseUpgradeRecordLegacyFields(obj);
16
+ const migration = parseUpgradeRecordMigrationFields(obj);
17
+ return {
18
+ version: '4.1.0',
19
+ createdAt: legacy.createdAt,
20
+ completedAt: legacy.completedAt,
21
+ outcome: legacy.outcome,
22
+ artifactPaths: legacy.artifactPaths,
23
+ disposed: legacy.disposed,
24
+ disposedAt: legacy.disposedAt,
25
+ role: legacy.role,
26
+ requestId: legacy.requestId,
27
+ sessionId: legacy.sessionId,
28
+ prompt: legacy.prompt,
29
+ toolCall: legacy.toolCall,
30
+ batchId: legacy.batchId,
31
+ heartbeats: legacy.heartbeats,
32
+ lastBeatAt: legacy.lastBeatAt,
33
+ status: legacy.status,
34
+ stage: migration.stage,
35
+ leaseId: migration.leaseId,
36
+ isolationStartedAt: migration.isolationStartedAt,
37
+ serviceKill: migration.serviceKill,
38
+ mergeBackAttempts: migration.mergeBackAttempts,
39
+ workflowId: migration.workflowId,
40
+ graphNodeId: migration.graphNodeId,
41
+ graphRef: migration.graphRef,
42
+ // Phase A Task 8: detached sub-agent fields. Legacy records
43
+ // (pre-4.1.0) default mode='in-process', vendor=null,
44
+ // autoCompactEvents=[], tokenUsage=null. See
45
+ // parseUpgradeRecordMigrationFields for the per-field
46
+ // validation rules.
47
+ mode: migration.mode,
48
+ vendor: migration.vendor,
49
+ autoCompactEvents: migration.autoCompactEvents,
50
+ tokenUsage: migration.tokenUsage
51
+ };
52
+ }
53
+ /**
54
+ * Parse the v1..v3.2 core fields of a legacy dispatch record.
55
+ * PRD-002b slice 6: extracted from `upgradeRecord` so the reader
56
+ * stays under the `max-lines-per-function: 50` ESLint ceiling.
57
+ * Behavior is byte-identical to the previous inline block.
58
+ */
59
+ function parseUpgradeRecordLegacyFields(obj) {
60
+ const role = stringField(obj, 'role');
61
+ const requestId = stringField(obj, 'requestId');
62
+ const sessionId = stringField(obj, 'sessionId');
63
+ const prompt = stringField(obj, 'prompt');
64
+ // Slice 2026-06-23-audit-4th #C2: preserve toolCallVersion on read.
65
+ // Pre-versioning records default to '2.0.0' (the pre-#C2 implicit
66
+ // shape; matches the version stamped by every current dispatcher).
67
+ const rawToolCall = obj.toolCall;
68
+ if (!isObject(rawToolCall) || typeof rawToolCall.name !== 'string') {
69
+ throw new Error('Dispatch record toolCall must be { name, args }');
70
+ }
71
+ const toolCall = {
72
+ name: rawToolCall.name,
73
+ args: (isObject(rawToolCall.args) ? rawToolCall.args : {}),
74
+ ...(typeof rawToolCall.toolCallVersion === 'string' ? { toolCallVersion: rawToolCall.toolCallVersion } : { toolCallVersion: '2.0.0' })
75
+ };
76
+ const createdAt = stringField(obj, 'createdAt');
77
+ const heartbeats = Array.isArray(obj.heartbeats)
78
+ ? obj.heartbeats.filter(isValidHeartbeat)
79
+ : [];
80
+ const lastBeatAt = typeof obj.lastBeatAt === 'string' ? obj.lastBeatAt : null;
81
+ // Slice 2026-07-29-dispatch-stall-governance / S1 (UQ-1) — `no-execution`
82
+ // keeps its natural "dispatched, never executed" reading; an unparseable
83
+ // status field now resolves to a *distinct* `unreadable` label so the
84
+ // caller can tell "corrupt record" apart from "record written, no first
85
+ // heartbeat" (which is the new `never-started` state).
86
+ const status = isDispatchStatus(obj.status)
87
+ ? obj.status
88
+ : 'unreadable';
89
+ const completedAt = typeof obj.completedAt === 'string' ? obj.completedAt : null;
90
+ const outcome = isOutcome(obj.outcome) ? obj.outcome : 'no-execution';
91
+ const artifactPaths = Array.isArray(obj.artifactPaths)
92
+ ? obj.artifactPaths.filter((p) => typeof p === 'string')
93
+ : [];
94
+ const disposed = obj.disposed === true;
95
+ const disposedAt = typeof obj.disposedAt === 'string' ? obj.disposedAt : null;
96
+ const batchId = typeof obj.batchId === 'string' && obj.batchId.length > 0
97
+ ? obj.batchId
98
+ : 'legacy-batch';
99
+ return {
100
+ role,
101
+ requestId,
102
+ sessionId,
103
+ prompt,
104
+ toolCall,
105
+ createdAt,
106
+ heartbeats,
107
+ lastBeatAt,
108
+ status,
109
+ completedAt,
110
+ outcome,
111
+ artifactPaths,
112
+ disposed,
113
+ disposedAt,
114
+ batchId
115
+ };
116
+ }
117
+ /**
118
+ * Parse the post-v3 migration fields of a legacy dispatch record.
119
+ * PRD-002b slice 6: extracted from `upgradeRecord` so the reader
120
+ * stays under the `max-lines-per-function: 50` ESLint ceiling.
121
+ * Behavior is byte-identical to the previous inline block.
122
+ */
123
+ function parseUpgradeRecordMigrationFields(obj) {
124
+ return {
125
+ // Slice 2026-07-29-dispatch-stall-governance / S5 (AC-5.1 / PB-2)
126
+ // — legacy records (pre-slice) had no `stage` field. The reader
127
+ // defaults to `null` so the watch surface can tell "no stage ever
128
+ // emitted" apart from "stage: ''" (which is itself a *valid*
129
+ // round-trip through the writer — an empty stage is rejected by
130
+ // `setStage`, but a record that round-tripped through a non-strict
131
+ // tool would land here).
132
+ stage: typeof obj.stage === 'string' && obj.stage.length > 0 ? obj.stage : null,
133
+ // Slice 2026-07-29-worktree-l2-extended Part 3.A: legacy records
134
+ // have no `leaseId`; default to `null` so the auto-release hook
135
+ // in `markCompleted` is a clean no-op for them.
136
+ leaseId: typeof obj.leaseId === 'string' && /^[a-f0-9]{16}$/.test(obj.leaseId)
137
+ ? obj.leaseId
138
+ : null,
139
+ // Slice 2026-07-29-worktree-l2-extended Part 7: v3 → v3.1
140
+ // migration. Legacy records have no `isolationStartedAt`; default
141
+ // to `null`. v3.1 readers can treat the field as opt-in.
142
+ isolationStartedAt: typeof obj.isolationStartedAt === 'string' && obj.isolationStartedAt.length > 0
143
+ ? obj.isolationStartedAt
144
+ : null,
145
+ // Slice 2026-08-01-subagent-merge-and-e2e (Task 7): v3.1 → v3.2
146
+ // migration. Legacy v3.1 records have no `serviceKill` or
147
+ // `mergeBackAttempts` fields. Default to [] and 0 so the
148
+ // merge-back-runner (Task 9) can read either schema on disk.
149
+ serviceKill: Array.isArray(obj.serviceKill)
150
+ ? (obj.serviceKill.filter((e) => {
151
+ if (typeof e !== 'object' || e === null)
152
+ return false;
153
+ const o = e;
154
+ return typeof o.pid === 'number' && typeof o.name === 'string' && typeof o.signal === 'string' && (o.exitCode === null || typeof o.exitCode === 'number');
155
+ }))
156
+ : [],
157
+ mergeBackAttempts: typeof obj.mergeBackAttempts === 'number' && Number.isFinite(obj.mergeBackAttempts) && obj.mergeBackAttempts >= 0
158
+ ? Math.floor(obj.mergeBackAttempts)
159
+ : 0,
160
+ // Slice 4.0.8: 3.2 → 4.0.0 migration. v3.2 records on disk
161
+ // pre-date the workflow-graph binding; default all three
162
+ // fields to `null` so a legacy record upgrades transparently.
163
+ workflowId: typeof obj.workflowId === 'string' && /^[a-zA-Z0-9._-]{1,200}$/.test(obj.workflowId) ? obj.workflowId : null,
164
+ graphNodeId: typeof obj.graphNodeId === 'string' && /^[a-zA-Z0-9._-]{1,200}$/.test(obj.graphNodeId) ? obj.graphNodeId : null,
165
+ graphRef: typeof obj.graphRef === 'string' ? obj.graphRef : null,
166
+ // Phase A Task 8: 4.0.0 → 4.1.0 migration. Pre-4.1.0 records
167
+ // have no mode / vendor / autoCompactEvents / tokenUsage
168
+ // fields. Default to safe in-process / null / [] / null so
169
+ // legacy records upgrade transparently without breaking
170
+ // consumers (e.g. the dashboard, the merge-back-runner).
171
+ mode: obj.mode === 'detached' ? 'detached' : 'in-process',
172
+ vendor: obj.vendor === 'claude' || obj.vendor === 'codex' || obj.vendor === 'copilot' ? obj.vendor : null,
173
+ autoCompactEvents: Array.isArray(obj.autoCompactEvents)
174
+ ? obj.autoCompactEvents.filter((e) => typeof e?.at === 'number' &&
175
+ (e?.threshold === '0.85' || e?.threshold === '0.95') &&
176
+ typeof e?.tokensBefore === 'number' &&
177
+ typeof e?.tokensAfter === 'number')
178
+ : [],
179
+ tokenUsage: typeof obj.tokenUsage === 'object' && obj.tokenUsage !== null && typeof obj.tokenUsage.promptTokens === 'number' && typeof obj.tokenUsage.completionTokens === 'number'
180
+ ? {
181
+ promptTokens: obj.tokenUsage.promptTokens,
182
+ completionTokens: obj.tokenUsage.completionTokens,
183
+ ...(typeof obj.tokenUsage.totalCostUsd === 'number'
184
+ ? { totalCostUsd: obj.tokenUsage.totalCostUsd }
185
+ : {}),
186
+ }
187
+ : null
188
+ };
189
+ }
190
+ function isObject(v) {
191
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
192
+ }
193
+ function stringField(obj, key) {
194
+ const v = obj[key];
195
+ if (typeof v !== 'string') {
196
+ throw new Error(`Dispatch record field '${key}' must be a string (got ${typeof v})`);
197
+ }
198
+ return v;
199
+ }
200
+ function isValidHeartbeat(v) {
201
+ if (!isObject(v))
202
+ return false;
203
+ return (typeof v.at === 'string' &&
204
+ isHeartbeatStatus(v.status) &&
205
+ typeof v.progress === 'number' &&
206
+ (v.note === null || typeof v.note === 'string'));
207
+ }
208
+ function isHeartbeatStatus(v) {
209
+ return (v === 'queued' || v === 'running' || v === 'finalizing' ||
210
+ v === 'done' || v === 'failed' || v === 'stale' ||
211
+ // Slice 2026-07-29-dispatch-stall-governance / S2 — accept the
212
+ // S1 terminal members so a sub-agent can report `cancelled`,
213
+ // `no-execution`, `never-started`, or `unreadable` through the
214
+ // heartbeat CLI.
215
+ v === 'cancelled' || v === 'no-execution' ||
216
+ v === 'never-started' || v === 'unreadable');
217
+ }
218
+ function isDispatchStatus(v) {
219
+ return (v === 'queued' || v === 'running' || v === 'finalizing' ||
220
+ v === 'done' || v === 'failed' || v === 'cancelled' ||
221
+ v === 'no-execution' || v === 'stale' ||
222
+ // Slice 2026-07-29-dispatch-stall-governance / S1 — accept the two
223
+ // new terminal members from the startup-timeout service.
224
+ v === 'never-started' || v === 'unreadable');
225
+ }
226
+ function isOutcome(v) {
227
+ return (v === 'success' || v === 'failed' || v === 'timeout' ||
228
+ v === 'cancelled' || v === 'no-execution');
229
+ }
230
+ export { isDispatchStatus, isOutcome };