@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.3

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 (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -1,21 +1,15 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import * as log from "../../log.js";
4
- import { formatLocalTime } from "../../shared/local-time.js";
5
- import { errorMessage } from "../../shared/text-utils.js";
6
- import { changedPathsSummary, workspaceSubjectHash } from "../../tasks/artifact-subject.js";
7
- import { writeVerificationAttestation } from "../../tasks/verification.js";
8
- import { resolveVerificationOutcome } from "../verification-outcome.js";
3
+ import { resolveVerificationVerdict } from "../verification-outcome.js";
4
+ import { changedPathsSummary } from "../workspace-summary.js";
9
5
  import { classifyExternalOutcome } from "./harness.js";
10
6
  import { getExternalHarness } from "./registry.js";
11
7
  /**
12
8
  * Spec 042 D1: the one place an external run's parsed outcome becomes a `SettleInput`, and the
13
- * one place its verify verdict gets decided and attested. Before this module existed, that logic
14
- * was written three times — the live post-exit path (`external/run.ts`), and restart
15
- * reconciliation (`runs.ts`) — and the third copy was the thinnest: it never read `events.jsonl`
16
- * at all on a cancelled/timed-out run, and never attempted a verify attestation, because the
17
- * inputs it would have needed (`verifySubjectBefore`, `channelDir`) were never persisted. Both
18
- * defects are closed by making this the only path either caller can take.
9
+ * one place its verify verdict gets decided. Before this module existed, that logic was written
10
+ * three times — the live post-exit path (`external/run.ts`), and restart reconciliation
11
+ * (`runs.ts`) — and the third copy was the thinnest: it never read `events.jsonl` at all on a
12
+ * cancelled/timed-out run. Making this the only path either caller can take closes that defect.
19
13
  */
20
14
  const STDERR_TAIL_CHARS = 2_000;
21
15
  /**
@@ -56,10 +50,10 @@ export function buildExternalSettleInput(input) {
56
50
  };
57
51
  }
58
52
  /**
59
- * Read this run's artifact files, parse them through its harness, decide its verdict (including a
60
- * verify attestation when applicable), and hand the result to `settle`. Both the live post-exit
61
- * path and restart reconciliation call this and only this — there is no second implementation to
62
- * drift out of sync with the first (spec 042 F1).
53
+ * Read this run's artifact files, parse them through its harness, decide its verdict (for a
54
+ * `purpose=verify` run), and hand the result to `settle`. Both the live post-exit path and
55
+ * restart reconciliation call this and only this — there is no second implementation to drift out
56
+ * of sync with the first (spec 042 F1).
63
57
  */
64
58
  export async function finalizeExternalRun(input, settle, options) {
65
59
  const harness = getExternalHarness(input.harnessId);
@@ -93,57 +87,12 @@ export async function finalizeExternalRun(input, settle, options) {
93
87
  if (workspaceSummary)
94
88
  settleInput = { ...settleInput, workspaceSummary };
95
89
  }
96
- const shouldVerify = input.purpose === "verify" &&
97
- input.taskId !== undefined &&
98
- input.channelDir !== undefined &&
99
- settleInput.status === "completed";
100
- if (!shouldVerify) {
101
- await settle(settleInput, options);
90
+ if (input.purpose === "verify" && settleInput.status === "completed") {
91
+ // A verifier that did not finish cleanly gets no verdict at all; one that did is judged on
92
+ // what it printed, so `runFailed` is false by construction here.
93
+ const verificationVerdict = resolveVerificationVerdict({ finalText: outcome.finalText, runFailed: false });
94
+ await settle({ ...settleInput, verificationVerdict }, options);
102
95
  return;
103
96
  }
104
- // D9: an external verifier's tools cannot be structurally removed, so a before/after subject
105
- // hash is the only after-the-fact check available. The base and untracked baseline came from the
106
- // launch-time snapshot (persisted so restart reconciliation has it too).
107
- const baseSubjectAvailable = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths !== undefined;
108
- const partialBaseSubject = input.verifyBaseCommit !== undefined && input.verifyBaselineUntrackedPaths === undefined;
109
- const subjectAfter = partialBaseSubject
110
- ? undefined
111
- : await workspaceSubjectHash(input.workingDirectory, baseSubjectAvailable
112
- ? {
113
- baseCommit: input.verifyBaseCommit,
114
- baselineUntrackedPaths: input.verifyBaselineUntrackedPaths,
115
- }
116
- : {});
117
- const verification = resolveVerificationOutcome({
118
- subjectBefore: input.verifySubjectBefore,
119
- subjectAfter,
120
- finalText: outcome.finalText,
121
- runFailed: false, // shouldVerify already gates on settleInput.status === "completed".
122
- });
123
- // `verifySubjectBefore` and `verifyBaseCommit` are always set together at launch (both come
124
- // from the one all-or-nothing `workspaceSubjectSnapshot()` call in `external/run.ts`), so a
125
- // freshly launched run can never carry a subject hash without a base commit — there is no
126
- // live path left that produces a "legacy-head" attestation. `verification.ts` still reads and
127
- // compares `legacy-head` attestations written before base-relative subjects existed; this is
128
- // only the write side, for a run happening now.
129
- const subjectAvailable = !verification.workspaceChanged && subjectAfter !== undefined && baseSubjectAvailable;
130
- await writeVerificationAttestation(input.channelDir, {
131
- runId: input.runId,
132
- taskId: input.taskId,
133
- verdict: verification.verdict,
134
- checkedAt: formatLocalTime(),
135
- evidence: verification.evidence,
136
- workspaceChanged: verification.workspaceChanged,
137
- subjectHash: subjectAvailable ? subjectAfter : undefined,
138
- subjectDir: subjectAvailable ? input.workingDirectory : undefined,
139
- subjectMode: subjectAvailable ? "base-relative" : undefined,
140
- subjectBaseCommit: subjectAvailable ? input.verifyBaseCommit : undefined,
141
- subjectBaselineUntrackedPaths: subjectAvailable ? input.verifyBaselineUntrackedPaths : undefined,
142
- // External verifiers cannot have their tools structurally removed the way an internal
143
- // verifier's are — advisory, not enforced (D9).
144
- verificationStrength: "advisory",
145
- }).catch((error) => {
146
- log.logWarning(`Failed to write verification attestation for run ${input.runId}`, errorMessage(error));
147
- });
148
- await settle({ ...settleInput, verificationVerdict: verification.verdict, verificationStrength: "advisory" }, options);
97
+ await settle(settleInput, options);
149
98
  }
@@ -5,7 +5,7 @@ import type { UsageLedger } from "../usage/ledger.js";
5
5
  /**
6
6
  * The run: one abstraction level for delegation, whether it executes as an in-process sub-agent
7
7
  * or (from spec 040 phase 2 onward) a short-lived external CLI process. See
8
- * `docs/specs/040-async-delegation-and-external-agents/design.md`, D1.
8
+ * `docs/archive/specs/040-async-delegation-and-external-agents/design.md`, D1.
9
9
  *
10
10
  * State machine vocabulary is borrowed from `job-manager.ts`'s `JobStatus` rather than inventing
11
11
  * a second one. Only three facts are persisted as idempotent markers (D1/P5) because only three
@@ -71,6 +71,8 @@ export interface RunRecord extends RunUsage {
71
71
  model?: string;
72
72
  purpose: "work" | "verify";
73
73
  taskId?: string;
74
+ /** The task's Work Items id this run was dispatched for (spec 052, D4). */
75
+ item?: string;
74
76
  workingDirectory: string;
75
77
  artifactDir: string;
76
78
  status: RunStatus;
@@ -80,9 +82,8 @@ export interface RunRecord extends RunUsage {
80
82
  failureReason?: string;
81
83
  turns?: number;
82
84
  toolCalls?: number;
85
+ /** The checker's declared `VERDICT:` for a `purpose=verify` run (spec 052, D6): information for the leader, not a gate. */
83
86
  verificationVerdict?: "pass" | "fail";
84
- /** `enforced` only for a structurally read-only verifier; write-capable/external runs are advisory. */
85
- verificationStrength?: "enforced" | "advisory";
86
87
  /** P2-2: `git status --porcelain` taken right after a `mutates: "write"` run finished, so the
87
88
  * wake's reader does not have to spend its own first tool call finding out what changed. */
88
89
  workspaceSummary?: string;
@@ -96,8 +97,8 @@ export interface RunRecord extends RunUsage {
96
97
  settlementPending?: PendingSettlement;
97
98
  /** Set once this run's usage has been written to the ledger; guards against double billing. */
98
99
  usageRecorded?: boolean;
99
- /** Set once this run's cost (and, for a verifier, its round) has been credited to its task.
100
- * Separate from `usageRecorded` so a replayed settlement can never write a second round. */
100
+ /** Set once this run's cost has been credited to its task. Separate from `usageRecorded` so a
101
+ * replayed settlement can never credit it twice. */
101
102
  taskAccounted?: boolean;
102
103
  /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
103
104
  wakeEnqueued?: boolean;
@@ -119,19 +120,14 @@ export interface RunRecord extends RunUsage {
119
120
  sessionId?: string;
120
121
  leaseKey?: string;
121
122
  mutates?: RunMutates;
122
- /** Persisted at launch so restart reconciliation has the same inputs as a live verifier. */
123
- verifySubjectBefore?: string;
124
- /** Fixed commit and initial untracked manifest for the base-relative verification subject. */
125
- verifyBaseCommit?: string;
126
- verifyBaselineUntrackedPaths?: string[];
127
123
  /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
128
124
  * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
129
125
  maxWallTimeSec?: number;
130
126
  /** Spec 042 D1: the real process start time (`setLaunched` time), as opposed to `startedAt`
131
127
  * (registration time) — restart reconciliation's duration estimate is measured from here. */
132
128
  processStartedAt?: number;
133
- /** Spec 042 D1: needed only to write a verify attestation from restart reconciliation, which
134
- * has no other way to reach the channel directory. */
129
+ /** This run's channel directory, so settlement (including restart reconciliation) can reach the
130
+ * owning task's log (spec 052, D4). */
135
131
  channelDir?: string;
136
132
  /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
137
133
  * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
@@ -163,11 +159,12 @@ export interface RegisterRunInput {
163
159
  model?: string;
164
160
  purpose: "work" | "verify";
165
161
  taskId?: string;
162
+ item?: string;
166
163
  workingDirectory: string;
167
164
  artifactDir: string;
168
- /** This run's channel directory — where its owning task lives (spec 051, D7/D10). Set at
169
- * registration for every runtime, so settlement can credit the task whether the run was
170
- * internal or external; the external launch path re-persists it with the rest of its info. */
165
+ /** This run's channel directory — where its owning task lives. Set at registration for every
166
+ * runtime, so settlement can credit the task whether the run was internal or external; the
167
+ * external launch path re-persists it with the rest of its info. */
171
168
  channelDir?: string;
172
169
  /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
173
170
  leaseKey?: string;
@@ -184,7 +181,6 @@ interface PendingSettlement {
184
181
  durationMs: number;
185
182
  durationEstimated?: boolean;
186
183
  verificationVerdict?: "pass" | "fail";
187
- verificationStrength?: "enforced" | "advisory";
188
184
  workspaceSummary?: string;
189
185
  sessionId?: string;
190
186
  finishedAt: number;
@@ -205,7 +201,6 @@ export interface SettleInput {
205
201
  /** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
206
202
  outputText: string;
207
203
  verificationVerdict?: "pass" | "fail";
208
- verificationStrength?: "enforced" | "advisory";
209
204
  /** P2-2: see `RunRecord.workspaceSummary`. */
210
205
  workspaceSummary?: string;
211
206
  /** The harness's own session/thread id, captured even on failure so a later resume can still use it. */
@@ -323,9 +318,6 @@ export declare class SubAgentRunManager {
323
318
  /** Spec 042 D1: everything a restart reconciliation might need if this daemon disappears
324
319
  * before the process exits — restore/deadline recovery must have the same inputs a live watcher
325
320
  * would, not a thinner subset. */
326
- verifySubjectBefore?: string;
327
- verifyBaseCommit?: string;
328
- verifyBaselineUntrackedPaths?: string[];
329
321
  maxWallTimeSec?: number;
330
322
  processStartedAt?: number;
331
323
  channelDir?: string;
@@ -367,17 +359,11 @@ export declare class SubAgentRunManager {
367
359
  announce: boolean;
368
360
  }): Promise<void>;
369
361
  /**
370
- * Credit one settled run to the task that owns it: cost onto the cycle, and — for a verifier —
371
- * one round onto the rework ledger. Best-effort by design: a task whose file has since been
372
- * archived or hand-deleted must not block the completion wake.
362
+ * Credit one settled run to the task that owns it: cost onto its usage, outcome onto its log.
363
+ * Best-effort by design: a task whose file has since been archived or hand-deleted must not
364
+ * block the completion wake.
373
365
  */
374
366
  private creditOwningTask;
375
- /**
376
- * The `purpose=work` run this verdict most plausibly judged: the same task's latest work run
377
- * started before the verifier. Left `undefined` rather than guessed when there is none — an
378
- * unattributed round is honest, a wrong attribution is not.
379
- */
380
- private latestWorkRunFor;
381
367
  /**
382
368
  * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
383
369
  * call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readdir, readFile, rename, rmdir, stat, unlink } from "node:fs/promises";
2
- import { dirname, join, relative, sep } from "node:path";
2
+ import { join } from "node:path";
3
3
  import { getChannelDir, isChannelId } from "../channel/channel-paths.js";
4
4
  import * as log from "../log.js";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -11,10 +11,7 @@ import { errorMessage } from "../shared/text-utils.js";
11
11
  import { isRecord } from "../shared/type-guards.js";
12
12
  import { createEmptyUsageTotals } from "../shared/types.js";
13
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
14
- import { DEFAULT_TASK_BUDGET } from "../tasks/budget.js";
15
- import { recordTaskCost, recordVerificationRound } from "../tasks/rounds.js";
16
- import { readStoredTask } from "../tasks/store.js";
17
- import { attestationRejectionReason } from "../tasks/verification.js";
14
+ import { logTaskDispatch, logTaskSettlement } from "../tasks/work-log.js";
18
15
  import { startExternalProgressTail } from "./external/progress-tail.js";
19
16
  import { finalizeExternalRun } from "./external/settlement.js";
20
17
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
@@ -99,7 +96,6 @@ function createPendingSettlement(input, finishedAt, announce) {
99
96
  durationMs: input.durationMs,
100
97
  durationEstimated: input.durationEstimated,
101
98
  verificationVerdict: input.verificationVerdict,
102
- verificationStrength: input.verificationStrength,
103
99
  workspaceSummary: input.workspaceSummary,
104
100
  sessionId: input.sessionId,
105
101
  finishedAt,
@@ -117,7 +113,6 @@ function applyPendingSettlement(record, pending) {
117
113
  record.durationMs = pending.durationMs;
118
114
  record.durationEstimated = pending.durationEstimated;
119
115
  record.verificationVerdict = pending.verificationVerdict;
120
- record.verificationStrength = pending.verificationStrength;
121
116
  record.workspaceSummary = pending.workspaceSummary;
122
117
  if (pending.sessionId)
123
118
  record.sessionId = pending.sessionId;
@@ -358,6 +353,17 @@ export class SubAgentRunManager {
358
353
  this.externalLaunches.delete(record.runId);
359
354
  throw error;
360
355
  }
356
+ if (record.taskId && record.channelDir) {
357
+ await logTaskDispatch(record.channelDir, record.taskId, {
358
+ ref: record.runId,
359
+ item: record.item,
360
+ agent: record.agent,
361
+ purpose: record.purpose,
362
+ label: record.label,
363
+ }).catch((error) => {
364
+ log.logWarning(`Failed to log dispatch of ${record.runId} to task ${record.taskId}`, errorMessage(error));
365
+ });
366
+ }
361
367
  return record;
362
368
  }));
363
369
  }
@@ -396,9 +402,6 @@ export class SubAgentRunManager {
396
402
  // at settle(), means a run that crashes before any output is still resumable.
397
403
  if (info.sessionId)
398
404
  record.sessionId = info.sessionId;
399
- record.verifySubjectBefore = info.verifySubjectBefore;
400
- record.verifyBaseCommit = info.verifyBaseCommit;
401
- record.verifyBaselineUntrackedPaths = info.verifyBaselineUntrackedPaths;
402
405
  record.maxWallTimeSec = info.maxWallTimeSec;
403
406
  record.processStartedAt = info.processStartedAt;
404
407
  record.channelDir = info.channelDir;
@@ -575,12 +578,13 @@ export class SubAgentRunManager {
575
578
  });
576
579
  await this.persist(record);
577
580
  }
578
- // Spec 051, D7/D10: credit this run to its task's cycle — cost always, and for a
579
- // purpose=verify run also one rework round. Guarded by its own idempotency marker
580
- // inside the same settlement lock, so a replay adds nothing.
581
+ // Spec 052, D4: tell the owning task this work settled — its cost goes onto the task's
582
+ // budget and the outcome onto its log (the board's source), whether or not the run record
583
+ // is still around by the time the leader looks. Guarded by its own idempotency marker
584
+ // inside the same settlement lock, so a replay writes nothing twice.
581
585
  if (!record.taskAccounted && record.taskId && record.channelDir) {
582
586
  record.taskAccounted = true;
583
- await this.creditOwningTask(record, input).catch((error) => {
587
+ await this.creditOwningTask(record, input, outputSaved).catch((error) => {
584
588
  log.logWarning(`Failed to credit task ${record.taskId} for run ${record.runId}`, errorMessage(error));
585
589
  });
586
590
  await this.persist(record);
@@ -596,63 +600,25 @@ export class SubAgentRunManager {
596
600
  });
597
601
  }
598
602
  /**
599
- * Credit one settled run to the task that owns it: cost onto the cycle, and — for a verifier —
600
- * one round onto the rework ledger. Best-effort by design: a task whose file has since been
601
- * archived or hand-deleted must not block the completion wake.
603
+ * Credit one settled run to the task that owns it: cost onto its usage, outcome onto its log.
604
+ * Best-effort by design: a task whose file has since been archived or hand-deleted must not
605
+ * block the completion wake.
602
606
  */
603
- async creditOwningTask(record, input) {
607
+ async creditOwningTask(record, input, outputSaved) {
604
608
  const channelDir = record.channelDir;
605
609
  const taskId = record.taskId;
606
610
  if (!channelDir || !taskId)
607
611
  return;
608
- const usd = input.usage.cost.total;
609
- const estimated = input.costKnown === false;
610
- if (record.purpose === "verify" && record.verificationVerdict) {
611
- // Fail closed: a PASS only counts once the on-disk attestation still binds to this task,
612
- // this contract and this checkout — exactly the checks `task_verify` ran before it was
613
- // retired. A rejected PASS is recorded as a fail *with its reason*, so the loop sees why
614
- // instead of silently losing a round.
615
- const task = await readStoredTask(channelDir, taskId).catch(() => undefined);
616
- const rejection = task
617
- ? await attestationRejectionReason({
618
- channelDir,
619
- taskId,
620
- runId: record.runId,
621
- taskBody: task.body,
622
- trustedWorkingDirectory: record.workingDirectory,
623
- })
624
- : "task file is missing";
625
- await recordVerificationRound({
626
- channelDir,
627
- taskId,
628
- verifyRunId: record.runId,
629
- verdict: rejection ? "fail" : record.verificationVerdict,
630
- strength: record.verificationStrength ?? "advisory",
631
- workRunId: this.latestWorkRunFor(taskId, record.startedAt),
632
- usd,
633
- usdEstimated: estimated,
634
- reason: rejection,
635
- }, DEFAULT_TASK_BUDGET.rounds);
636
- return;
637
- }
638
- await recordTaskCost(channelDir, taskId, usd, estimated);
639
- }
640
- /**
641
- * The `purpose=work` run this verdict most plausibly judged: the same task's latest work run
642
- * started before the verifier. Left `undefined` rather than guessed when there is none — an
643
- * unattributed round is honest, a wrong attribution is not.
644
- */
645
- latestWorkRunFor(taskId, before) {
646
- let best;
647
- for (const candidate of this.runs.values()) {
648
- if (candidate.taskId !== taskId || candidate.purpose !== "work")
649
- continue;
650
- if (candidate.startedAt > before)
651
- continue;
652
- if (!best || candidate.startedAt > best.startedAt)
653
- best = candidate;
654
- }
655
- return best?.runId;
612
+ await logTaskSettlement(channelDir, taskId, {
613
+ ref: record.runId,
614
+ item: record.item,
615
+ status: record.status,
616
+ verdict: record.purpose === "verify" ? record.verificationVerdict : undefined,
617
+ output: outputSaved ? join(record.artifactDir, "output.md") : undefined,
618
+ tail: input.outputText.slice(-WAKE_OUTPUT_TAIL_CHARS).trim() || undefined,
619
+ changed: record.workspaceSummary,
620
+ durationMs: input.durationMs,
621
+ }, { usd: input.usage.cost.total, estimated: input.costKnown === false });
656
622
  }
657
623
  /**
658
624
  * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
@@ -695,7 +661,7 @@ export class SubAgentRunManager {
695
661
  ? ` It belongs to task ${record.taskId}.${siblingCount > 0 ? ` ${siblingCount} other run(s) for this task are still running.` : ""}`
696
662
  : "";
697
663
  const verdictLine = record.verificationVerdict !== undefined
698
- ? `\nVerdict: ${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? " (advisory)" : ""}`
664
+ ? `\nVerdict: ${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}`
699
665
  : "";
700
666
  const event = {
701
667
  type: record.channelId.startsWith("group_") ? "group" : "dm",
@@ -834,16 +800,32 @@ export class SubAgentRunManager {
834
800
  let restored = 0;
835
801
  for (const filename of filenames) {
836
802
  const path = join(dir, filename);
803
+ // A transient I/O error (EACCES, EIO) reading the file is not the same failure as the
804
+ // file actually being corrupt (R7b): the old code unlinked either way, so a run record
805
+ // that only became briefly unreadable (a permissions slip, a filesystem hiccup) was
806
+ // permanently destroyed instead of retried on the next restart. Only a read that
807
+ // actually succeeds gets to judge the content.
808
+ let raw;
809
+ try {
810
+ raw = await readFile(path, "utf-8");
811
+ }
812
+ catch (error) {
813
+ log.logWarning(`Skipping unreadable sub-agent run record ${filename} (left on disk)`, errorMessage(error));
814
+ continue;
815
+ }
837
816
  let record;
838
817
  try {
839
- record = parseRunRecord(await readFile(path, "utf-8"));
818
+ record = parseRunRecord(raw);
840
819
  }
841
820
  catch {
842
821
  record = undefined;
843
822
  }
844
823
  if (!record) {
845
- log.logWarning(`Discarding unreadable sub-agent run record: ${filename}`);
846
- await unlink(path).catch(() => undefined);
824
+ // Genuinely corrupt content (bad JSON or shape) — quarantine rather than delete, so
825
+ // the evidence survives for a manual look; `.corrupt` files never match the `.json`
826
+ // filter above, so this cannot loop.
827
+ log.logWarning(`Quarantining corrupt sub-agent run record: ${filename}`);
828
+ await rename(path, `${path}.corrupt`).catch(() => undefined);
847
829
  continue;
848
830
  }
849
831
  this.runs.set(record.runId, record);
@@ -868,7 +850,6 @@ export class SubAgentRunManager {
868
850
  durationEstimated: pending.durationEstimated,
869
851
  outputText,
870
852
  verificationVerdict: pending.verificationVerdict,
871
- verificationStrength: pending.verificationStrength,
872
853
  workspaceSummary: pending.workspaceSummary,
873
854
  sessionId: pending.sessionId,
874
855
  }, { announce: pending.announce }).catch((error) => {
@@ -1061,12 +1042,8 @@ export class SubAgentRunManager {
1061
1042
  const maxWallTimeSec = record.maxWallTimeSec ??
1062
1043
  (record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined);
1063
1044
  await finalizeExternalRun({
1064
- runId: record.runId,
1065
- channelId: record.channelId,
1066
- channelDir: record.channelDir,
1067
1045
  harnessId: record.harness,
1068
1046
  purpose: record.purpose,
1069
- taskId: record.taskId,
1070
1047
  workingDirectory: record.workingDirectory,
1071
1048
  artifactDir: record.artifactDir,
1072
1049
  exitCode: undefined,
@@ -1074,9 +1051,6 @@ export class SubAgentRunManager {
1074
1051
  durationEstimated: true,
1075
1052
  terminationReason: record.terminationReason,
1076
1053
  maxWallTimeSec,
1077
- verifySubjectBefore: record.verifySubjectBefore,
1078
- verifyBaseCommit: record.verifyBaseCommit,
1079
- verifyBaselineUntrackedPaths: record.verifyBaselineUntrackedPaths,
1080
1054
  mutates: record.mutates,
1081
1055
  }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
1082
1056
  }
@@ -1143,84 +1117,32 @@ export class SubAgentRunManager {
1143
1117
  }
1144
1118
  }
1145
1119
  /**
1146
- * How deep the scan below looks for record files.
1147
- *
1148
- * Canonical records sit one level under the state root. Records written before the id was
1149
- * escaped sit one level deeper per `/` in the channel id, and a base64 conversation id carries
1150
- * very few; three is generous, and the bound keeps a corrupted or hand-made tree from turning
1151
- * startup into an unbounded walk.
1120
+ * The channel each record directory belongs to. The id is read out of a record itself — the one
1121
+ * lossless source, since a directory name is the *escaped* id and `__` cannot be turned back
1122
+ * into `/` — with the directory name as the fallback for a directory without a readable record.
1152
1123
  */
1153
- const MAX_RECORD_SCAN_DEPTH = 3;
1154
- /** Every directory under `root` that directly holds run records, canonical or not. */
1155
- async function findRecordDirectories(root, dir = root, depth = 0) {
1156
- const entries = await readdir(dir, { withFileTypes: true });
1157
- const found = entries.some((entry) => entry.isFile() && entry.name.endsWith(".json")) ? [dir] : [];
1158
- if (depth >= MAX_RECORD_SCAN_DEPTH)
1159
- return found;
1160
- for (const entry of entries) {
1124
+ async function listRecordChannelIds(stateDir) {
1125
+ const channelIds = [];
1126
+ for (const entry of await readdir(stateDir, { withFileTypes: true })) {
1161
1127
  if (!entry.isDirectory())
1162
1128
  continue;
1163
- try {
1164
- found.push(...(await findRecordDirectories(root, join(dir, entry.name), depth + 1)));
1165
- }
1166
- catch (error) {
1167
- // One unreadable subtree must not hide every other channel's runs.
1168
- log.logWarning(`Failed to scan sub-agent run directory ${entry.name}`, errorMessage(error));
1169
- }
1170
- }
1171
- return found;
1172
- }
1173
- /**
1174
- * The channel a directory of records belongs to, and the records that are not where they belong.
1175
- *
1176
- * The id is read out of the records themselves — the one lossless source, since a directory name
1177
- * is the *escaped* id and `__` cannot be turned back into `/`. Records written before escaping
1178
- * are moved to the canonical directory here, so a run started by an older build is adopted
1179
- * rather than abandoned; without the move it would stay invisible to `restore()` forever, and an
1180
- * external process would keep running with nothing supervising, settling or billing it.
1181
- */
1182
- async function adoptRecordDirectory(stateDir, dir) {
1183
- const filenames = (await readdir(dir)).filter((name) => name.endsWith(".json"));
1184
- const channelIds = new Set();
1185
- let moved = 0;
1186
- for (const filename of filenames) {
1187
- const path = join(dir, filename);
1129
+ const dir = join(stateDir, entry.name);
1188
1130
  let channelId;
1189
1131
  try {
1190
- channelId = parseRunRecord(await readFile(path, "utf-8"))?.channelId;
1132
+ for (const filename of (await readdir(dir)).filter((name) => name.endsWith(".json"))) {
1133
+ channelId = parseRunRecord(await readFile(join(dir, filename), "utf-8"))?.channelId;
1134
+ if (channelId)
1135
+ break;
1136
+ }
1191
1137
  }
1192
1138
  catch {
1193
1139
  channelId = undefined;
1194
1140
  }
1195
- // A record is only trusted to name its own directory if it is a well-formed id; anything
1196
- // else keeps the path-derived fallback, which cannot escape the state root.
1197
- if (!channelId || !isChannelId(channelId)) {
1198
- channelIds.add(relative(stateDir, dir).split(sep).join("/"));
1199
- continue;
1200
- }
1201
- channelIds.add(channelId);
1202
- const canonicalDir = getChannelDir(stateDir, channelId);
1203
- if (canonicalDir === dir)
1204
- continue;
1205
- try {
1206
- await mkdir(canonicalDir, { recursive: true });
1207
- await rename(path, join(canonicalDir, filename));
1208
- moved++;
1209
- }
1210
- catch (error) {
1211
- log.logWarning(`Failed to relocate sub-agent run record ${filename}`, errorMessage(error));
1212
- }
1213
- }
1214
- if (moved > 0) {
1215
- log.logInfo(`Relocated ${moved} sub-agent run record(s) from ${relative(stateDir, dir)}`);
1216
- // Tidy the directory the unescaped id created. `rmdir` refuses a non-empty one, which is
1217
- // exactly the guard wanted: records that could not be moved keep their home.
1218
- await rmdir(dir).catch(() => undefined);
1219
- const parent = dirname(dir);
1220
- if (parent !== stateDir)
1221
- await rmdir(parent).catch(() => undefined);
1141
+ const resolved = channelId && isChannelId(channelId) ? channelId : entry.name;
1142
+ if (isChannelId(resolved))
1143
+ channelIds.push(resolved);
1222
1144
  }
1223
- return Array.from(channelIds);
1145
+ return channelIds;
1224
1146
  }
1225
1147
  /** Owns this application's channel managers and their maintenance timer. */
1226
1148
  export function createSubAgentRuntime(options = {}) {
@@ -1291,25 +1213,15 @@ export function createSubAgentRuntime(options = {}) {
1291
1213
  const stateDir = config.stateDir;
1292
1214
  if (!stateDir)
1293
1215
  return 0;
1294
- const channelIds = new Set();
1295
- let recordDirs;
1216
+ let channelIds;
1296
1217
  try {
1297
1218
  await mkdir(stateDir, { recursive: true });
1298
- recordDirs = await findRecordDirectories(stateDir);
1219
+ channelIds = await listRecordChannelIds(stateDir);
1299
1220
  }
1300
1221
  catch (error) {
1301
1222
  log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1302
1223
  return 0;
1303
1224
  }
1304
- for (const dir of recordDirs) {
1305
- try {
1306
- for (const channelId of await adoptRecordDirectory(stateDir, dir))
1307
- channelIds.add(channelId);
1308
- }
1309
- catch (error) {
1310
- log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1311
- }
1312
- }
1313
1225
  let restored = 0;
1314
1226
  for (const channelId of channelIds) {
1315
1227
  restored += await get(channelId).restore();