@oyasmi/pipiclaw 0.9.0-beta.6 → 0.9.0-beta.8

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 (82) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +154 -132
  3. package/dist/agent/commands.d.ts +6 -0
  4. package/dist/agent/job-manager.js +6 -10
  5. package/dist/agent/progress-formatter.js +3 -3
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.js +2 -1
  8. package/dist/main.js +2 -1
  9. package/dist/memory/extraction.js +0 -1
  10. package/dist/memory/maintenance-gates.d.ts +1 -1
  11. package/dist/memory/maintenance-jobs.js +2 -3
  12. package/dist/memory/metadata.d.ts +0 -15
  13. package/dist/memory/metadata.js +0 -7
  14. package/dist/memory/probation.d.ts +1 -5
  15. package/dist/memory/probation.js +2 -6
  16. package/dist/memory/review-log.js +0 -0
  17. package/dist/memory/scheduler.d.ts +1 -0
  18. package/dist/memory/scheduler.js +64 -6
  19. package/dist/models/auth-cli.d.ts +1 -1
  20. package/dist/models/auth-cli.js +3 -2
  21. package/dist/paths.d.ts +0 -6
  22. package/dist/paths.js +0 -6
  23. package/dist/playbooks/agent-delegation.md +2 -2
  24. package/dist/runtime/app-home.d.ts +32 -0
  25. package/dist/runtime/app-home.js +319 -0
  26. package/dist/runtime/bootstrap.d.ts +1 -67
  27. package/dist/runtime/bootstrap.js +114 -512
  28. package/dist/runtime/delivery.js +1 -1
  29. package/dist/runtime/dingtalk.d.ts +7 -6
  30. package/dist/runtime/dingtalk.js +5 -13
  31. package/dist/runtime/durable-dispatch.d.ts +1 -0
  32. package/dist/runtime/durable-dispatch.js +36 -25
  33. package/dist/runtime/subagent-commands.js +48 -10
  34. package/dist/runtime/task-wake.d.ts +54 -0
  35. package/dist/runtime/task-wake.js +99 -0
  36. package/dist/shared/host-process.d.ts +25 -9
  37. package/dist/shared/host-process.js +59 -10
  38. package/dist/shared/wake-claim.d.ts +23 -0
  39. package/dist/shared/wake-claim.js +26 -0
  40. package/dist/subagents/discovery.d.ts +25 -1
  41. package/dist/subagents/discovery.js +108 -17
  42. package/dist/subagents/external/claude-code.js +13 -5
  43. package/dist/subagents/external/codex-cli.js +9 -3
  44. package/dist/subagents/external/exec.js +1 -0
  45. package/dist/subagents/external/harness.d.ts +22 -0
  46. package/dist/subagents/external/harness.js +40 -7
  47. package/dist/subagents/external/run.d.ts +23 -3
  48. package/dist/subagents/external/run.js +113 -123
  49. package/dist/subagents/external/settlement.d.ts +50 -0
  50. package/dist/subagents/external/settlement.js +123 -0
  51. package/dist/subagents/format.d.ts +4 -0
  52. package/dist/subagents/format.js +7 -0
  53. package/dist/subagents/runs.d.ts +70 -13
  54. package/dist/subagents/runs.js +202 -118
  55. package/dist/subagents/tool.d.ts +27 -2
  56. package/dist/subagents/tool.js +92 -48
  57. package/dist/subagents/verification-outcome.d.ts +26 -0
  58. package/dist/subagents/verification-outcome.js +16 -0
  59. package/dist/subagents/workspace-lease.d.ts +10 -1
  60. package/dist/subagents/workspace-lease.js +15 -2
  61. package/dist/tools/index.js +6 -0
  62. package/dist/tools/memory-manage.js +0 -1
  63. package/dist/tools/subagent-manage.d.ts +20 -6
  64. package/dist/tools/subagent-manage.js +86 -16
  65. package/dist/tui/app.d.ts +1 -1
  66. package/dist/tui/app.js +3 -2
  67. package/dist/tui/cli.d.ts +1 -1
  68. package/dist/tui/cli.js +1 -1
  69. package/dist/tui/terminal-media-sender.d.ts +1 -1
  70. package/examples/sub-agents/README.md +15 -14
  71. package/examples/sub-agents/builder-hard.md +9 -8
  72. package/examples/sub-agents/builder.md +12 -11
  73. package/examples/sub-agents/documenter.md +11 -12
  74. package/examples/sub-agents/explorer.md +16 -13
  75. package/examples/sub-agents/git-committer.md +17 -16
  76. package/examples/sub-agents/log-sifter.md +19 -16
  77. package/examples/sub-agents/planner.md +17 -17
  78. package/examples/sub-agents/reviewer.md +13 -21
  79. package/examples/sub-agents/scout.md +5 -4
  80. package/examples/sub-agents/verifier.md +8 -12
  81. package/examples/sub-agents/worker.md +7 -6
  82. package/package.json +1 -1
