@oyasmi/pipiclaw 0.9.0-beta.7 → 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 (35) hide show
  1. package/dist/memory/review-log.js +0 -0
  2. package/dist/memory/scheduler.d.ts +1 -0
  3. package/dist/memory/scheduler.js +64 -6
  4. package/dist/playbooks/agent-delegation.md +2 -2
  5. package/dist/runtime/bootstrap.js +9 -5
  6. package/dist/runtime/durable-dispatch.d.ts +1 -0
  7. package/dist/runtime/durable-dispatch.js +36 -25
  8. package/dist/runtime/subagent-commands.js +48 -10
  9. package/dist/shared/host-process.d.ts +25 -9
  10. package/dist/shared/host-process.js +59 -10
  11. package/dist/subagents/discovery.d.ts +24 -0
  12. package/dist/subagents/discovery.js +103 -17
  13. package/dist/subagents/external/claude-code.js +10 -3
  14. package/dist/subagents/external/codex-cli.js +9 -3
  15. package/dist/subagents/external/exec.js +1 -0
  16. package/dist/subagents/external/harness.d.ts +22 -0
  17. package/dist/subagents/external/harness.js +22 -4
  18. package/dist/subagents/external/run.d.ts +23 -3
  19. package/dist/subagents/external/run.js +110 -123
  20. package/dist/subagents/external/settlement.d.ts +50 -0
  21. package/dist/subagents/external/settlement.js +123 -0
  22. package/dist/subagents/format.d.ts +4 -0
  23. package/dist/subagents/format.js +7 -0
  24. package/dist/subagents/runs.d.ts +70 -13
  25. package/dist/subagents/runs.js +195 -108
  26. package/dist/subagents/tool.d.ts +27 -2
  27. package/dist/subagents/tool.js +92 -48
  28. package/dist/subagents/verification-outcome.d.ts +26 -0
  29. package/dist/subagents/verification-outcome.js +16 -0
  30. package/dist/subagents/workspace-lease.d.ts +10 -1
  31. package/dist/subagents/workspace-lease.js +15 -2
  32. package/dist/tools/index.js +6 -0
  33. package/dist/tools/subagent-manage.d.ts +20 -6
  34. package/dist/tools/subagent-manage.js +86 -16
  35. 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";
@@ -8,8 +8,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
10
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
11
- import { classifyExternalOutcome } from "./external/harness.js";
12
- import { getExternalHarness } from "./external/registry.js";
11
+ import { finalizeExternalRun } from "./external/settlement.js";
13
12
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
14
13
  /**
15
14
  * Longest a dispatching tool call waits for its run to settle before returning a "still running"
@@ -51,6 +50,19 @@ function normalizeRunIdQuery(query) {
51
50
  const hostAdmissionQueue = createSerialQueue();
52
51
  /** Bytes of the reply text carried inline in the completion wake, matching job-manager's tail budget. */
53
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
+ }
54
66
  function isTerminal(status) {
55
67
  return status !== "running";
56
68
  }
