@oyasmi/pipiclaw 0.9.2-beta.1 → 0.9.2-beta.2

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.
@@ -75,10 +75,16 @@ export interface RunRecord extends RunUsage {
75
75
  turns?: number;
76
76
  toolCalls?: number;
77
77
  verificationVerdict?: "pass" | "fail";
78
- /** `enforced` for a built-in verifier (tools structurally removed); `advisory` for external (D9). */
78
+ /** `enforced` only for a structurally read-only verifier; write-capable/external runs are advisory. */
79
79
  verificationStrength?: "enforced" | "advisory";
80
80
  /** Set once settlement (write output, free resources) has happened; guards against replay. */
81
81
  settledAt?: number;
82
+ /**
83
+ * Durable settlement intent. While this exists the public status remains `running` and the
84
+ * lease is still held; it lets a restart finish a settlement that crashed after the intent was
85
+ * recorded but before the terminal record was published.
86
+ */
87
+ settlementPending?: PendingSettlement;
82
88
  /** Set once this run's usage has been written to the ledger; guards against double billing. */
83
89
  usageRecorded?: boolean;
84
90
  /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
@@ -101,10 +107,11 @@ export interface RunRecord extends RunUsage {
101
107
  sessionId?: string;
102
108
  leaseKey?: string;
103
109
  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. */
110
+ /** Persisted at launch so restart reconciliation has the same inputs as a live verifier. */
107
111
  verifySubjectBefore?: string;
112
+ /** Fixed commit and initial untracked manifest for the base-relative verification subject. */
113
+ verifyBaseCommit?: string;
114
+ verifyBaselineUntrackedPaths?: string[];
108
115
  /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
109
116
  * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
110
117
  maxWallTimeSec?: number;
@@ -148,6 +155,23 @@ export interface RegisterRunInput {
148
155
  artifactDir: string;
149
156
  /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
150
157
  leaseKey?: string;
158
+ mutates?: RunMutates;
159
+ }
160
+ interface PendingSettlement {
161
+ status: SettleInput["status"];
162
+ failureReason?: string;
163
+ usage: UsageTotals;
164
+ usageKnown: boolean;
165
+ costKnown: boolean;
166
+ turns: number;
167
+ toolCalls: number;
168
+ durationMs: number;
169
+ durationEstimated?: boolean;
170
+ verificationVerdict?: "pass" | "fail";
171
+ verificationStrength?: "enforced" | "advisory";
172
+ sessionId?: string;
173
+ finishedAt: number;
174
+ announce: boolean;
151
175
  }
152
176
  export interface SettleInput {
153
177
  status: "completed" | "failed" | "cancelled" | "lost";
@@ -185,9 +209,9 @@ export declare class SubAgentRunManager {
185
209
  private readonly channelId;
186
210
  private readonly options;
187
211
  private readonly runs;
188
- /** In-memory cancel handles for runs alive in *this* process (internal runs; external process
189
- * kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
190
- * the only thing that could reach an in-process worker anyway (D10.3). */
212
+ /** In-memory cancel handles for runs alive in *this* process (internal worker abort or live
213
+ * external process-group kill). Never persisted: a restart cannot reach an in-process worker,
214
+ * while adopted external runs are cancelled through their persisted pid (D10.3). */
191
215
  private readonly cancelHandles;
192
216
  /** External launch intents exist before a safe live child handle does. A cancel in that window
193
217
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
@@ -242,6 +266,8 @@ export declare class SubAgentRunManager {
242
266
  * before the process exits — restore/deadline recovery must have the same inputs a live watcher
243
267
  * would, not a thinner subset. */
244
268
  verifySubjectBefore?: string;
269
+ verifyBaseCommit?: string;
270
+ verifyBaselineUntrackedPaths?: string[];
245
271
  maxWallTimeSec?: number;
246
272
  processStartedAt?: number;
247
273
  channelDir?: string;
@@ -256,6 +282,12 @@ export declare class SubAgentRunManager {
256
282
  parserVersion?: number;
257
283
  cliVersion?: string;
258
284
  }): Promise<void>;
285
+ /** Persist best-effort probe results after the pid/launch recovery record is already durable.
286
+ * A slow or unavailable `ps`/`--version` probe must never reopen the post-spawn recovery window. */
287
+ updateLaunchMetadata(runId: string, info: {
288
+ pidStartedAt?: string;
289
+ cliVersion?: string;
290
+ }): Promise<void>;
259
291
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
260
292
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
261
293
  beginWakeConsumption(runId: string, taskId: string, dispatchId: string): Promise<boolean>;
@@ -289,7 +321,9 @@ export declare class SubAgentRunManager {
289
321
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
290
322
  * construction (D10.3): the worker lived in the process that just disappeared, so any record
291
323
  * still `running` is settled as `lost` and the channel is woken to say so. External runs are
292
- * left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
324
+ * left for the harness-specific probe (spec 040 phase 2/3), except an adopted write run whose
325
+ * lease cannot be rebuilt: it is killed and settled as `lost` rather than allowed to continue
326
+ * without mutual exclusion.
293
327
  */
294
328
  restore(): Promise<number>;
295
329
  /** Whether `record.pid` is still the same process that was launched, when that can be checked
@@ -297,6 +331,7 @@ export declare class SubAgentRunManager {
297
331
  * launch) means there is nothing to compare against — trust `isProcessAlive` alone rather
298
332
  * than manufacture a false negative. */
299
333
  private isSameProcess;
334
+ private processIdentity;
300
335
  /**
301
336
  * Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
302
337
  * judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
@@ -340,3 +375,4 @@ export declare function channelDelegationTaskIds(channelId: string): Set<string>
340
375
  * like `restoreChannelJobs`.
341
376
  */
342
377
  export declare function restoreAllSubAgentRuns(): Promise<number>;
378
+ export {};
@@ -68,6 +68,42 @@ async function unlinkIfPresent(path) {
68
68
  function isTerminal(status) {
69
69
  return status !== "running";
70
70
  }
71
+ function createPendingSettlement(input, finishedAt, announce) {
72
+ return {
73
+ status: input.status,
74
+ failureReason: input.failureReason,
75
+ usage: input.usage,
76
+ usageKnown: input.usageKnown,
77
+ costKnown: input.costKnown,
78
+ turns: input.turns,
79
+ toolCalls: input.toolCalls,
80
+ durationMs: input.durationMs,
81
+ durationEstimated: input.durationEstimated,
82
+ verificationVerdict: input.verificationVerdict,
83
+ verificationStrength: input.verificationStrength,
84
+ sessionId: input.sessionId,
85
+ finishedAt,
86
+ announce,
87
+ };
88
+ }
89
+ function applyPendingSettlement(record, pending) {
90
+ record.status = pending.status;
91
+ record.failureReason = pending.failureReason;
92
+ record.usage = pending.usage;
93
+ record.usageKnown = pending.usageKnown;
94
+ record.costKnown = pending.costKnown;
95
+ record.turns = pending.turns;
96
+ record.toolCalls = pending.toolCalls;
97
+ record.durationMs = pending.durationMs;
98
+ record.durationEstimated = pending.durationEstimated;
99
+ record.verificationVerdict = pending.verificationVerdict;
100
+ record.verificationStrength = pending.verificationStrength;
101
+ if (pending.sessionId)
102
+ record.sessionId = pending.sessionId;
103
+ record.finishedAt = pending.finishedAt;
104
+ record.settledAt = pending.finishedAt;
105
+ record.settlementPending = undefined;
106
+ }
71
107
  function parseRunRecord(raw) {
72
108
  const value = JSON.parse(raw);
73
109
  if (!isRecord(value) ||
@@ -94,9 +130,9 @@ export class SubAgentRunManager {
94
130
  this.channelId = channelId;
95
131
  this.options = options;
96
132
  this.runs = new Map();
97
- /** In-memory cancel handles for runs alive in *this* process (internal runs; external process
98
- * kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
99
- * the only thing that could reach an in-process worker anyway (D10.3). */
133
+ /** In-memory cancel handles for runs alive in *this* process (internal worker abort or live
134
+ * external process-group kill). Never persisted: a restart cannot reach an in-process worker,
135
+ * while adopted external runs are cancelled through their persisted pid (D10.3). */
100
136
  this.cancelHandles = new Map();
101
137
  /** External launch intents exist before a safe live child handle does. A cancel in that window
102
138
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
@@ -267,26 +303,44 @@ export class SubAgentRunManager {
267
303
  * that restore treats as `lost` rather than guessing (D1/D10.3).
268
304
  */
269
305
  async setLaunched(runId, info) {
270
- const record = this.runs.get(runId);
271
- if (!record)
272
- return;
273
- record.pid = info.pid;
274
- record.pidStartedAt = info.pidStartedAt;
275
- record.argv = info.argv;
276
- record.deadlineAt = info.deadlineAt;
277
- // claude-code pre-assigns its session id before running (D4); persisting it here, not just
278
- // at settle(), means a run that crashes before any output is still resumable.
279
- if (info.sessionId)
280
- record.sessionId = info.sessionId;
281
- record.verifySubjectBefore = info.verifySubjectBefore;
282
- record.maxWallTimeSec = info.maxWallTimeSec;
283
- record.processStartedAt = info.processStartedAt;
284
- record.channelDir = info.channelDir;
285
- record.invocationWarnings = info.invocationWarnings;
286
- record.roleFingerprint = info.roleFingerprint;
287
- record.parserVersion = info.parserVersion;
288
- record.cliVersion = info.cliVersion;
289
- await this.persist(record, true);
306
+ await this.queue.run(runId, async () => {
307
+ const record = this.runs.get(runId);
308
+ if (!record || record.status !== "running")
309
+ return;
310
+ record.pid = info.pid;
311
+ record.pidStartedAt = info.pidStartedAt;
312
+ record.argv = info.argv;
313
+ record.deadlineAt = info.deadlineAt;
314
+ // claude-code pre-assigns its session id before running (D4); persisting it here, not just
315
+ // at settle(), means a run that crashes before any output is still resumable.
316
+ if (info.sessionId)
317
+ record.sessionId = info.sessionId;
318
+ record.verifySubjectBefore = info.verifySubjectBefore;
319
+ record.verifyBaseCommit = info.verifyBaseCommit;
320
+ record.verifyBaselineUntrackedPaths = info.verifyBaselineUntrackedPaths;
321
+ record.maxWallTimeSec = info.maxWallTimeSec;
322
+ record.processStartedAt = info.processStartedAt;
323
+ record.channelDir = info.channelDir;
324
+ record.invocationWarnings = info.invocationWarnings;
325
+ record.roleFingerprint = info.roleFingerprint;
326
+ record.parserVersion = info.parserVersion;
327
+ record.cliVersion = info.cliVersion;
328
+ await this.persist(record, true);
329
+ });
330
+ }
331
+ /** Persist best-effort probe results after the pid/launch recovery record is already durable.
332
+ * A slow or unavailable `ps`/`--version` probe must never reopen the post-spawn recovery window. */
333
+ async updateLaunchMetadata(runId, info) {
334
+ await this.queue.run(runId, async () => {
335
+ const record = this.runs.get(runId);
336
+ if (!record || record.status !== "running" || !record.pid)
337
+ return;
338
+ if (info.pidStartedAt !== undefined)
339
+ record.pidStartedAt = info.pidStartedAt;
340
+ if (info.cliVersion !== undefined)
341
+ record.cliVersion = info.cliVersion;
342
+ await this.persist(record);
343
+ });
290
344
  }
291
345
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
292
346
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
@@ -356,39 +410,35 @@ export class SubAgentRunManager {
356
410
  const record = this.runs.get(runId);
357
411
  if (!record || record.settledAt)
358
412
  return; // Idempotent: already settled, never replay.
359
- // The terminal fields are persisted, required, before any side effect runs (P0-2): a
360
- // failed persist here rolls the record back to `running` so a restart replays settlement
361
- // from scratch instead of applying side effects the disk never recorded.
413
+ // Keep the externally visible record `running` while the settlement intent is made durable.
414
+ // This preserves restart recovery without publishing a terminal status before its lease is
415
+ // released: the caller reaches settle() only after its worker/process has finished.
362
416
  const snapshot = { ...record };
363
- record.status = input.status;
364
- record.failureReason = input.failureReason;
365
- record.usage = input.usage;
366
- record.usageKnown = input.usageKnown;
367
- record.costKnown = input.costKnown;
368
- record.turns = input.turns;
369
- record.toolCalls = input.toolCalls;
370
- record.durationMs = input.durationMs;
371
- record.durationEstimated = input.durationEstimated;
372
- record.verificationVerdict = input.verificationVerdict;
373
- record.verificationStrength = input.verificationStrength;
374
- if (input.sessionId)
375
- record.sessionId = input.sessionId;
376
- record.finishedAt = Date.now();
377
- record.settledAt = record.finishedAt;
378
- try {
379
- await this.persist(record, true);
380
- }
381
- catch (error) {
382
- Object.assign(record, snapshot);
383
- throw error;
417
+ const pending = record.settlementPending ?? createPendingSettlement(input, Date.now(), options.announce);
418
+ if (!record.settlementPending) {
419
+ record.settlementPending = pending;
420
+ try {
421
+ await this.persist(record, true);
422
+ }
423
+ catch (error) {
424
+ Object.assign(record, snapshot);
425
+ throw error;
426
+ }
384
427
  }
385
428
  const outputSaved = await this.writeOutputFile(record, input.outputText);
429
+ // This is the commit point for the observable state transition. Both operations are
430
+ // synchronous and adjacent: no observer can see a terminal record while this run still
431
+ // owns the lease. The durable intent above covers a crash before this point.
386
432
  releaseWorkspaceLease(record.leaseKey, record.runId);
387
- record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
433
+ record.leaseKey = undefined;
434
+ applyPendingSettlement(record, pending);
435
+ // Terminal records never display as "lease held" (P1-4). The terminal write is best-effort:
436
+ // the durable intent above remains available for restart recovery if this publish fails,
437
+ // and the lease must not be reacquired after the process has finished.
438
+ await this.persist(record);
388
439
  this.cancelHandles.delete(runId);
389
440
  this.externalLaunches.delete(runId);
390
441
  this.clearExternalRecoveryTimer(runId);
391
- await this.persist(record);
392
442
  if (!record.usageRecorded) {
393
443
  record.usageRecorded = true;
394
444
  this.options.ledger?.record({
@@ -431,7 +481,7 @@ export class SubAgentRunManager {
431
481
  runId: record.runId,
432
482
  runtime: record.runtime,
433
483
  harness: record.harness,
434
- status: record.status,
484
+ status: pending.status,
435
485
  taskId: record.taskId,
436
486
  artifactDir: record.artifactDir,
437
487
  })
@@ -533,8 +583,10 @@ export class SubAgentRunManager {
533
583
  if (record.status !== "running")
534
584
  return record.status;
535
585
  const cancelHandle = this.cancelHandles.get(runId);
536
- this.cancelHandles.delete(runId);
537
586
  if (cancelHandle) {
587
+ // Keep the handle until settle() owns terminal cleanup. A worker may need an async turn to
588
+ // observe abort(); deleting it here would let a second cancel mark an active writer lost,
589
+ // release its lease, and admit another writer while the first worker can still run.
538
590
  // External: mark the reason before the handle kills the process, so whichever code
539
591
  // path settles this run reports "cancelled" instead of guessing from whatever the
540
592
  // process happened to print before it died (P1-1). This also covers
@@ -587,7 +639,9 @@ export class SubAgentRunManager {
587
639
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
588
640
  * construction (D10.3): the worker lived in the process that just disappeared, so any record
589
641
  * still `running` is settled as `lost` and the channel is woken to say so. External runs are
590
- * left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
642
+ * left for the harness-specific probe (spec 040 phase 2/3), except an adopted write run whose
643
+ * lease cannot be rebuilt: it is killed and settled as `lost` rather than allowed to continue
644
+ * without mutual exclusion.
591
645
  */
592
646
  async restore() {
593
647
  const stateDir = this.options.stateDir;
@@ -618,6 +672,33 @@ export class SubAgentRunManager {
618
672
  }
619
673
  this.runs.set(record.runId, record);
620
674
  restored++;
675
+ if (record.settlementPending && !record.settledAt) {
676
+ // A previous process reached the settlement intent after its worker/process had
677
+ // finished, but crashed before publishing the terminal record. The old lease key is
678
+ // process-local and cannot be trusted after restart; clear it before retrying so this
679
+ // recovery cannot release a different run's lease.
680
+ const pending = record.settlementPending;
681
+ record.leaseKey = undefined;
682
+ const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => "");
683
+ await this.settle(record.runId, {
684
+ status: pending.status,
685
+ failureReason: pending.failureReason,
686
+ usage: pending.usage,
687
+ usageKnown: pending.usageKnown,
688
+ costKnown: pending.costKnown,
689
+ turns: pending.turns,
690
+ toolCalls: pending.toolCalls,
691
+ durationMs: pending.durationMs,
692
+ durationEstimated: pending.durationEstimated,
693
+ outputText,
694
+ verificationVerdict: pending.verificationVerdict,
695
+ verificationStrength: pending.verificationStrength,
696
+ sessionId: pending.sessionId,
697
+ }, { announce: pending.announce }).catch((error) => {
698
+ log.logWarning(`Failed to finish pending sub-agent settlement ${record?.runId}`, errorMessage(error));
699
+ });
700
+ continue;
701
+ }
621
702
  if (record.runtime === "internal" && record.status === "running") {
622
703
  await this.settle(record.runId, {
623
704
  status: "lost",
@@ -654,13 +735,47 @@ export class SubAgentRunManager {
654
735
  }
655
736
  else {
656
737
  log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
657
- // This run does not actually hold a lease anymore — record that honestly
658
- // (spec 042 D5) so a later settle() cannot delete a different holder's lease
659
- // for the same key, and so displays stop claiming this run still holds it.
738
+ // This run cannot safely continue without its lease: it could write concurrently
739
+ // with the holder that won the restart race. Kill the adopted process only after
740
+ // confirming its persisted pid identity; a reused pid must never receive a signal.
741
+ // Either an identity mismatch or an unavailable probe is settled as lost with the
742
+ // uncertainty recorded, instead of silently degrading to an unprotected writer
743
+ // (D10.1/D10.3).
744
+ const processIdentity = record.pid ? await this.processIdentity(record) : "unknown";
745
+ let processSafetyNote;
746
+ if (processIdentity === "same") {
747
+ await killProcessGroup(record.pid).catch(() => undefined);
748
+ processSafetyNote = " The adopted process identity matched and its process group was signalled.";
749
+ }
750
+ else if (processIdentity === "different") {
751
+ processSafetyNote =
752
+ " The persisted pid identity did not match the current process; no signal was sent.";
753
+ }
754
+ else {
755
+ processSafetyNote =
756
+ " The adopted process identity could not be confirmed; no signal was sent, so its result remains unknown.";
757
+ }
758
+ // Clear the stale key first so settlement cannot delete the other run's lease.
660
759
  record.leaseKey = undefined;
661
760
  await this.persist(record).catch((error) => {
662
761
  log.logWarning(`Failed to persist cleared lease for run ${record.runId}`, errorMessage(error));
663
762
  });
763
+ await this.settle(record.runId, {
764
+ status: "lost",
765
+ failureReason: "The daemon restarted while this write delegation's workspace lease was held by another run; its result is unknown." +
766
+ processSafetyNote,
767
+ usage: record.usage,
768
+ usageKnown: record.usageKnown,
769
+ costKnown: record.costKnown,
770
+ turns: record.turns ?? 0,
771
+ toolCalls: record.toolCalls ?? 0,
772
+ durationMs: Date.now() - (record.processStartedAt ?? record.startedAt),
773
+ durationEstimated: true,
774
+ outputText: "",
775
+ }, { announce: true }).catch((error) => {
776
+ log.logWarning(`Failed to settle lease-conflicted run ${record?.runId}`, errorMessage(error));
777
+ });
778
+ continue;
664
779
  }
665
780
  }
666
781
  await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
@@ -696,6 +811,14 @@ export class SubAgentRunManager {
696
811
  const current = await readProcessStartTime(record.pid);
697
812
  return current === record.pidStartedAt;
698
813
  }
814
+ async processIdentity(record) {
815
+ if (!record.pid || !record.pidStartedAt)
816
+ return "unknown";
817
+ const current = await readProcessStartTime(record.pid);
818
+ if (!current)
819
+ return "unknown";
820
+ return current === record.pidStartedAt ? "same" : "different";
821
+ }
699
822
  /**
700
823
  * Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
701
824
  * judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
@@ -775,6 +898,8 @@ export class SubAgentRunManager {
775
898
  terminationReason: record.terminationReason,
776
899
  maxWallTimeSec,
777
900
  verifySubjectBefore: record.verifySubjectBefore,
901
+ verifyBaseCommit: record.verifyBaseCommit,
902
+ verifyBaselineUntrackedPaths: record.verifyBaselineUntrackedPaths,
778
903
  }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
779
904
  }
780
905
  /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
@@ -156,12 +156,11 @@ declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number,
156
156
  /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
157
157
  export declare function buildVerificationProtocol(taskPath: string): string;
158
158
  /**
159
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
160
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
161
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
159
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
160
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
161
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
162
162
  * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
163
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
164
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
163
+ * dispatch does, including the remaining `exec` restriction.
165
164
  */
166
165
  export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
167
166
  /**