@maheidem/pi-delegate 0.1.4 → 0.1.5

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.
package/README.md CHANGED
@@ -80,8 +80,24 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
80
80
  ignored, never dropped.
81
81
  - Cancellation is idempotent (first wins): RPC abort → SIGTERM → SIGKILL;
82
82
  every finalization reaps the child exactly once.
83
+ - Startup orphan recovery only marks a nonterminal run `crashed` /
84
+ `E_ORPHANED_RUN` when its stored pid is dead or provably not a pi process
85
+ (recycled pid). A live pi process owns its runs — a concurrent pi session
86
+ (the multi-session pattern) never clobbers a run that another live pi
87
+ process is running or finalizing; live pids with unreadable command lines
88
+ are left alone (fail-safe, never clobber on doubt). This process never kills
89
+ a pid it finds in stale metadata.
90
+ - Every terminal failure state carries a specific error payload: timeout and
91
+ cancel states reached without one (timers, user cancels) synthesize
92
+ `E_TIMEOUT_IDLE` / `E_TIMEOUT_HARD` / `E_CANCELLED` with a descriptive
93
+ message at finalization, in both the receipt and the tool text — the error
94
+ line never degrades to `unknown failure`.
83
95
  - Run-store is `0700` with `0600` receipt/transcript/stderr files; corrupt
84
- config is preserved as evidence and defaults are loaded.
96
+ config is preserved as evidence and defaults are loaded. Manual data
97
+ repairs are recorded on the receipt in a `curationNote` field (one-time
98
+ 2026-09-03 repair: receipts clobbered by pre-0.1.5 orphan recovery and
99
+ later removed by retention were reconstructed from the parent sessions'
100
+ delegate tool results — see `.planning/`, excluded from the npm tarball).
85
101
  - Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
86
102
  persisted via session custom entries; persistence failures degrade loudly
87
103
  but never silently disable the gate.
@@ -94,6 +110,7 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
94
110
  npm run typecheck # strict tsc, no emit
95
111
  npm test # unit + runner (real RPC children) + application + UI + load
96
112
  npm run test:e2e # real pi session E2E (needs a working default model)