@@ -93,6 +105,9 @@ export class SubAgentRunManager {
93
105
  /** External launch intents exist before a safe live child handle does. A cancel in that window
94
106
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
95
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();
96
111
  this.queue = createSerialQueue();
97
112
  }
98
113
  recordPath(runId) {
@@ -131,12 +146,16 @@ export class SubAgentRunManager {
131
146
  }
132
147
  }
133
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);
134
155
  this.runs.delete(record.runId);
135
156
  this.cancelHandles.delete(record.runId);
136
157
  this.externalLaunches.delete(record.runId);
137
- const path = this.recordPath(record.runId);
138
- if (path)
139
- await unlink(path).catch(() => undefined);
158
+ this.clearExternalRecoveryTimer(record.runId);
140
159
  }
141
160
  get(runId) {
142
161
  return this.runs.get(runId);
@@ -258,6 +277,14 @@ export class SubAgentRunManager {
258
277
  // at settle(), means a run that crashes before any output is still resumable.
259
278
  if (info.sessionId)
260
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;
261
288
  await this.persist(record, true);
262
289
  }
263
290
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
@@ -340,6 +367,7 @@ export class SubAgentRunManager {
340
367
  record.turns = input.turns;
341
368
  record.toolCalls = input.toolCalls;
342
369
  record.durationMs = input.durationMs;
370
+ record.durationEstimated = input.durationEstimated;
343
371
  record.verificationVerdict = input.verificationVerdict;
344
372
  record.verificationStrength = input.verificationStrength;
345
373
  if (input.sessionId)
@@ -354,10 +382,11 @@ export class SubAgentRunManager {
354
382
  throw error;
355
383
  }
356
384
  const outputSaved = await this.writeOutputFile(record, input.outputText);
357
- releaseWorkspaceLease(record.leaseKey);
385
+ releaseWorkspaceLease(record.leaseKey, record.runId);
358
386
  record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
359
387
  this.cancelHandles.delete(runId);
360
388
  this.externalLaunches.delete(runId);
389
+ this.clearExternalRecoveryTimer(runId);
361
390
  await this.persist(record);
362
391
  if (!record.usageRecorded) {
363
392
  record.usageRecorded = true;
@@ -440,7 +469,7 @@ export class SubAgentRunManager {
440
469
  user: "SUBAGENT",
441
470
  userName: "SUBAGENT",
442
471
  text: `[SUBAGENT:${record.runId}] Delegation "${record.label}" -> ${record.agent} (${harnessLabel}) finished: ` +
443
- `${record.status} (${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
472
+ `${record.status} (${record.durationEstimated ? "≈" : ""}${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
444
473
  `Result:\n${tail || "(no output)"}\n` +
445
474
  // A run that produced no text has no output.md; pointing at it would send the model
446
475
  // after a file that does not exist. The artifact dir still holds the run's evidence
@@ -476,7 +505,8 @@ export class SubAgentRunManager {
476
505
  }
477
506
  /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
478
507
  async cancel(runId) {
479
- return this.queue.run(runId, async () => {
508
+ let adoptedRecord;
509
+ const status = await this.queue.run(runId, async () => {
480
510
  const record = this.runs.get(runId);
481
511
  if (!record)
482
512
  return "not_found";
@@ -486,9 +516,8 @@ export class SubAgentRunManager {
486
516
  this.cancelHandles.delete(runId);
487
517
  if (cancelHandle) {
488
518
  // External: mark the reason before the handle kills the process, so whichever code
489
- // path settles this run (the live watcher below, or the sweeper if that watcher's
490
- // process disappears mid-kill) reports "cancelled" instead of guessing from
491
- // 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
492
521
  // the pre-spawn placeholder handle `claimExternalLaunch` installs: a cancel that
493
522
  // lands in that narrow window durably marks the intent even though the placeholder
494
523
  // itself does nothing else.
@@ -505,11 +534,12 @@ export class SubAgentRunManager {
505
534
  }
506
535
  else if (record.runtime === "external" && record.pid) {
507
536
  // Adopted from a previous daemon (spec 040, D10.3): no live in-process watcher, but
508
- // the run is genuinely still running and the sweeper is observing it. Kill it now
509
- // 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.
510
539
  record.terminationReason = "cancelled";
511
540
  await this.persist(record).catch(() => undefined);
512
541
  await killProcessGroup(record.pid).catch(() => undefined);
542
+ adoptedRecord = record;
513
543
  }
514
544
  else {
515
545
  // Truly unreachable (e.g. an internal run this process did not launch): mark it lost
@@ -518,13 +548,20 @@ export class SubAgentRunManager {
518
548
  record.finishedAt = Date.now();
519
549
  record.settledAt = record.finishedAt;
520
550
  record.wakeEnqueued = true;
521
- releaseWorkspaceLease(record.leaseKey);
551
+ releaseWorkspaceLease(record.leaseKey, record.runId);
522
552
  record.leaseKey = undefined;
523
553
  await this.persist(record);
524
554
  return record.status;
525
555
  }
526
- 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.
527
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));
563
+ });
564
+ return this.runs.get(runId)?.status ?? status;
528
565
  }
529
566
  /**
530
567
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
@@ -586,13 +623,31 @@ export class SubAgentRunManager {
586
623
  channelId: record.channelId,
587
624
  workingDirectory: record.workingDirectory,
588
625
  });
589
- 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 {
590
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
+ });
591
644
  }
592
645
  }
593
- await this.reconcileExternalRun(record).catch((error) => {
646
+ await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
594
647
  log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
595
648
  });
649
+ if (record.status === "running")
650
+ this.scheduleExternalRecovery(record);
596
651
  }
597
652
  if (isTerminal(record.status) && record.settledAt) {
598
653
  // A settled-but-unwoken record means the wake was lost between settlement and
@@ -605,7 +660,6 @@ export class SubAgentRunManager {
605
660
  log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
606
661
  });
607
662
  }
608
- await this.collectGarbageIfExpired(record);
609
663
  }
610
664
  }
611
665
  return restored;
@@ -632,9 +686,10 @@ export class SubAgentRunManager {
632
686
  * ever started, so it is judged `lost` the same as an internal run (D1).
633
687
  * - `pid` alive under the same identity: genuinely still running. Left alone.
634
688
  * - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
635
- * while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
636
- * over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
637
- * 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.
638
693
  */
639
694
  async reconcileExternalRun(record) {
640
695
  if (!record.pid) {
@@ -647,6 +702,7 @@ export class SubAgentRunManager {
647
702
  turns: record.turns ?? 0,
648
703
  toolCalls: record.toolCalls ?? 0,
649
704
  durationMs: Date.now() - record.startedAt,
705
+ durationEstimated: true,
650
706
  outputText: "",
651
707
  }, { announce: true });
652
708
  return;
@@ -654,90 +710,112 @@ export class SubAgentRunManager {
654
710
  if (isProcessAlive(record.pid) && (await this.isSameProcess(record))) {
655
711
  return; // Still genuinely running; nothing to reconcile yet.
656
712
  }
657
- const durationMs = Date.now() - record.startedAt;
658
- if (record.terminationReason === "cancelled") {
659
- await this.settle(record.runId, {
660
- status: "cancelled",
661
- failureReason: "Cancelled by request.",
662
- usage: record.usage,
663
- usageKnown: record.usageKnown,
664
- costKnown: record.costKnown,
665
- turns: record.turns ?? 0,
666
- toolCalls: record.toolCalls ?? 0,
667
- durationMs,
668
- outputText: "",
669
- }, { announce: false });
670
- return;
671
- }
672
- if (record.terminationReason === "timeout") {
673
- 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).
674
715
  await this.settle(record.runId, {
675
716
  status: "failed",
676
- failureReason: `Wall time budget exceeded${budgetSec ? ` (${budgetSec}s)` : ""}`,
717
+ failureReason: "Run has no recorded harness; cannot judge it.",
677
718
  usage: record.usage,
678
719
  usageKnown: record.usageKnown,
679
720
  costKnown: record.costKnown,
680
721
  turns: record.turns ?? 0,
681
722
  toolCalls: record.toolCalls ?? 0,
682
- durationMs,
723
+ durationMs: Date.now() - record.startedAt,
724
+ durationEstimated: true,
683
725
  outputText: "",
684
726
  }, { announce: true });
685
727
  return;
686
728
  }
687
- const harness = record.harness ? getExternalHarness(record.harness) : undefined;
688
- const eventsText = await readFile(join(record.artifactDir, "events.jsonl"), "utf-8").catch(() => "");
689
- const stderrTail = (await readFile(join(record.artifactDir, "stderr.log"), "utf-8").catch(() => "")).slice(-2_000);
690
- const outcome = harness?.parseOutcome({ eventsText, exitCode: undefined, stderrTail }) ?? {
691
- finalText: "",
692
- terminalSeen: false,
693
- protocolStatus: "unparsable",
694
- usageKnown: false,
695
- costKnown: false,
696
- stderrTail,
697
- };
698
- const classification = harness
699
- ? classifyExternalOutcome(harness.id, outcome)
700
- : { status: "failed", failureReason: `Unknown harness "${record.harness}"; cannot judge this run.` };
701
- await this.settle(record.runId, {
702
- status: classification.status,
703
- failureReason: classification.failureReason,
704
- usage: record.usage,
705
- usageKnown: outcome.usageKnown,
706
- costKnown: outcome.costKnown,
707
- turns: record.turns ?? 0,
708
- toolCalls: record.toolCalls ?? 0,
709
- durationMs,
710
- outputText: outcome.finalText,
711
- sessionId: outcome.sessionId,
712
- }, { 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);
713
797
  }
714
798
  /**
715
- * Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
716
- * deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
717
- * previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
718
- * settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
719
- * 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.
720
802
  */
721
- 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()) {
722
811
  for (const record of Array.from(this.runs.values())) {
723
- if (record.status !== "running" || record.runtime !== "external" || !record.pid)
812
+ if (!isTerminal(record.status))
724
813
  continue;
725
- if (record.deadlineAt && now >= record.deadlineAt && record.terminationReason !== "timeout") {
726
- await this.markTerminationReason(record.runId, "timeout");
727
- await killProcessGroup(record.pid).catch(() => undefined);
728
- }
729
- await this.reconcileExternalRun(record).catch((error) => {
730
- 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));
731
816
  });
732
817
  }