@@ -94,13 +94,43 @@ export interface RunRecord extends RunUsage {
94
94
  * enforcing it — an in-process timer dies with the process that set it. */
95
95
  deadlineAt?: number;
96
96
  /** Set before the kill signal is sent, so whichever code path eventually settles this run (the
97
- * live in-process watcher or the cross-restart sweeper) reports why, instead of guessing from
97
+ * live in-process watcher or the cross-restart deadline check) reports why, instead of guessing from
98
98
  * protocol output alone (P1-1). */
99
99
  terminationReason?: "timeout" | "cancelled";
100
100
  argv?: string[];
101
101
  sessionId?: string;
102
102
  leaseKey?: string;
103
103
  mutates?: RunMutates;
104
+ /** Spec 042 D1: persisted at launch so restart reconciliation has the same inputs a live
105
+ * watcher would — the workspace subject hash taken just before an external verify run
106
+ * started, so a restart can still write its attestation instead of silently skipping it. */
107
+ verifySubjectBefore?: string;
108
+ /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
109
+ * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
110
+ maxWallTimeSec?: number;
111
+ /** Spec 042 D1: the real process start time (`setLaunched` time), as opposed to `startedAt`
112
+ * (registration time) — restart reconciliation's duration estimate is measured from here. */
113
+ processStartedAt?: number;
114
+ /** Spec 042 D1: needed only to write a verify attestation from restart reconciliation, which
115
+ * has no other way to reach the channel directory. */
116
+ channelDir?: string;
117
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
118
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
119
+ durationEstimated?: boolean;
120
+ /** Spec 042 D10: non-fatal argv-assembly warnings (e.g. a dropped placeholder token) recorded
121
+ * at launch, shown by `/subagents show`. */
122
+ invocationWarnings?: string[];
123
+ /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell` at launch time
124
+ * (external only) — `follow_up` refuses to resume under a role that has since changed one of
125
+ * these instead of silently reinterpreting the old session under a new harness invocation. */
126
+ roleFingerprint?: string;
127
+ /** Spec 042 D12: the harness adapter's own schema version at launch — lets `/subagents show`
128
+ * distinguish "the target CLI's own protocol changed under an adapter that hasn't caught up"
129
+ * from "the agent itself failed". */
130
+ parserVersion?: number;
131
+ /** Spec 042 D12: best-effort `<executable> --version` output captured at launch (1s timeout,
132
+ * `undefined` if the probe failed or timed out) — the other half of the same diagnosis. */
133
+ cliVersion?: string;
104
134
  }
105
135
  export interface RegisterRunInput {
106
136
  runId: string;
@@ -128,6 +158,9 @@ export interface SettleInput {
128
158
  turns: number;
129
159
  toolCalls: number;
130
160
  durationMs: number;
161
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
162
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
163
+ durationEstimated?: boolean;
131
164
  /** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
132
165
  outputText: string;
133
166
  verificationVerdict?: "pass" | "fail";
@@ -159,6 +192,9 @@ export declare class SubAgentRunManager {
159
192
  /** External launch intents exist before a safe live child handle does. A cancel in that window
160
193
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
161
194
  private readonly externalLaunches;
195
+ /** One-shot deadline checks for external processes adopted during restore. Unlike a child this
196
+ * daemon spawned itself, an adopted process cannot emit a `close` event to this process. */
197
+ private readonly externalRecoveryTimers;
162
198
  private readonly queue;
163
199
  constructor(channelId: string, options: RunManagerOptions);
164
200
  private recordPath;
@@ -202,6 +238,23 @@ export declare class SubAgentRunManager {
202
238
  argv: string[];
203
239
  deadlineAt: number;
204
240
  sessionId?: string;
241
+ /** Spec 042 D1: everything a restart reconciliation might need if this daemon disappears
242
+ * before the process exits — restore/deadline recovery must have the same inputs a live watcher
243
+ * would, not a thinner subset. */
244
+ verifySubjectBefore?: string;
245
+ maxWallTimeSec?: number;
246
+ processStartedAt?: number;
247
+ channelDir?: string;
248
+ /** Spec 042 D10: non-fatal invocation warnings from argv assembly (e.g. a dropped
249
+ * placeholder token), so they survive on the run rather than only ever hitting a log line. */
250
+ invocationWarnings?: string[];
251
+ /** Spec 042 D7: the role's `command`/`externalModelRef`/`shell` fingerprint at launch. */
252
+ roleFingerprint?: string;
253
+ /** Spec 042 D12: the harness adapter's schema version and a best-effort `--version` probe
254
+ * of the target CLI, so a later failure can be diagnosed as "adapter is stale" vs. "the
255
+ * agent itself failed" instead of looking identical. */
256
+ parserVersion?: number;
257
+ cliVersion?: string;
205
258
  }): Promise<void>;
206
259
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
207
260
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
@@ -254,24 +307,28 @@ export declare class SubAgentRunManager {
254
307
  * ever started, so it is judged `lost` the same as an internal run (D1).
255
308
  * - `pid` alive under the same identity: genuinely still running. Left alone.
256
309
  * - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
257
- * while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
258
- * over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
259
- * live post-exit path uses.
310
+ * while the daemon was down. `finalizeExternalRun` (spec 042 D1) parses whatever the process
311
+ * actually wrote before applying `terminationReason` — the same sequence the live post-exit
312
+ * path uses, so a reconciled run never loses usage, output, session id, or its verify verdict
313
+ * just because the daemon happened to be down when the run finished.
260
314
  */
261
315
  private reconcileExternalRun;
316
+ /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
317
+ * liveness before assigning a timeout lets a process that finished just before the deadline be
318
+ * settled from its artifacts as a normal completion. */
319
+ private reconcileExternalRunAtDeadline;
320
+ private clearExternalRecoveryTimer;
321
+ private scheduleExternalRecovery;
262
322
  /**
263
- * Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
264
- * deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
265
- * previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
266
- * settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
267
- * so sweeping one this process itself launched is harmless, not just adopted ones.
323
+ * Daily retention GC. A settled run and all runtime-managed artifacts are deleted together once
324
+ * they are at least seven days old. Other files deliberately created by the delegated task are
325
+ * not recursively removed from the artifact directory.
268
326
  */
269
- sweep(now?: number): Promise<void>;
270
- /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
271
327
  private collectGarbageIfExpired;
328
+ collectGarbage(now?: number): Promise<void>;
272
329
  }
273
- /** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
274
- export declare function stopSubAgentSweeper(): void;
330
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
331
+ export declare function stopSubAgentGarbageCollector(): void;
275
332
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
276
333
  export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
277
334
  export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;
@@ -1,4 +1,4 @@
1
- import { mkdir, readdir, readFile, unlink } from "node:fs/promises";
1
+ import { mkdir, readdir, readFile, stat, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -7,8 +7,8 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
7
7
  import { createSerialQueue } from "../shared/serial-queue.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
- import { classifyExternalOutcome } from "./external/harness.js";
11
- import { getExternalHarness } from "./external/registry.js";
10
+ import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
11
+ import { finalizeExternalRun } from "./external/settlement.js";
12
12
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
13
13
  /**
14
14
  * Longest a dispatching tool call waits for its run to settle before returning a "still running"
@@ -50,6 +50,19 @@ function normalizeRunIdQuery(query) {
50
50
  const hostAdmissionQueue = createSerialQueue();
51
51
  /** Bytes of the reply text carried inline in the completion wake, matching job-manager's tail budget. */
52
52
  const WAKE_OUTPUT_TAIL_CHARS = 2_000;
53
+ /** Settled runs and every runtime-managed artifact are retained together for one week. GC runs
54
+ * daily, so an item can remain for up to one additional sweep interval after this age. */
55
+ const RUN_RETENTION_MS = 7 * 24 * 60 * 60_000;
56
+ const RUN_ARTIFACT_FILENAMES = ["prompt.txt", "system-prompt.txt", "events.jsonl", "stderr.log", "output.md"];
57
+ async function unlinkIfPresent(path) {
58
+ try {
59
+ await unlink(path);
60
+ }
61
+ catch (error) {
62
+ if (error.code !== "ENOENT")
63
+ throw error;
64
+ }
65
+ }
53
66
  function isTerminal(status) {
54
67
  return status !== "running";
55
68
  }
@@ -92,6 +105,9 @@ export class SubAgentRunManager {
92
105
  /** External launch intents exist before a safe live child handle does. A cancel in that window
93
106
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
94
107
  this.externalLaunches = new Map();
108
+ /** One-shot deadline checks for external processes adopted during restore. Unlike a child this
109
+ * daemon spawned itself, an adopted process cannot emit a `close` event to this process. */
110
+ this.externalRecoveryTimers = new Map();
95
111
  this.queue = createSerialQueue();
96
112
  }
97
113
  recordPath(runId) {
@@ -130,12 +146,16 @@ export class SubAgentRunManager {
130
146
  }
131
147
  }
132
148
  async forget(record) {
149
+ // Delete artifacts before the durable record. If a real filesystem error occurs, retaining
150
+ // the record keeps the run eligible for a later daily retry instead of orphaning its files.
151
+ await Promise.all(RUN_ARTIFACT_FILENAMES.map((name) => unlinkIfPresent(join(record.artifactDir, name))));
152
+ const path = this.recordPath(record.runId);
153
+ if (path)
154
+ await unlinkIfPresent(path);
133
155
  this.runs.delete(record.runId);
134
156
  this.cancelHandles.delete(record.runId);
135
157
  this.externalLaunches.delete(record.runId);
136
- const path = this.recordPath(record.runId);
137
- if (path)
138
- await unlink(path).catch(() => undefined);
158
+ this.clearExternalRecoveryTimer(record.runId);
139
159
  }
140
160
  get(runId) {
141
161
  return this.runs.get(runId);
@@ -257,6 +277,14 @@ export class SubAgentRunManager {
257
277
  // at settle(), means a run that crashes before any output is still resumable.
258
278
  if (info.sessionId)
259
279
  record.sessionId = info.sessionId;
280
+ record.verifySubjectBefore = info.verifySubjectBefore;
281
+ record.maxWallTimeSec = info.maxWallTimeSec;
282
+ record.processStartedAt = info.processStartedAt;
283
+ record.channelDir = info.channelDir;
284
+ record.invocationWarnings = info.invocationWarnings;
285
+ record.roleFingerprint = info.roleFingerprint;
286
+ record.parserVersion = info.parserVersion;
287
+ record.cliVersion = info.cliVersion;
260
288
  await this.persist(record, true);
261
289
  }
262
290
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
@@ -264,16 +292,13 @@ export class SubAgentRunManager {
264
292
  async beginWakeConsumption(runId, taskId, dispatchId) {
265
293
  return this.queue.run(runId, async () => {
266
294
  const record = this.runs.get(runId);
267
- const expected = `subagent:${record?.channelId}:${runId}:done`;
268
- if (!record?.settledAt ||
269
- record.taskId !== taskId ||
270
- dispatchId !== expected ||
271
- record.wakeConsumedAt ||
272
- (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
295
+ if (!record)
273
296
  return false;
274
- }
297
+ const expected = `subagent:${record.channelId}:${runId}:done`;
298
+ const eligible = record.settledAt !== undefined && record.taskId === taskId && dispatchId === expected;
275
299
  const previousClaim = record.wakeClaimDispatchId;
276
- record.wakeClaimDispatchId = dispatchId;
300
+ if (!beginWakeClaim(record, eligible, dispatchId))
301
+ return false;
277
302
  try {
278
303
  await this.persist(record, true);
279
304
  }
@@ -287,9 +312,8 @@ export class SubAgentRunManager {
287
312
  async finishWakeConsumption(runId, dispatchId) {
288
313
  await this.queue.run(runId, async () => {
289
314
  const record = this.runs.get(runId);
290
- if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
315
+ if (!record || !finishWakeClaim(record, dispatchId))
291
316
  return;
292
- record.wakeConsumedAt = Date.now();
293
317
  try {
294
318
  await this.persist(record, true);
295
319
  }
@@ -343,6 +367,7 @@ export class SubAgentRunManager {
343
367
  record.turns = input.turns;
344
368
  record.toolCalls = input.toolCalls;
345
369
  record.durationMs = input.durationMs;
370
+ record.durationEstimated = input.durationEstimated;
346
371
  record.verificationVerdict = input.verificationVerdict;
347
372
  record.verificationStrength = input.verificationStrength;
348
373
  if (input.sessionId)
@@ -357,10 +382,11 @@ export class SubAgentRunManager {
357
382
  throw error;
358
383
  }
359
384
  const outputSaved = await this.writeOutputFile(record, input.outputText);
360
- releaseWorkspaceLease(record.leaseKey);
385
+ releaseWorkspaceLease(record.leaseKey, record.runId);
361
386
  record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
362
387
  this.cancelHandles.delete(runId);
363
388
  this.externalLaunches.delete(runId);
389
+ this.clearExternalRecoveryTimer(runId);
364
390
  await this.persist(record);
365
391
  if (!record.usageRecorded) {
366
392
  record.usageRecorded = true;
@@ -443,7 +469,7 @@ export class SubAgentRunManager {
443
469
  user: "SUBAGENT",
444
470
  userName: "SUBAGENT",
445
471
  text: `[SUBAGENT:${record.runId}] Delegation "${record.label}" -> ${record.agent} (${harnessLabel}) finished: ` +
446
- `${record.status} (${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
472
+ `${record.status} (${record.durationEstimated ? "≈" : ""}${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
447
473
  `Result:\n${tail || "(no output)"}\n` +
448
474
  // A run that produced no text has no output.md; pointing at it would send the model
449
475
  // after a file that does not exist. The artifact dir still holds the run's evidence
@@ -479,7 +505,8 @@ export class SubAgentRunManager {
479
505
  }
480
506
  /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
481
507
  async cancel(runId) {
482
- return this.queue.run(runId, async () => {
508
+ let adoptedRecord;
509
+ const status = await this.queue.run(runId, async () => {
483
510
  const record = this.runs.get(runId);
484
511
  if (!record)
485
512
  return "not_found";
@@ -489,9 +516,8 @@ export class SubAgentRunManager {
489
516
  this.cancelHandles.delete(runId);
490
517
  if (cancelHandle) {
491
518
  // External: mark the reason before the handle kills the process, so whichever code
492
- // path settles this run (the live watcher below, or the sweeper if that watcher's
493
- // process disappears mid-kill) reports "cancelled" instead of guessing from
494
- // whatever the process happened to print before it died (P1-1). This also covers
519
+ // path settles this run reports "cancelled" instead of guessing from whatever the
520
+ // process happened to print before it died (P1-1). This also covers
495
521
  // the pre-spawn placeholder handle `claimExternalLaunch` installs: a cancel that
496
522
  // lands in that narrow window durably marks the intent even though the placeholder
497
523
  // itself does nothing else.
@@ -508,11 +534,12 @@ export class SubAgentRunManager {
508
534
  }
509
535
  else if (record.runtime === "external" && record.pid) {
510
536
  // Adopted from a previous daemon (spec 040, D10.3): no live in-process watcher, but
511
- // the run is genuinely still running and the sweeper is observing it. Kill it now
512
- // rather than relabeling a live process "lost" without touching it.
537
+ // the run is genuinely still running. Kill and reconcile it directly rather than
538
+ // waiting for its one-shot deadline check.
513
539
  record.terminationReason = "cancelled";
514
540
  await this.persist(record).catch(() => undefined);
515
541
  await killProcessGroup(record.pid).catch(() => undefined);
542
+ adoptedRecord = record;
516
543
  }
517
544
  else {
518
545
  // Truly unreachable (e.g. an internal run this process did not launch): mark it lost
@@ -521,13 +548,20 @@ export class SubAgentRunManager {
521
548
  record.finishedAt = Date.now();
522
549
  record.settledAt = record.finishedAt;
523
550
  record.wakeEnqueued = true;
524
- releaseWorkspaceLease(record.leaseKey);
551
+ releaseWorkspaceLease(record.leaseKey, record.runId);
525
552
  record.leaseKey = undefined;
526
553
  await this.persist(record);
527
554
  return record.status;
528
555
  }
529
- return "running"; // The handle, or the sweeper once the process exits, drives the settle() call.
556
+ return "running"; // A live handle or the adopted-run reconciliation below drives settlement.
557
+ });
558
+ if (!adoptedRecord)
559
+ return status;
560
+ this.clearExternalRecoveryTimer(runId);
561
+ await this.reconcileExternalRun(adoptedRecord).catch((error) => {
562
+ log.logWarning(`Failed to reconcile cancelled adopted run ${runId}`, errorMessage(error));
530
563
  });
564
+ return this.runs.get(runId)?.status ?? status;
531
565
  }
532
566
  /**
533
567
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
@@ -589,13 +623,31 @@ export class SubAgentRunManager {
589
623
  channelId: record.channelId,
590
624
  workingDirectory: record.workingDirectory,
591
625
  });
592
- if (!rebuilt.ok) {
626
+ if (rebuilt.ok) {
627
+ // Spec 042 D5: persist what was *actually* acquired, not just trust the old
628
+ // value — a symlink swap or a checkout replaced at the same path can make the
629
+ // realpath drift between restarts.
630
+ record.leaseKey = rebuilt.leaseKey;
631
+ await this.persist(record).catch((error) => {
632
+ log.logWarning(`Failed to persist rebuilt lease for run ${record.runId}`, errorMessage(error));
633
+ });
634
+ }
635
+ else {
593
636
  log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
637
+ // This run does not actually hold a lease anymore — record that honestly
638
+ // (spec 042 D5) so a later settle() cannot delete a different holder's lease
639
+ // for the same key, and so displays stop claiming this run still holds it.
640
+ record.leaseKey = undefined;
641
+ await this.persist(record).catch((error) => {
642
+ log.logWarning(`Failed to persist cleared lease for run ${record.runId}`, errorMessage(error));
643
+ });
594
644
  }
595
645
  }
596
- await this.reconcileExternalRun(record).catch((error) => {
646
+ await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
597
647
  log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
598
648
  });
649
+ if (record.status === "running")
650
+ this.scheduleExternalRecovery(record);
599
651
  }
600
652
  if (isTerminal(record.status) && record.settledAt) {
601
653
  // A settled-but-unwoken record means the wake was lost between settlement and
@@ -608,7 +660,6 @@ export class SubAgentRunManager {
608
660
  log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
609
661
  });
610
662
  }
611
- await this.collectGarbageIfExpired(record);
612
663
  }
613
664
  }
614
665
  return restored;
@@ -635,9 +686,10 @@ export class SubAgentRunManager {
635
686
  * ever started, so it is judged `lost` the same as an internal run (D1).
636
687
  * - `pid` alive under the same identity: genuinely still running. Left alone.
637
688
  * - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
638
- * while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
639
- * over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
640
- * live post-exit path uses.
689
+ * while the daemon was down. `finalizeExternalRun` (spec 042 D1) parses whatever the process
690
+ * actually wrote before applying `terminationReason` — the same sequence the live post-exit
691
+ * path uses, so a reconciled run never loses usage, output, session id, or its verify verdict
692
+ * just because the daemon happened to be down when the run finished.
641
693
  */
642
694
  async reconcileExternalRun(record) {
643
695
  if (!record.pid) {
@@ -650,6 +702,7 @@ export class SubAgentRunManager {
650
702
  turns: record.turns ?? 0,
651
703
  toolCalls: record.toolCalls ?? 0,
652
704
  durationMs: Date.now() - record.startedAt,
705
+ durationEstimated: true,
653
706
  outputText: "",
654
707
  }, { announce: true });
655
708
  return;
@@ -657,90 +710,112 @@ export class SubAgentRunManager {
657
710
  if (isProcessAlive(record.pid) && (await this.isSameProcess(record))) {
658
711
  return; // Still genuinely running; nothing to reconcile yet.
659
712
  }
660
- const durationMs = Date.now() - record.startedAt;
661
- if (record.terminationReason === "cancelled") {
662
- await this.settle(record.runId, {
663
- status: "cancelled",
664
- failureReason: "Cancelled by request.",
665
- usage: record.usage,
666
- usageKnown: record.usageKnown,
667
- costKnown: record.costKnown,
668
- turns: record.turns ?? 0,
669
- toolCalls: record.toolCalls ?? 0,
670
- durationMs,
671
- outputText: "",
672
- }, { announce: false });
673
- return;
674
- }
675
- if (record.terminationReason === "timeout") {
676
- const budgetSec = record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined;
713
+ if (!record.harness) {
714
+ // Defensive only: external runs always get a harness at register() time (spec 040 D1).
677
715
  await this.settle(record.runId, {
678
716
  status: "failed",
679
- failureReason: `Wall time budget exceeded${budgetSec ? ` (${budgetSec}s)` : ""}`,
717
+ failureReason: "Run has no recorded harness; cannot judge it.",
680
718
  usage: record.usage,
681
719
  usageKnown: record.usageKnown,
682
720
  costKnown: record.costKnown,
683
721
  turns: record.turns ?? 0,
684
722
  toolCalls: record.toolCalls ?? 0,
685
- durationMs,
723
+ durationMs: Date.now() - record.startedAt,
724
+ durationEstimated: true,
686
725
  outputText: "",
687
726
  }, { announce: true });
688
727
  return;
689
728
  }
690
- const harness = record.harness ? getExternalHarness(record.harness) : undefined;
691
- const eventsText = await readFile(join(record.artifactDir, "events.jsonl"), "utf-8").catch(() => "");
692
- const stderrTail = (await readFile(join(record.artifactDir, "stderr.log"), "utf-8").catch(() => "")).slice(-2_000);
693
- const outcome = harness?.parseOutcome({ eventsText, exitCode: undefined, stderrTail }) ?? {
694
- finalText: "",
695
- terminalSeen: false,
696
- protocolStatus: "unparsable",
697
- usageKnown: false,
698
- costKnown: false,
699
- stderrTail,
700
- };
701
- const classification = harness
702
- ? classifyExternalOutcome(harness.id, outcome)
703
- : { status: "failed", failureReason: `Unknown harness "${record.harness}"; cannot judge this run.` };
704
- await this.settle(record.runId, {
705
- status: classification.status,
706
- failureReason: classification.failureReason,
707
- usage: record.usage,
708
- usageKnown: outcome.usageKnown,
709
- costKnown: outcome.costKnown,
710
- turns: record.turns ?? 0,
711
- toolCalls: record.toolCalls ?? 0,
712
- durationMs,
713
- outputText: outcome.finalText,
714
- sessionId: outcome.sessionId,
715
- }, { announce: true });
729
+ // Duration can only be estimated post-restart: the artifact file's own mtime is the closest
730
+ // proxy for "when the process last wrote something" (D1); wall clock from the last known
731
+ // process start is the fallback when the file is missing (e.g. already GC'd).
732
+ const processStartedAt = record.processStartedAt ?? record.startedAt;
733
+ let durationMs = Date.now() - processStartedAt;
734
+ try {
735
+ const eventsStat = await stat(join(record.artifactDir, "events.jsonl"));
736
+ durationMs = eventsStat.mtimeMs - processStartedAt;
737
+ }
738
+ catch {
739
+ // No events file (or already GC'd) — fall back to the wall-clock estimate above.
740
+ }
741
+ const maxWallTimeSec = record.maxWallTimeSec ??
742
+ (record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined);
743
+ await finalizeExternalRun({
744
+ runId: record.runId,
745
+ channelId: record.channelId,
746
+ channelDir: record.channelDir,
747
+ harnessId: record.harness,
748
+ purpose: record.purpose,
749
+ taskId: record.taskId,
750
+ workingDirectory: record.workingDirectory,
751
+ artifactDir: record.artifactDir,
752
+ exitCode: undefined,
753
+ durationMs: Math.max(0, durationMs),
754
+ durationEstimated: true,
755
+ terminationReason: record.terminationReason,
756
+ maxWallTimeSec,
757
+ verifySubjectBefore: record.verifySubjectBefore,
758
+ }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
759
+ }
760
+ /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
761
+ * liveness before assigning a timeout lets a process that finished just before the deadline be
762
+ * settled from its artifacts as a normal completion. */
763
+ async reconcileExternalRunAtDeadline(record, now = Date.now()) {
764
+ if (record.pid &&
765
+ record.deadlineAt &&
766
+ now >= record.deadlineAt &&
767
+ record.terminationReason !== "timeout" &&
768
+ isProcessAlive(record.pid) &&
769
+ (await this.isSameProcess(record))) {
770
+ await this.markTerminationReason(record.runId, "timeout");
771
+ await killProcessGroup(record.pid).catch(() => undefined);
772
+ }
773
+ await this.reconcileExternalRun(record);
774
+ }
775
+ clearExternalRecoveryTimer(runId) {
776
+ const timer = this.externalRecoveryTimers.get(runId);
777
+ if (!timer)
778
+ return;
779
+ clearTimeout(timer);
780
+ this.externalRecoveryTimers.delete(runId);
781
+ }
782
+ scheduleExternalRecovery(record) {
783
+ if (!record.deadlineAt)
784
+ return;
785
+ this.clearExternalRecoveryTimer(record.runId);
786
+ const timer = setTimeout(() => {
787
+ this.externalRecoveryTimers.delete(record.runId);
788
+ const current = this.runs.get(record.runId);
789
+ if (!current || current.status !== "running")
790
+ return;
791
+ void this.reconcileExternalRunAtDeadline(current).catch((error) => {
792
+ log.logWarning(`Failed to reconcile adopted external run ${current.runId}`, errorMessage(error));
793
+ });
794
+ }, Math.max(0, record.deadlineAt - Date.now()));
795
+ timer.unref?.();
796
+ this.externalRecoveryTimers.set(record.runId, timer);
716
797
  }
717
798
  /**
718
- * Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
719
- * deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
720
- * previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
721
- * settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
722
- * so sweeping one this process itself launched is harmless, not just adopted ones.
799
+ * Daily retention GC. A settled run and all runtime-managed artifacts are deleted together once
800
+ * they are at least seven days old. Other files deliberately created by the delegated task are
801
+ * not recursively removed from the artifact directory.
723
802
  */
724
- async sweep(now = Date.now()) {
803
+ async collectGarbageIfExpired(record, now = Date.now()) {
804
+ if (!record.settledAt)
805
+ return;
806
+ if (now - record.settledAt >= RUN_RETENTION_MS) {
807
+ await this.forget(record);
808
+ }
809
+ }
810
+ async collectGarbage(now = Date.now()) {
725
811
  for (const record of Array.from(this.runs.values())) {
726
- if (record.status !== "running" || record.runtime !== "external" || !record.pid)
812
+ if (!isTerminal(record.status))
727
813
  continue;
728
- if (record.deadlineAt && now >= record.deadlineAt && record.terminationReason !== "timeout") {
729
- await this.markTerminationReason(record.runId, "timeout");
730
- await killProcessGroup(record.pid).catch(() => undefined);
731
- }
732
- await this.reconcileExternalRun(record).catch((error) => {
733
- log.logWarning(`Failed to sweep external run ${record.runId}`, errorMessage(error));
814
+ await this.collectGarbageIfExpired(record, now).catch((error) => {
815
+ log.logWarning(`Failed to garbage-collect sub-agent run ${record.runId}`, errorMessage(error));
734
816
  });
735
817
  }
736
818
  }
737
- /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
738
- async collectGarbageIfExpired(record, now = Date.now()) {
739
- const RETENTION_MS = 24 * 60 * 60_000;
740
- if (record.settledAt && now - record.settledAt >= RETENTION_MS) {
741
- await this.forget(record);
742
- }
743
- }
744
819
  }
745
820
  function emptyUsage() {
746
821
  return {
@@ -762,35 +837,42 @@ function totalRunningSubAgentRuns() {
762
837
  return total;
763
838
  }
764
839
  let runtimeConfig = {};
765
- /** How often the host-wide sweep checks external runs for an overdue deadline or a process that
766
- * exited while nobody was watching it (D10.3). A code constant per CLAUDE.md's rule for numeric
767
- * thresholds — deliberately coarse (budgets are in the 300-1800s range) since it exists to
768
- * guarantee eventual enforcement across a restart, not to replace the live in-process watcher's
769
- * prompt one. */
770
- const SWEEP_INTERVAL_MS = 30_000;
771
- let sweepTimer;
772
- async function sweepAllChannels() {
773
- for (const manager of managers.values()) {
774
- await manager.sweep().catch((error) => log.logWarning("Sub-agent sweep failed", errorMessage(error)));
840
+ const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
841
+ let garbageCollectionTimer;
842
+ let collectingGarbage = false;
843
+ async function collectGarbageAllChannels() {
844
+ if (collectingGarbage)
845
+ return;
846
+ collectingGarbage = true;
847
+ try {
848
+ for (const manager of managers.values()) {
849
+ await manager
850
+ .collectGarbage()
851
+ .catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
852
+ }
853
+ }
854
+ finally {
855
+ collectingGarbage = false;
775
856
  }
776
857
  }
777
- function startSubAgentSweeper() {
778
- if (sweepTimer)
779
- clearInterval(sweepTimer);
780
- sweepTimer = setInterval(() => void sweepAllChannels(), SWEEP_INTERVAL_MS);
781
- sweepTimer.unref?.();
858
+ function startSubAgentGarbageCollector() {
859
+ if (garbageCollectionTimer)
860
+ clearInterval(garbageCollectionTimer);
861
+ garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
862
+ garbageCollectionTimer.unref?.();
782
863
  }
783
- /** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
784
- export function stopSubAgentSweeper() {
785
- if (sweepTimer) {
786
- clearInterval(sweepTimer);
787
- sweepTimer = undefined;
864
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
865
+ export function stopSubAgentGarbageCollector() {
866
+ if (garbageCollectionTimer) {
867
+ clearInterval(garbageCollectionTimer);
868
+ garbageCollectionTimer = undefined;
788
869
  }
789
870
  }
790
871
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
791
872
  export function configureSubAgentRuntime(config) {
792
873
  runtimeConfig = config;
793
- startSubAgentSweeper();
874
+ stopSubAgentGarbageCollector();
875
+ startSubAgentGarbageCollector();
794
876
  }
795
877
  export function getSubAgentRunManager(channelId) {
796
878
  let manager = managers.get(channelId);
@@ -828,6 +910,8 @@ export async function restoreAllSubAgentRuns() {
828
910
  for (const channelId of channelIds) {
829
911
  restored += await getSubAgentRunManager(channelId).restore();
830
912
  }
913
+ // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
914
+ await collectGarbageAllChannels();
831
915
  if (restored > 0) {
832
916
  log.logInfo(`Restored ${restored} sub-agent run record(s)`);
833
917
  }