113
+ # E2E_SCENARIOS=D,F runs a targeted subset
97
114
  ```
98
115
 
99
116
  Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/run-store.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import * as crypto from "node:crypto";
14
+ import * as childProcess from "node:child_process";
14
15
  import type {
15
16
  DelegatePaths,
16
17
  DelegateRequest,
@@ -258,22 +259,107 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
258
259
  }
259
260
 
260
261
  /**
261
- * Startup orphan recovery (§10.6): nonterminal metadata with no owned
262
- * process becomes `crashed` with E_ORPHANED_RUN. This process NEVER kills
263
- * a PID found in stale metadata. Returns the touched run IDs.
262
+ * Signal-0 liveness probe: `process.kill(pid, 0)` sends no signal. EPERM
263
+ * means the pid exists (owned by another user) — treat as alive; ESRCH and
264
+ * any other error mean the pid is gone.
265
+ */
266
+ export function isPidAlive(pid: number): boolean {
267
+ if (!Number.isInteger(pid) || pid <= 1) return false;
268
+ try {
269
+ process.kill(pid, 0);
270
+ return true;
271
+ } catch (error) {
272
+ return (error as NodeJS.ErrnoException).code === "EPERM";
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Best-effort read of another process's command line:
278
+ * - Linux: /proc/<pid>/cmdline (NUL-separated args);
279
+ * - elsewhere (macOS): `ps -o args= -p <pid>` (single line, no header).
280
+ * Returns null when the pid is dead or the cmdline cannot be read.
281
+ */
282
+ export function pidCommandLine(pid: number): string | null {
283
+ if (!isPidAlive(pid)) return null;
284
+ if (process.platform === "linux") {
285
+ try {
286
+ const text = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8")
287
+ .replace(/\0+/g, " ")
288
+ .trim();
289
+ return text.length > 0 ? text : null;
290
+ } catch {
291
+ return null;
292
+ }
293
+ }
294
+ try {
295
+ const out = childProcess.spawnSync("ps", ["-o", "args=", "-p", String(pid)], {
296
+ encoding: "utf8",
297
+ timeout: 2_000,
298
+ });
299
+ if (out.error || out.status !== 0) return null;
300
+ const text = (out.stdout ?? "").trim();
301
+ return text.length > 0 ? text : null;
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
306
+
307
+ /**
308
+ * True when the command line belongs to a Pi process (a delegate child, or
309
+ * a concurrent pi parent owning a run): any whitespace-split token whose
310
+ * path basename is exactly `pi` (covers `pi --mode rpc ...`,
311
+ * `/opt/homebrew/bin/pi ...`, `node /opt/homebrew/bin/pi ...`), or a path
312
+ * under the pi-coding-agent package (covers
313
+ * `node .../pi-coding-agent/dist/bundle/cli.js ...`).
314
+ */
315
+ export function commandLineIsPi(cmdline: string): boolean {
316
+ for (const token of cmdline.trim().split(/\s+/)) {
317
+ if (token && path.basename(token) === "pi") return true;
318
+ }
319
+ return cmdline.includes("pi-coding-agent");
320
+ }
321
+
322
+ /**
323
+ * Startup orphan recovery (§10.6): nonterminal metadata whose owned process
324
+ * is gone becomes `crashed` with E_ORPHANED_RUN. This process NEVER kills a
325
+ * PID found in stale metadata.
326
+ *
327
+ * P1: a live pi process owns its runs — concurrent multi-session pi (the
328
+ * pattern documented in AGENTS.md) must never clobber a run that another
329
+ * live pi process is actively running or finalizing. Decision table per
330
+ * nonterminal run:
331
+ * - no stored pid, or pid dead → mark crashed (unchanged);
332
+ * - pid alive, cmdline is pi → SKIP (live delegate owner);
333
+ * - pid alive, cmdline known, not pi → mark crashed (recycled PID);
334
+ * - pid alive, cmdline unreadable → SKIP (fail-safe: never clobber on doubt).
335
+ * Returns the touched run IDs.
264
336
  */
265
337
  export function markOrphanedRuns(agentDir: string): string[] {
266
338
  const touched: string[] = [];
267
339
  for (const summary of listRuns(agentDir)) {
268
340
  if (isTerminalRunState(summary.state)) continue;
269
341
  try {
270
- const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
271
- state: "crashed",
272
- errorCode: "E_ORPHANED_RUN",
273
- errorMessage: "Run store started with this run nonterminal and no owned child process.",
274
- finishedAt: current.finishedAt ?? new Date().toISOString(),
275
- }));
276
- if (next.state === "crashed") touched.push(summary.runId);
342
+ const storedPid = readRunMetadata(agentDir, summary.runId)?.pid;
343
+ if (typeof storedPid === "number" && isPidAlive(storedPid)) {
344
+ const cmdline = pidCommandLine(storedPid);
345
+ if (cmdline === null) continue; // fail-safe: alive but unreadable
346
+ if (commandLineIsPi(cmdline)) continue; // live pi owner
347
+ const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
348
+ state: "crashed",
349
+ errorCode: "E_ORPHANED_RUN",
350
+ errorMessage: `Run store started with this run nonterminal; stored pid ${storedPid} is alive but not a pi process (recycled pid), so the run has no owner.`,
351
+ finishedAt: current.finishedAt ?? new Date().toISOString(),
352
+ }));
353
+ if (next.state === "crashed") touched.push(summary.runId);
354
+ } else {
355
+ const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
356
+ state: "crashed",
357
+ errorCode: "E_ORPHANED_RUN",
358
+ errorMessage: "Run store started with this run nonterminal and no owned child process.",
359
+ finishedAt: current.finishedAt ?? new Date().toISOString(),
360
+ }));
361
+ if (next.state === "crashed") touched.push(summary.runId);
362
+ }
277
363
  } catch {
278
364
  // skip
279
365
  }
package/runner.ts CHANGED
@@ -25,6 +25,7 @@ import type {
25
25
  import { EMPTY_USAGE } from "./types.ts";
26
26
  import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.ts";
27
27
  import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
28
+ import { formatDuration } from "./config.ts";
28
29
 
29
30
  export interface RunnerConfig {
30
31
  maxResultBytes: number;
@@ -603,7 +604,13 @@ export class DelegateRunner {
603
604
  this.finalizing = true;
604
605
  const finishedAt = new Date().toISOString();
605
606
  const durationMs = this.startedAtMs ? Date.now() - this.startedAtMs : 0;
606
- this.finalError = error ?? this.finalError;
607
+ // P3: timeout/cancel terminal states are reached without an explicit
608
+ // error (timers and user cancels funnel through finish() bare).
609
+ // Synthesize a specific payload so the tool text never degrades to
610
+ // "unknown failure" — the header shows the state; the error line must
611
+ // agree. Flows into both the metadata and the reported outcome.
612
+ const effectiveError = error ?? this.synthesizedTerminalError(state);
613
+ this.finalError = effectiveError ?? this.finalError;
607
614
  const usage = { ...(extra?.usage ?? this.usage), turns: this.turns };
608
615
  const metadataPatch: Record<string, unknown> = {
609
616
  state,
@@ -617,9 +624,9 @@ export class DelegateRunner {
617
624
  metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
618
625
  }
619
626
  if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
620
- if (error) {
621
- metadataPatch.errorCode = error.code;
622
- metadataPatch.errorMessage = error.message;
627
+ if (effectiveError) {
628
+ metadataPatch.errorCode = effectiveError.code;
629
+ metadataPatch.errorMessage = effectiveError.message;
623
630
  }
624
631
  if (this.diagnosticNotes.length > 0) {
625
632
  metadataPatch.errorMessage = metadataPatch.errorMessage
@@ -643,12 +650,39 @@ export class DelegateRunner {
643
650
  this.reapChild();
644
651
  this.cleanup();
645
652
 
646
- const outcome = this.outcome(state, extra, error);
653
+ const outcome = this.outcome(state, extra, effectiveError);
647
654
  const resolver = this.settledResolver;
648
655
  this.settledResolver = null;
649
656
  resolver?.(outcome);
650
657
  }
651
658
 
659
+ /**
660
+ * P3: specific error payloads for the terminal states reached without an
661
+ * explicit error. `succeeded`/`failed` already carry their error at the
662
+ * call site (or legitimately have none) and are unaffected.
663
+ */
664
+ private synthesizedTerminalError(state: RunTerminalState): DelegateError | undefined {
665
+ switch (state) {
666
+ case "timed_out_idle":
667
+ return {
668
+ code: "E_TIMEOUT_IDLE",
669
+ message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
670
+ };
671
+ case "timed_out_hard":
672
+ return {
673
+ code: "E_TIMEOUT_HARD",
674
+ message: `hard timeout of ${formatDuration(this.cfg.hardTimeoutMs)} reached (wall-clock cap)`,
675
+ };
676
+ case "cancelled":
677
+ return {
678
+ code: "E_CANCELLED",
679
+ message: this.cancelledByUser ? "cancelled by user" : "aborted (parent session abort)",
680
+ };
681
+ default:
682
+ return undefined;
683
+ }
684
+ }
685
+
652
686
  private outcome(
653
687
  state: RunTerminalState,
654
688
  extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
package/types.ts CHANGED
@@ -195,6 +195,8 @@ export interface RunMetadataV1 {
195
195
  finalHandoff?: string;
196
196
  transcriptPath: string;
197
197
  stderrPath: string;
198
+ /** Present only on manually curated receipts (one-time data repair). */
199
+ curationNote?: string;
198
200
  }
199
201
 
200
202
  export interface TranscriptRecordV1 {