@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

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 (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  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-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -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",
@@ -721,8 +687,7 @@ export class SubAgentRunManager {
721
687
  ts: String(Date.now()),
722
688
  conversationType: record.channelId.startsWith("group_") ? "2" : "1",
723
689
  dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
724
- // P0-2: a user is genuinely waiting on this result — render the resulting turn's progress
725
- // instead of the "none" style autonomous check-ins get (delivery.ts's `progressStyleOverride`).
690
+ // The result is awaited; the wake itself still runs without a progress card.
726
691
  presentation: "awaited",
727
692
  ...(record.taskId
728
693
  ? {
@@ -835,16 +800,32 @@ export class SubAgentRunManager {
835
800
  let restored = 0;
836
801
  for (const filename of filenames) {
837
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
+ }
838
816
  let record;
839
817
  try {
840
- record = parseRunRecord(await readFile(path, "utf-8"));
818
+ record = parseRunRecord(raw);
841
819
  }
842
820
  catch {
843
821
  record = undefined;
844
822
  }
845
823
  if (!record) {
846
- log.logWarning(`Discarding unreadable sub-agent run record: ${filename}`);
847
- 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);
848
829
  continue;
849
830
  }
850
831
  this.runs.set(record.runId, record);
@@ -869,7 +850,6 @@ export class SubAgentRunManager {
869
850
  durationEstimated: pending.durationEstimated,
870
851
  outputText,
871
852
  verificationVerdict: pending.verificationVerdict,
872
- verificationStrength: pending.verificationStrength,
873
853
  workspaceSummary: pending.workspaceSummary,
874
854
  sessionId: pending.sessionId,
875
855
  }, { announce: pending.announce }).catch((error) => {
@@ -1062,12 +1042,8 @@ export class SubAgentRunManager {
1062
1042
  const maxWallTimeSec = record.maxWallTimeSec ??
1063
1043
  (record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined);
1064
1044
  await finalizeExternalRun({
1065
- runId: record.runId,
1066
- channelId: record.channelId,
1067
- channelDir: record.channelDir,
1068
1045
  harnessId: record.harness,
1069
1046
  purpose: record.purpose,
1070
- taskId: record.taskId,
1071
1047
  workingDirectory: record.workingDirectory,
1072
1048
  artifactDir: record.artifactDir,
1073
1049
  exitCode: undefined,
@@ -1075,9 +1051,6 @@ export class SubAgentRunManager {
1075
1051
  durationEstimated: true,
1076
1052
  terminationReason: record.terminationReason,
1077
1053
  maxWallTimeSec,
1078
- verifySubjectBefore: record.verifySubjectBefore,
1079
- verifyBaseCommit: record.verifyBaseCommit,
1080
- verifyBaselineUntrackedPaths: record.verifyBaselineUntrackedPaths,
1081
1054
  mutates: record.mutates,
1082
1055
  }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
1083
1056
  }
@@ -1144,84 +1117,32 @@ export class SubAgentRunManager {
1144
1117
  }
1145
1118
  }
1146
1119
  /**
1147
- * How deep the scan below looks for record files.
1148
- *
1149
- * Canonical records sit one level under the state root. Records written before the id was
1150
- * escaped sit one level deeper per `/` in the channel id, and a base64 conversation id carries
1151
- * very few; three is generous, and the bound keeps a corrupted or hand-made tree from turning
1152
- * 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.
1153
1123
  */
1154
- const MAX_RECORD_SCAN_DEPTH = 3;
1155
- /** Every directory under `root` that directly holds run records, canonical or not. */
1156
- async function findRecordDirectories(root, dir = root, depth = 0) {
1157
- const entries = await readdir(dir, { withFileTypes: true });
1158
- const found = entries.some((entry) => entry.isFile() && entry.name.endsWith(".json")) ? [dir] : [];
1159
- if (depth >= MAX_RECORD_SCAN_DEPTH)
1160
- return found;
1161
- for (const entry of entries) {
1124
+ async function listRecordChannelIds(stateDir) {
1125
+ const channelIds = [];
1126
+ for (const entry of await readdir(stateDir, { withFileTypes: true })) {
1162
1127
  if (!entry.isDirectory())
1163
1128
  continue;
1164
- try {
1165
- found.push(...(await findRecordDirectories(root, join(dir, entry.name), depth + 1)));
1166
- }
1167
- catch (error) {
1168
- // One unreadable subtree must not hide every other channel's runs.
1169
- log.logWarning(`Failed to scan sub-agent run directory ${entry.name}`, errorMessage(error));
1170
- }
1171
- }
1172
- return found;
1173
- }
1174
- /**
1175
- * The channel a directory of records belongs to, and the records that are not where they belong.
1176
- *
1177
- * The id is read out of the records themselves — the one lossless source, since a directory name
1178
- * is the *escaped* id and `__` cannot be turned back into `/`. Records written before escaping
1179
- * are moved to the canonical directory here, so a run started by an older build is adopted
1180
- * rather than abandoned; without the move it would stay invisible to `restore()` forever, and an
1181
- * external process would keep running with nothing supervising, settling or billing it.
1182
- */
1183
- async function adoptRecordDirectory(stateDir, dir) {
1184
- const filenames = (await readdir(dir)).filter((name) => name.endsWith(".json"));
1185
- const channelIds = new Set();
1186
- let moved = 0;
1187
- for (const filename of filenames) {
1188
- const path = join(dir, filename);
1129
+ const dir = join(stateDir, entry.name);
1189
1130
  let channelId;
1190
1131
  try {
1191
- 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
+ }
1192
1137
  }
1193
1138
  catch {
1194
1139
  channelId = undefined;
1195
1140
  }
1196
- // A record is only trusted to name its own directory if it is a well-formed id; anything
1197
- // else keeps the path-derived fallback, which cannot escape the state root.
1198
- if (!channelId || !isChannelId(channelId)) {
1199
- channelIds.add(relative(stateDir, dir).split(sep).join("/"));
1200
- continue;
1201
- }
1202
- channelIds.add(channelId);
1203
- const canonicalDir = getChannelDir(stateDir, channelId);
1204
- if (canonicalDir === dir)
1205
- continue;
1206
- try {
1207
- await mkdir(canonicalDir, { recursive: true });
1208
- await rename(path, join(canonicalDir, filename));
1209
- moved++;
1210
- }
1211
- catch (error) {
1212
- log.logWarning(`Failed to relocate sub-agent run record ${filename}`, errorMessage(error));
1213
- }
1214
- }
1215
- if (moved > 0) {
1216
- log.logInfo(`Relocated ${moved} sub-agent run record(s) from ${relative(stateDir, dir)}`);
1217
- // Tidy the directory the unescaped id created. `rmdir` refuses a non-empty one, which is
1218
- // exactly the guard wanted: records that could not be moved keep their home.
1219
- await rmdir(dir).catch(() => undefined);
1220
- const parent = dirname(dir);
1221
- if (parent !== stateDir)
1222
- await rmdir(parent).catch(() => undefined);
1141
+ const resolved = channelId && isChannelId(channelId) ? channelId : entry.name;
1142
+ if (isChannelId(resolved))
1143
+ channelIds.push(resolved);
1223
1144
  }
1224
- return Array.from(channelIds);
1145
+ return channelIds;
1225
1146
  }
1226
1147
  /** Owns this application's channel managers and their maintenance timer. */
1227
1148
  export function createSubAgentRuntime(options = {}) {
@@ -1292,25 +1213,15 @@ export function createSubAgentRuntime(options = {}) {
1292
1213
  const stateDir = config.stateDir;
1293
1214
  if (!stateDir)
1294
1215
  return 0;
1295
- const channelIds = new Set();
1296
- let recordDirs;
1216
+ let channelIds;
1297
1217
  try {
1298
1218
  await mkdir(stateDir, { recursive: true });
1299
- recordDirs = await findRecordDirectories(stateDir);
1219
+ channelIds = await listRecordChannelIds(stateDir);
1300
1220
  }
1301
1221
  catch (error) {
1302
1222
  log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1303
1223
  return 0;
1304
1224
  }
1305
- for (const dir of recordDirs) {
1306
- try {
1307
- for (const channelId of await adoptRecordDirectory(stateDir, dir))
1308
- channelIds.add(channelId);
1309
- }
1310
- catch (error) {
1311
- log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
1312
- }
1313
- }
1314
1225
  let restored = 0;
1315
1226
  for (const channelId of channelIds) {
1316
1227
  restored += await get(channelId).restore();