733
818
  }
734
- /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
735
- async collectGarbageIfExpired(record, now = Date.now()) {
736
- const RETENTION_MS = 24 * 60 * 60_000;
737
- if (record.settledAt && now - record.settledAt >= RETENTION_MS) {
738
- await this.forget(record);
739
- }
740
- }
741
819
  }
742
820
  function emptyUsage() {
743
821
  return {
@@ -759,35 +837,42 @@ function totalRunningSubAgentRuns() {
759
837
  return total;
760
838
  }
761
839
  let runtimeConfig = {};
762
- /** How often the host-wide sweep checks external runs for an overdue deadline or a process that
763
- * exited while nobody was watching it (D10.3). A code constant per CLAUDE.md's rule for numeric
764
- * thresholds — deliberately coarse (budgets are in the 300-1800s range) since it exists to
765
- * guarantee eventual enforcement across a restart, not to replace the live in-process watcher's
766
- * prompt one. */
767
- const SWEEP_INTERVAL_MS = 30_000;
768
- let sweepTimer;
769
- async function sweepAllChannels() {
770
- for (const manager of managers.values()) {
771
- 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;
772
856
  }
773
857
  }
774
- function startSubAgentSweeper() {
775
- if (sweepTimer)
776
- clearInterval(sweepTimer);
777
- sweepTimer = setInterval(() => void sweepAllChannels(), SWEEP_INTERVAL_MS);
778
- sweepTimer.unref?.();
858
+ function startSubAgentGarbageCollector() {
859
+ if (garbageCollectionTimer)
860
+ clearInterval(garbageCollectionTimer);
861
+ garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
862
+ garbageCollectionTimer.unref?.();
779
863
  }
780
- /** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
781
- export function stopSubAgentSweeper() {
782
- if (sweepTimer) {
783
- clearInterval(sweepTimer);
784
- 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;
785
869
  }
786
870
  }
787
871
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
788
872
  export function configureSubAgentRuntime(config) {
789
873
  runtimeConfig = config;
790
- startSubAgentSweeper();
874
+ stopSubAgentGarbageCollector();
875
+ startSubAgentGarbageCollector();
791
876
  }
792
877
  export function getSubAgentRunManager(channelId) {
793
878
  let manager = managers.get(channelId);
@@ -825,6 +910,8 @@ export async function restoreAllSubAgentRuns() {
825
910
  for (const channelId of channelIds) {
826
911
  restored += await getSubAgentRunManager(channelId).restore();
827
912
  }
913
+ // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
914
+ await collectGarbageAllChannels();
828
915
  if (restored > 0) {
829
916
  log.logInfo(`Restored ${restored} sub-agent run record(s)`);
830
917
  }