@vicary/pi-subagents 0.87.0 → 0.88.1

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 (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-75LVXBSA.js → chunk-2HKPEANZ.js} +114 -49
  6. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  7. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  8. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  9. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  10. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-Z4TR7MK6.js → chunk-AZPP3G4N.js} +14 -5
  13. package/bundle/{chunk-PUSTU4Q7.js → chunk-BKISQ5CJ.js} +130 -49
  14. package/bundle/{chunk-NMYBVCGP.js → chunk-CGWNA6EJ.js} +75 -44
  15. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  18. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  19. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  20. package/bundle/{chunk-O7A26O6B.js → chunk-IYT7X46U.js} +6 -4
  21. package/bundle/{chunk-NJTSXIMG.js → chunk-JQTHG2ID.js} +12 -12
  22. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  23. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  24. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  25. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  26. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  27. package/bundle/{chunk-HTI7DD5D.js → chunk-V7SZMS6W.js} +2 -2
  28. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  29. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  30. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  31. package/bundle/chunk-YDZ7BZD5.js +523 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +4 -2
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +3 -3
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +9 -0
  50. package/src/extension/config.js +13 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -2,8 +2,10 @@ import {
2
2
  agentDefinitionDigest
3
3
  } from "./chunk-7F6RKT6W.js";
4
4
  import {
5
- PROJECT_SUBAGENTS_RELATIVE_DIR
6
- } from "./chunk-XSDYTXHF.js";
5
+ PROJECT_SUBAGENTS_RELATIVE_DIR,
6
+ canonicalSessionId,
7
+ inspectSessionLease
8
+ } from "./chunk-YDZ7BZD5.js";
7
9
  import {
8
10
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
9
11
  DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
@@ -25,7 +27,7 @@ import {
25
27
  withFileLease,
26
28
  writeAtomicJson,
27
29
  writePrivateAtomicJson
28
- } from "./chunk-C3KWLXDH.js";
30
+ } from "./chunk-4MVDMA5C.js";
29
31
  import {
30
32
  DIRS,
31
33
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -467,53 +469,10 @@ function writeProcessTerminalCandidate(asyncDir, candidate) {
467
469
  }
468
470
 
469
471
  // src/runs/background/process-terminal.ts
470
- import * as fs5 from "node:fs";
471
- import * as path6 from "node:path";
472
-
473
- // src/runs/shared/session-lease.ts
474
- import { createHash as createHash2, randomUUID } from "node:crypto";
475
472
  import * as fs4 from "node:fs";
476
473
  import * as path5 from "node:path";
477
- var SESSION_LEASES_DIR = path5.join(TEMP_ROOT_DIR, "session-leases");
478
- function canonicalSessionFilePath(sessionFile) {
479
- return fs4.realpathSync.native(path5.resolve(sessionFile));
480
- }
481
- function canonicalSessionId(sessionFile) {
482
- const canonical = canonicalSessionFilePath(sessionFile);
483
- const key = process.platform === "win32" ? canonical.toLowerCase() : canonical;
484
- return createHash2("sha256").update(key).digest("hex");
485
- }
486
- function inspectSessionLease(sessionFile, rootDir = SESSION_LEASES_DIR) {
487
- const canonicalSessionFile = canonicalSessionFilePath(sessionFile);
488
- const canonicalSessionIdValue = canonicalSessionId(canonicalSessionFile);
489
- const leaseDir = path5.join(rootDir, canonicalSessionIdValue);
490
- if (!fs4.existsSync(leaseDir)) return { state: "free", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
491
- const owner = readLeaseOwner(leaseDir);
492
- return owner ? { state: "owned", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue, owner } : { state: "unreadable", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
493
- }
494
- function parseOwner(value) {
495
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
496
- const owner = value;
497
- if (owner.version !== 1 || typeof owner.token !== "string" || typeof owner.canonicalSessionFile !== "string" || typeof owner.runId !== "string" || typeof owner.sourceRunId !== "string" || typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== "string" || owner.writerState !== "none" && owner.writerState !== "spawning" && owner.writerState !== "running" || typeof owner.acquiredAt !== "string" || typeof owner.acquiredAtMs !== "number" || typeof owner.updatedAtMs !== "number") return void 0;
498
- if (owner.parentSessionId !== void 0 && typeof owner.parentSessionId !== "string") return void 0;
499
- if (owner.processStartIdentity !== void 0 && typeof owner.processStartIdentity !== "string") return void 0;
500
- if (owner.writerPid !== void 0 && (typeof owner.writerPid !== "number" || !Number.isInteger(owner.writerPid) || owner.writerPid <= 0)) return void 0;
501
- if (owner.writerProcessStartIdentity !== void 0 && typeof owner.writerProcessStartIdentity !== "string") return void 0;
502
- if (owner.writerState === "running" && owner.writerPid === void 0) return void 0;
503
- if (owner.writerState !== "running" && (owner.writerPid !== void 0 || owner.writerProcessStartIdentity !== void 0)) return void 0;
504
- return owner;
505
- }
506
- function readLeaseOwner(leaseDir) {
507
- try {
508
- return parseOwner(JSON.parse(fs4.readFileSync(path5.join(leaseDir, "owner.json"), "utf-8")));
509
- } catch {
510
- return void 0;
511
- }
512
- }
513
-
514
- // src/runs/background/process-terminal.ts
515
474
  function processTerminalPath(asyncDir) {
516
- return path6.join(asyncDir, "process-terminal.json");
475
+ return path5.join(asyncDir, "process-terminal.json");
517
476
  }
518
477
  function errorMessage(error) {
519
478
  return error instanceof Error ? error.message : String(error);
@@ -538,7 +497,7 @@ function unknownProof(runId, runnerProcessInstanceId, reason, diagnostic) {
538
497
  function resumeDisposition(state, sessionFile) {
539
498
  if (state === "stopped") return "non-resumable";
540
499
  if (state !== "complete" && state !== "completed" && state !== "failed" && state !== "paused") return "unavailable";
541
- return sessionFile && fs5.existsSync(sessionFile) ? "resumable" : "unavailable";
500
+ return sessionFile && fs4.existsSync(sessionFile) ? "resumable" : "unavailable";
542
501
  }
543
502
  function sessionProjection(candidate, lease) {
544
503
  if (!candidate.sessionFile || lease.state !== "free") return void 0;
@@ -579,12 +538,12 @@ function sanitizeProcessTerminal(value, fallback, label = "status") {
579
538
  }
580
539
  function readProcessTerminal(asyncDir, fallback) {
581
540
  try {
582
- const raw = JSON.parse(fs5.readFileSync(processTerminalPath(asyncDir), "utf-8"));
541
+ const raw = JSON.parse(fs4.readFileSync(processTerminalPath(asyncDir), "utf-8"));
583
542
  validateProof(raw, asyncDir, fallback);
584
543
  return raw;
585
544
  } catch (error) {
586
545
  if (error.code === "ENOENT") return void 0;
587
- return unknownProof(fallback?.runId ?? path6.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
546
+ return unknownProof(fallback?.runId ?? path5.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
588
547
  }
589
548
  }
590
549
  function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispositionValue) {
@@ -604,9 +563,9 @@ function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispo
604
563
  return { ...base, state };
605
564
  }
606
565
  function overlayStatus(asyncDir, proof, candidate) {
607
- const statusPath = path6.join(asyncDir, "status.json");
566
+ const statusPath = path5.join(asyncDir, "status.json");
608
567
  try {
609
- const status = JSON.parse(fs5.readFileSync(statusPath, "utf-8"));
568
+ const status = JSON.parse(fs4.readFileSync(statusPath, "utf-8"));
610
569
  status.processTerminal = proof;
611
570
  if (status.steps) {
612
571
  for (const [index, step] of status.steps.entries()) {
@@ -622,7 +581,7 @@ function overlayStatus(asyncDir, proof, candidate) {
622
581
  }
623
582
  function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
624
583
  const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
625
- if (existing && fs5.existsSync(processTerminalPath(asyncDir))) {
584
+ if (existing && fs4.existsSync(processTerminalPath(asyncDir))) {
626
585
  if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
627
586
  if (existing.state === "unknown") {
628
587
  if (existing.instances?.length || existing.reason === "proof-write-failed") return existing;
@@ -646,7 +605,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
646
605
  const allWriters = Object.values(candidate.writers).flat();
647
606
  const status = (() => {
648
607
  try {
649
- return JSON.parse(fs5.readFileSync(path6.join(asyncDir, "status.json"), "utf-8"));
608
+ return JSON.parse(fs4.readFileSync(path5.join(asyncDir, "status.json"), "utf-8"));
650
609
  } catch {
651
610
  return void 0;
652
611
  }
@@ -691,7 +650,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
691
650
  durable = true;
692
651
  if (proof.state === "observed") releaseActiveRunIndex(asyncDir);
693
652
  overlayStatus(asyncDir, proof, candidateForOverlay);
694
- fs5.appendFileSync(path6.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.run.process_terminal", lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, ts: Date.now(), runId, processTerminal: proof })}
653
+ fs4.appendFileSync(path5.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.run.process_terminal", lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, ts: Date.now(), runId, processTerminal: proof })}
695
654
  `, "utf-8");
696
655
  } catch {
697
656
  }
@@ -699,10 +658,10 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
699
658
  }
700
659
 
701
660
  // src/runs/shared/nested-events.ts
702
- import { randomUUID as randomUUID2 } from "node:crypto";
703
- import * as fs6 from "node:fs";
704
- import * as path7 from "node:path";
705
- var NESTED_EVENTS_DIR = path7.join(TEMP_ROOT_DIR, "nested-subagent-events");
661
+ import { randomUUID } from "node:crypto";
662
+ import * as fs5 from "node:fs";
663
+ import * as path6 from "node:path";
664
+ var NESTED_EVENTS_DIR = path6.join(TEMP_ROOT_DIR, "nested-subagent-events");
706
665
  var ROUTE_FILE = "route.json";
707
666
  var REGISTRY_FILE = "registry.json";
708
667
  var ROUTE_INDEX_DIR = ".route-index";
@@ -720,48 +679,48 @@ function assertSafeId(label, value) {
720
679
  assertSafeNestedId(label, value);
721
680
  }
722
681
  function containedPath(base, candidate) {
723
- const resolvedBase = path7.resolve(base);
724
- const resolvedCandidate = path7.resolve(candidate);
725
- return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path7.sep}`);
682
+ const resolvedBase = path6.resolve(base);
683
+ const resolvedCandidate = path6.resolve(candidate);
684
+ return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path6.sep}`);
726
685
  }
727
686
  function commonRouteRoot(route) {
728
- return path7.dirname(path7.resolve(route.eventSink));
687
+ return path6.dirname(path6.resolve(route.eventSink));
729
688
  }
730
689
  function routeIndexRoot() {
731
- return path7.join(NESTED_EVENTS_DIR, ROUTE_INDEX_DIR, "roots");
690
+ return path6.join(NESTED_EVENTS_DIR, ROUTE_INDEX_DIR, "roots");
732
691
  }
733
692
  function routeIndexDir(rootRunId) {
734
- return path7.join(routeIndexRoot(), encodeURIComponent(rootRunId));
693
+ return path6.join(routeIndexRoot(), encodeURIComponent(rootRunId));
735
694
  }
736
695
  function routeIndexPath(rootRunId, capabilityToken) {
737
- return path7.join(routeIndexDir(rootRunId), `${encodeURIComponent(capabilityToken)}.json`);
696
+ return path6.join(routeIndexDir(rootRunId), `${encodeURIComponent(capabilityToken)}.json`);
738
697
  }
739
698
  function validateRouteShape(route) {
740
699
  assertSafeId("rootRunId", route.rootRunId);
741
700
  assertSafeId("capabilityToken", route.capabilityToken);
742
701
  if (!containedPath(NESTED_EVENTS_DIR, route.eventSink)) throw new Error("Nested event sink is outside the subagent nested event root.");
743
702
  if (!containedPath(NESTED_EVENTS_DIR, route.controlInbox)) throw new Error("Nested control inbox is outside the subagent nested event root.");
744
- if (commonRouteRoot(route) !== path7.dirname(path7.resolve(route.controlInbox))) throw new Error("Nested event sink and control inbox must share one route root.");
703
+ if (commonRouteRoot(route) !== path6.dirname(path6.resolve(route.controlInbox))) throw new Error("Nested event sink and control inbox must share one route root.");
745
704
  }
746
705
  function createNestedRoute(rootRunId) {
747
706
  assertSafeId("rootRunId", rootRunId);
748
- const capabilityToken = randomUUID2();
749
- const routeRoot = path7.join(NESTED_EVENTS_DIR, `${rootRunId}-${capabilityToken}`);
750
- const eventSink = path7.join(routeRoot, "events");
751
- const controlInbox = path7.join(routeRoot, "controls");
752
- fs6.mkdirSync(eventSink, { recursive: true, mode: 448 });
753
- fs6.mkdirSync(controlInbox, { recursive: true, mode: 448 });
707
+ const capabilityToken = randomUUID();
708
+ const routeRoot = path6.join(NESTED_EVENTS_DIR, `${rootRunId}-${capabilityToken}`);
709
+ const eventSink = path6.join(routeRoot, "events");
710
+ const controlInbox = path6.join(routeRoot, "controls");
711
+ fs5.mkdirSync(eventSink, { recursive: true, mode: 448 });
712
+ fs5.mkdirSync(controlInbox, { recursive: true, mode: 448 });
754
713
  const createdAt = Date.now();
755
- fs6.mkdirSync(routeIndexDir(rootRunId), { recursive: true, mode: 448 });
756
- writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot: path7.basename(routeRoot), createdAt });
757
- writeAtomicJson(path7.join(routeRoot, ROUTE_FILE), { rootRunId, capabilityToken, createdAt });
714
+ fs5.mkdirSync(routeIndexDir(rootRunId), { recursive: true, mode: 448 });
715
+ writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot: path6.basename(routeRoot), createdAt });
716
+ writeAtomicJson(path6.join(routeRoot, ROUTE_FILE), { rootRunId, capabilityToken, createdAt });
758
717
  return { rootRunId, eventSink, controlInbox, capabilityToken };
759
718
  }
760
719
  function resolveNestedRoute(route) {
761
720
  const { rootRunId, capabilityToken } = route;
762
721
  validateRouteShape(route);
763
- const routeFile = path7.join(commonRouteRoot(route), ROUTE_FILE);
764
- const metadata = JSON.parse(fs6.readFileSync(routeFile, "utf-8"));
722
+ const routeFile = path6.join(commonRouteRoot(route), ROUTE_FILE);
723
+ const metadata = JSON.parse(fs5.readFileSync(routeFile, "utf-8"));
765
724
  if (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {
766
725
  throw new Error("Nested event route metadata does not match the provided root id and capability token.");
767
726
  }
@@ -794,10 +753,10 @@ function nestedRunNotActiveMessage(runId) {
794
753
  }
795
754
  function resolveNestedAsyncDir(rootRunId, run) {
796
755
  if (!run.asyncDir) return void 0;
797
- const resolved2 = path7.resolve(run.asyncDir);
798
- const nestedRoot = path7.resolve(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId, run.id);
799
- const relative4 = path7.relative(nestedRoot, resolved2);
800
- return resolved2 === nestedRoot || !relative4.startsWith("..") && !path7.isAbsolute(relative4) ? resolved2 : void 0;
756
+ const resolved2 = path6.resolve(run.asyncDir);
757
+ const nestedRoot = path6.resolve(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId, run.id);
758
+ const relative4 = path6.relative(nestedRoot, resolved2);
759
+ return resolved2 === nestedRoot || !relative4.startsWith("..") && !path6.isAbsolute(relative4) ? resolved2 : void 0;
801
760
  }
802
761
  function clampNumber(value) {
803
762
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -1108,24 +1067,24 @@ function applyNestedEvent(registry, event) {
1108
1067
  };
1109
1068
  }
1110
1069
  function registryPath(route) {
1111
- return path7.join(commonRouteRoot(route), REGISTRY_FILE);
1070
+ return path6.join(commonRouteRoot(route), REGISTRY_FILE);
1112
1071
  }
1113
1072
  function routeFromIndexEntry(rootRunId, filePath) {
1114
1073
  try {
1115
- const metadata = JSON.parse(fs6.readFileSync(filePath, "utf-8"));
1074
+ const metadata = JSON.parse(fs5.readFileSync(filePath, "utf-8"));
1116
1075
  if (metadata.rootRunId !== rootRunId || typeof metadata.capabilityToken !== "string" || typeof metadata.routeRoot !== "string") return void 0;
1117
- const routeRoot = path7.join(NESTED_EVENTS_DIR, path7.basename(metadata.routeRoot));
1076
+ const routeRoot = path6.join(NESTED_EVENTS_DIR, path6.basename(metadata.routeRoot));
1118
1077
  const route = {
1119
1078
  rootRunId,
1120
- eventSink: path7.join(routeRoot, "events"),
1121
- controlInbox: path7.join(routeRoot, "controls"),
1079
+ eventSink: path6.join(routeRoot, "events"),
1080
+ controlInbox: path6.join(routeRoot, "controls"),
1122
1081
  capabilityToken: metadata.capabilityToken
1123
1082
  };
1124
1083
  validateRouteShape(route);
1125
- if (!fs6.statSync(route.eventSink).isDirectory() || !fs6.statSync(route.controlInbox).isDirectory()) return void 0;
1126
- const routeFilePath = path7.join(routeRoot, ROUTE_FILE);
1084
+ if (!fs5.statSync(route.eventSink).isDirectory() || !fs5.statSync(route.controlInbox).isDirectory()) return void 0;
1085
+ const routeFilePath = path6.join(routeRoot, ROUTE_FILE);
1127
1086
  try {
1128
- const routeFile = JSON.parse(fs6.readFileSync(routeFilePath, "utf-8"));
1087
+ const routeFile = JSON.parse(fs5.readFileSync(routeFilePath, "utf-8"));
1129
1088
  if (routeFile.rootRunId !== rootRunId || routeFile.capabilityToken !== metadata.capabilityToken) return void 0;
1130
1089
  } catch (error) {
1131
1090
  if (error.code !== "ENOENT") return void 0;
@@ -1143,13 +1102,13 @@ function findNestedRouteForRootId(rootRunId) {
1143
1102
  assertSafeId("rootRunId", rootRunId);
1144
1103
  let entries;
1145
1104
  try {
1146
- entries = fs6.readdirSync(routeIndexDir(rootRunId));
1105
+ entries = fs5.readdirSync(routeIndexDir(rootRunId));
1147
1106
  } catch (error) {
1148
1107
  if (error.code === "ENOENT") return void 0;
1149
1108
  throw error;
1150
1109
  }
1151
1110
  for (const entry of entries) {
1152
- const route = routeFromIndexEntry(rootRunId, path7.join(routeIndexDir(rootRunId), entry));
1111
+ const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexDir(rootRunId), entry));
1153
1112
  if (route) return route;
1154
1113
  }
1155
1114
  return void 0;
@@ -1195,7 +1154,7 @@ function collectScopedNestedRuns(children, scope, output = []) {
1195
1154
  function listNestedRoutes() {
1196
1155
  let rootEntries;
1197
1156
  try {
1198
- rootEntries = fs6.readdirSync(routeIndexRoot());
1157
+ rootEntries = fs5.readdirSync(routeIndexRoot());
1199
1158
  } catch (error) {
1200
1159
  if (error.code === "ENOENT") return [];
1201
1160
  throw error;
@@ -1209,8 +1168,8 @@ function listNestedRoutes() {
1209
1168
  continue;
1210
1169
  }
1211
1170
  try {
1212
- for (const entry of fs6.readdirSync(path7.join(routeIndexRoot(), rootEntry))) {
1213
- const route = routeFromIndexEntry(rootRunId, path7.join(routeIndexRoot(), rootEntry, entry));
1171
+ for (const entry of fs5.readdirSync(path6.join(routeIndexRoot(), rootEntry))) {
1172
+ const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexRoot(), rootEntry, entry));
1214
1173
  if (route) routes.push(route);
1215
1174
  }
1216
1175
  } catch {
@@ -1237,7 +1196,7 @@ function findNestedRunMatchesById(id, options = {}) {
1237
1196
  function readNestedRegistry(route) {
1238
1197
  validateRouteShape(route);
1239
1198
  try {
1240
- const parsed = JSON.parse(fs6.readFileSync(registryPath(route), "utf-8"));
1199
+ const parsed = JSON.parse(fs5.readFileSync(registryPath(route), "utf-8"));
1241
1200
  return {
1242
1201
  rootRunId: route.rootRunId,
1243
1202
  updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : 0,
@@ -1256,19 +1215,19 @@ function projectNestedEvents(route) {
1256
1215
  let changed = false;
1257
1216
  let entries = [];
1258
1217
  try {
1259
- entries = fs6.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl")).sort();
1218
+ entries = fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl")).sort();
1260
1219
  } catch (error) {
1261
1220
  if (error.code !== "ENOENT") throw error;
1262
1221
  }
1263
1222
  for (const entry of entries) {
1264
1223
  if (seen.has(entry)) continue;
1265
- const eventPath = path7.join(route.eventSink, entry);
1224
+ const eventPath = path6.join(route.eventSink, entry);
1266
1225
  if (!containedPath(route.eventSink, eventPath)) continue;
1267
1226
  let content;
1268
1227
  try {
1269
- const stat = fs6.statSync(eventPath);
1228
+ const stat = fs5.statSync(eventPath);
1270
1229
  if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
1271
- content = fs6.readFileSync(eventPath, "utf-8");
1230
+ content = fs5.readFileSync(eventPath, "utf-8");
1272
1231
  } catch {
1273
1232
  continue;
1274
1233
  }
@@ -1288,15 +1247,15 @@ function projectNestedEvents(route) {
1288
1247
  registry = { ...registry, processedEvents: retainedEvents };
1289
1248
  writeAtomicJson(registryPath(route), registry);
1290
1249
  for (const entry of evictedEvents) {
1291
- const eventPath = path7.join(route.eventSink, entry);
1250
+ const eventPath = path6.join(route.eventSink, entry);
1292
1251
  if (!containedPath(route.eventSink, eventPath)) continue;
1293
1252
  try {
1294
- const stat = fs6.statSync(eventPath);
1253
+ const stat = fs5.statSync(eventPath);
1295
1254
  if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
1296
- const content = fs6.readFileSync(eventPath, "utf-8");
1255
+ const content = fs5.readFileSync(eventPath, "utf-8");
1297
1256
  const hasStatusRecord = parseNestedEventRecords(content, route).length > 0;
1298
1257
  const hasControlResult = content.split("\n").some((line) => line.trim() && parseControlResult(line.trim(), route));
1299
- if (hasStatusRecord && !hasControlResult) fs6.unlinkSync(eventPath);
1258
+ if (hasStatusRecord && !hasControlResult) fs5.unlinkSync(eventPath);
1300
1259
  } catch {
1301
1260
  }
1302
1261
  }
@@ -1307,12 +1266,12 @@ function writeRouteRecord(dir, ts, payload) {
1307
1266
  const content = `${JSON.stringify(payload)}
1308
1267
  `;
1309
1268
  if (Buffer.byteLength(content, "utf-8") > MAX_EVENT_BYTES) throw new Error("Nested route record exceeds the maximum size.");
1310
- fs6.mkdirSync(dir, { recursive: true, mode: 448 });
1311
- const name = `${String(ts).padStart(13, "0")}-${randomUUID2()}.json`;
1312
- const tmp = path7.join(dir, `.${name}.tmp`);
1313
- const finalPath = path7.join(dir, name);
1314
- fs6.writeFileSync(tmp, content, { mode: 384 });
1315
- fs6.renameSync(tmp, finalPath);
1269
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1270
+ const name = `${String(ts).padStart(13, "0")}-${randomUUID()}.json`;
1271
+ const tmp = path6.join(dir, `.${name}.tmp`);
1272
+ const finalPath = path6.join(dir, name);
1273
+ fs5.writeFileSync(tmp, content, { mode: 384 });
1274
+ fs5.renameSync(tmp, finalPath);
1316
1275
  return finalPath;
1317
1276
  }
1318
1277
  function writeNestedEvent(route, event) {
@@ -1397,18 +1356,18 @@ function readNestedControlRequests(route) {
1397
1356
  validateRouteShape(route);
1398
1357
  let entries = [];
1399
1358
  try {
1400
- entries = fs6.readdirSync(route.controlInbox).filter((entry) => entry.endsWith(".json")).sort();
1359
+ entries = fs5.readdirSync(route.controlInbox).filter((entry) => entry.endsWith(".json")).sort();
1401
1360
  } catch (error) {
1402
1361
  if (error.code !== "ENOENT") throw error;
1403
1362
  }
1404
1363
  const requests = [];
1405
1364
  for (const entry of entries) {
1406
- const filePath = path7.join(route.controlInbox, entry);
1365
+ const filePath = path6.join(route.controlInbox, entry);
1407
1366
  if (!containedPath(route.controlInbox, filePath)) continue;
1408
1367
  try {
1409
- const stat = fs6.statSync(filePath);
1368
+ const stat = fs5.statSync(filePath);
1410
1369
  if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
1411
- const request = parseControlRequest(fs6.readFileSync(filePath, "utf-8"), route);
1370
+ const request = parseControlRequest(fs5.readFileSync(filePath, "utf-8"), route);
1412
1371
  if (request) requests.push({ ...request, filePath });
1413
1372
  } catch {
1414
1373
  continue;
@@ -1433,9 +1392,9 @@ function writeNestedControlResult(route, result) {
1433
1392
  function readControlResultsFromFile(route, eventPath) {
1434
1393
  if (!containedPath(route.eventSink, eventPath)) return [];
1435
1394
  try {
1436
- const stat = fs6.statSync(eventPath);
1395
+ const stat = fs5.statSync(eventPath);
1437
1396
  if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) return [];
1438
- const content = fs6.readFileSync(eventPath, "utf-8");
1397
+ const content = fs5.readFileSync(eventPath, "utf-8");
1439
1398
  const lines = content.includes("\n") ? content.split("\n").filter((line) => line.trim()) : [content];
1440
1399
  return lines.map((line) => parseControlResult(line, route)).filter((result) => Boolean(result));
1441
1400
  } catch {
@@ -1445,7 +1404,7 @@ function readControlResultsFromFile(route, eventPath) {
1445
1404
  function listNestedEventFiles(route) {
1446
1405
  validateRouteShape(route);
1447
1406
  try {
1448
- return fs6.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl"));
1407
+ return fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl"));
1449
1408
  } catch (error) {
1450
1409
  if (error.code === "ENOENT") return [];
1451
1410
  throw error;
@@ -1457,7 +1416,7 @@ function snapshotNestedEventFiles(route) {
1457
1416
  function findNestedControlResult(route, requestId, targetRunId, ignoredFiles) {
1458
1417
  const entries = listNestedEventFiles(route).filter((entry) => !ignoredFiles.has(entry)).sort().reverse();
1459
1418
  for (const entry of entries) {
1460
- const result = readControlResultsFromFile(route, path7.join(route.eventSink, entry)).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === targetRunId);
1419
+ const result = readControlResultsFromFile(route, path6.join(route.eventSink, entry)).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === targetRunId);
1461
1420
  if (result) return result;
1462
1421
  }
1463
1422
  return void 0;
@@ -1572,13 +1531,13 @@ function nestedSummaryFromAsyncStatus(status, asyncDir, fallback) {
1572
1531
  function nestedRunScope(rootRunId) {
1573
1532
  assertSafeId("rootRunId", rootRunId);
1574
1533
  return {
1575
- asyncDirRoot: path7.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
1576
- resultsDir: path7.join(DIRS.results, "nested", rootRunId)
1534
+ asyncDirRoot: path6.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
1535
+ resultsDir: path6.join(DIRS.results, "nested", rootRunId)
1577
1536
  };
1578
1537
  }
1579
1538
  function nestedResultsPath(rootRunId, id) {
1580
1539
  assertSafeId("id", id);
1581
- return path7.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
1540
+ return path6.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
1582
1541
  }
1583
1542
 
1584
1543
  // src/runs/shared/host-step-status.ts
@@ -1801,9 +1760,9 @@ function checkRequiredRunnerLauncher(agent, launcherName, required) {
1801
1760
 
1802
1761
  // src/workflows/host-command.ts
1803
1762
  import { spawn } from "node:child_process";
1804
- import { randomUUID as randomUUID3 } from "node:crypto";
1805
- import * as fs7 from "node:fs";
1806
- import * as path8 from "node:path";
1763
+ import { randomUUID as randomUUID2 } from "node:crypto";
1764
+ import * as fs6 from "node:fs";
1765
+ import * as path7 from "node:path";
1807
1766
  var MAX_COMMAND_BYTES = 16 * 1024;
1808
1767
  var MAX_OUTPUT_PATH_BYTES = 240;
1809
1768
  var MAX_CAPTURE_BYTES = 1024 * 1024;
@@ -1835,7 +1794,7 @@ function normalizeWorkflowHostCommandParams(value, label = "runs.host params") {
1835
1794
  if (params.output !== void 0) {
1836
1795
  if (typeof params.output !== "string" || !params.output.trim()) throw new Error(`${label}.output must be a non-empty relative path.`);
1837
1796
  output = params.output.trim();
1838
- if (path8.isAbsolute(output) || output.split(/[\\/]/).includes("..") || /[\u0000-\u001f\u007f]/.test(output) || byteLength(output) > MAX_OUTPUT_PATH_BYTES) throw new Error(`${label}.output must be a bounded relative path without traversal or control characters.`);
1797
+ if (path7.isAbsolute(output) || output.split(/[\\/]/).includes("..") || /[\u0000-\u001f\u007f]/.test(output) || byteLength(output) > MAX_OUTPUT_PATH_BYTES) throw new Error(`${label}.output must be a bounded relative path without traversal or control characters.`);
1839
1798
  }
1840
1799
  if (params.role !== void 0 && params.role !== "ci" && params.role !== "gate") throw new Error(`${label}.role must be 'ci' or 'gate'.`);
1841
1800
  let provider;
@@ -1860,19 +1819,19 @@ function resolveWorkflowHostOutputClaimPath(outputPath) {
1860
1819
  return resolveSingleOutputClaimPath(outputPath);
1861
1820
  }
1862
1821
  function assertSafeExplicitOutput(cwd, outputPath, key) {
1863
- const root = fs7.realpathSync(cwd);
1864
- const outputParent = path8.dirname(outputPath);
1822
+ const root = fs6.realpathSync(cwd);
1823
+ const outputParent = path7.dirname(outputPath);
1865
1824
  let existingParent = outputParent;
1866
- while (!fs7.existsSync(existingParent)) existingParent = path8.dirname(existingParent);
1867
- const existingParentReal = fs7.realpathSync(existingParent);
1868
- const existingRelative = path8.relative(root, existingParentReal);
1869
- if (existingRelative === ".." || existingRelative.startsWith(`..${path8.sep}`) || path8.isAbsolute(existingRelative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
1870
- fs7.mkdirSync(outputParent, { recursive: true });
1871
- const parent = fs7.realpathSync(outputParent);
1872
- const relative4 = path8.relative(root, parent);
1873
- if (relative4 === ".." || relative4.startsWith(`..${path8.sep}`) || path8.isAbsolute(relative4)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
1825
+ while (!fs6.existsSync(existingParent)) existingParent = path7.dirname(existingParent);
1826
+ const existingParentReal = fs6.realpathSync(existingParent);
1827
+ const existingRelative = path7.relative(root, existingParentReal);
1828
+ if (existingRelative === ".." || existingRelative.startsWith(`..${path7.sep}`) || path7.isAbsolute(existingRelative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
1829
+ fs6.mkdirSync(outputParent, { recursive: true });
1830
+ const parent = fs6.realpathSync(outputParent);
1831
+ const relative4 = path7.relative(root, parent);
1832
+ if (relative4 === ".." || relative4.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative4)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
1874
1833
  try {
1875
- const stat = fs7.lstatSync(outputPath);
1834
+ const stat = fs6.lstatSync(outputPath);
1876
1835
  if (!stat.isFile() || stat.nlink > 1) throw new Error(`runs.host('${key}') output must be a regular, non-linked file path.`);
1877
1836
  } catch (error) {
1878
1837
  if (error.code !== "ENOENT") throw error;
@@ -1880,24 +1839,24 @@ function assertSafeExplicitOutput(cwd, outputPath, key) {
1880
1839
  return parent;
1881
1840
  }
1882
1841
  function writeExplicitOutput(outputParent, outputPath, capture, key) {
1883
- const destination = path8.join(outputParent, path8.basename(outputPath));
1884
- const temporaryPath = path8.join(outputParent, `.pi-host-output-${process.pid}-${randomUUID3()}.tmp`);
1842
+ const destination = path7.join(outputParent, path7.basename(outputPath));
1843
+ const temporaryPath = path7.join(outputParent, `.pi-host-output-${process.pid}-${randomUUID2()}.tmp`);
1885
1844
  let descriptor;
1886
1845
  try {
1887
- descriptor = fs7.openSync(temporaryPath, fs7.constants.O_WRONLY | fs7.constants.O_CREAT | fs7.constants.O_EXCL, 384);
1888
- fs7.writeFileSync(descriptor, capture, { encoding: "utf8" });
1889
- fs7.closeSync(descriptor);
1846
+ descriptor = fs6.openSync(temporaryPath, fs6.constants.O_WRONLY | fs6.constants.O_CREAT | fs6.constants.O_EXCL, 384);
1847
+ fs6.writeFileSync(descriptor, capture, { encoding: "utf8" });
1848
+ fs6.closeSync(descriptor);
1890
1849
  descriptor = void 0;
1891
- fs7.chmodSync(temporaryPath, 384);
1892
- runFileSystemOperationWithRetry(() => fs7.renameSync(temporaryPath, destination), {
1850
+ fs6.chmodSync(temporaryPath, 384);
1851
+ runFileSystemOperationWithRetry(() => fs6.renameSync(temporaryPath, destination), {
1893
1852
  retryDelaysMs: process.platform === "win32" ? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS : []
1894
1853
  });
1895
1854
  } catch (error) {
1896
1855
  throw new Error(`runs.host('${key}') could not atomically replace its output.`, { cause: error instanceof Error ? error : void 0 });
1897
1856
  } finally {
1898
- if (descriptor !== void 0) fs7.closeSync(descriptor);
1857
+ if (descriptor !== void 0) fs6.closeSync(descriptor);
1899
1858
  try {
1900
- fs7.unlinkSync(temporaryPath);
1859
+ fs6.unlinkSync(temporaryPath);
1901
1860
  } catch (error) {
1902
1861
  if (error.code !== "ENOENT") throw error;
1903
1862
  }
@@ -1905,22 +1864,22 @@ function writeExplicitOutput(outputParent, outputPath, capture, key) {
1905
1864
  }
1906
1865
  function terminateProcessTree(pid, controller) {
1907
1866
  if (process.platform !== "win32") return controller.terminate();
1908
- return new Promise((resolve6) => {
1867
+ return new Promise((resolve5) => {
1909
1868
  const cleanup = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
1910
1869
  cleanup.once("error", () => {
1911
- void controller.terminate().then(resolve6);
1870
+ void controller.terminate().then(resolve5);
1912
1871
  });
1913
1872
  cleanup.once("close", () => {
1914
- void controller.terminate().then(resolve6);
1873
+ void controller.terminate().then(resolve5);
1915
1874
  });
1916
1875
  });
1917
1876
  }
1918
1877
  async function executeWorkflowHostCommand(input) {
1919
- const outputPath = input.params.output ? path8.resolve(input.cwd, input.params.output) : input.defaultOutputPath;
1920
- const relative4 = path8.relative(input.cwd, outputPath);
1921
- if (input.params.output && (relative4 === "" || relative4 === ".." || relative4.startsWith(`..${path8.sep}`) || path8.isAbsolute(relative4))) throw new Error(`runs.host('${input.key}') output escapes the workflow cwd.`);
1878
+ const outputPath = input.params.output ? path7.resolve(input.cwd, input.params.output) : input.defaultOutputPath;
1879
+ const relative4 = path7.relative(input.cwd, outputPath);
1880
+ if (input.params.output && (relative4 === "" || relative4 === ".." || relative4.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative4))) throw new Error(`runs.host('${input.key}') output escapes the workflow cwd.`);
1922
1881
  const explicitOutputParent = input.params.output ? assertSafeExplicitOutput(input.cwd, outputPath, input.key) : void 0;
1923
- if (!input.params.output) fs7.mkdirSync(path8.dirname(outputPath), { recursive: true });
1882
+ if (!input.params.output) fs6.mkdirSync(path7.dirname(outputPath), { recursive: true });
1924
1883
  const startedAt = Date.now();
1925
1884
  let stdout = "";
1926
1885
  let stderr = "";
@@ -1928,7 +1887,7 @@ async function executeWorkflowHostCommand(input) {
1928
1887
  let timedOut = false;
1929
1888
  let stopped = false;
1930
1889
  let settled = false;
1931
- return new Promise((resolve6, reject) => {
1890
+ return new Promise((resolve5, reject) => {
1932
1891
  const child = spawn(quoteExecutableForShell(input.params.command), {
1933
1892
  cwd: input.cwd,
1934
1893
  env: process.env,
@@ -1978,13 +1937,13 @@ async function executeWorkflowHostCommand(input) {
1978
1937
  if (currentParent !== explicitOutputParent) throw new Error(`output parent changed while the command was running.`);
1979
1938
  writeExplicitOutput(explicitOutputParent, outputPath, capture, input.key);
1980
1939
  } else {
1981
- fs7.writeFileSync(outputPath, capture, { encoding: "utf8", mode: 384 });
1940
+ fs6.writeFileSync(outputPath, capture, { encoding: "utf8", mode: 384 });
1982
1941
  }
1983
1942
  } catch (writeError) {
1984
1943
  reject(new Error(`runs.host('${input.key}') could not save command output: ${writeError instanceof Error ? writeError.message : String(writeError)}`, { cause: writeError instanceof Error ? writeError : void 0 }));
1985
1944
  return;
1986
1945
  }
1987
- resolve6({ key: input.key, kind: "command", ok: state === "passed", state, exitCode, stdout, stderr, outputPath, durationMs: Date.now() - startedAt, ...error ? { error } : {} });
1946
+ resolve5({ key: input.key, kind: "command", ok: state === "passed", state, exitCode, stdout, stderr, outputPath, durationMs: Date.now() - startedAt, ...error ? { error } : {} });
1988
1947
  };
1989
1948
  child.on("close", (code) => {
1990
1949
  void finish(code);
@@ -1996,15 +1955,15 @@ async function executeWorkflowHostCommand(input) {
1996
1955
  }
1997
1956
 
1998
1957
  // src/workflows/scripted-workflow.ts
1999
- import { accessSync, constants as constants2, readFileSync as readFileSync6, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
1958
+ import { accessSync, constants as constants2, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync4 } from "node:fs";
2000
1959
  import { createRequire } from "node:module";
2001
- import { dirname as dirname7, resolve as resolvePath } from "node:path";
1960
+ import { dirname as dirname6, resolve as resolvePath } from "node:path";
2002
1961
 
2003
1962
  // src/workflows/workflow-script-worker.ts
2004
1963
  import { fork } from "node:child_process";
2005
1964
  import { EventEmitter } from "node:events";
2006
- import { realpathSync as realpathSync3 } from "node:fs";
2007
- import { dirname as dirname6 } from "node:path";
1965
+ import { realpathSync as realpathSync2 } from "node:fs";
1966
+ import { dirname as dirname5 } from "node:path";
2008
1967
  import { fileURLToPath } from "node:url";
2009
1968
  import { Worker } from "node:worker_threads";
2010
1969
  var WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", new URL("../src/workflows/workflow-script-worker.js", import.meta.url).href);
@@ -2016,17 +1975,17 @@ var WorkflowScriptProcess = class extends EventEmitter {
2016
1975
  stderr = "";
2017
1976
  constructor(acornPath) {
2018
1977
  super();
2019
- const acorn = realpathSync3(acornPath);
2020
- this.child = fork(WORKFLOW_PROCESS_URL, [acorn], {
1978
+ const acorn = realpathSync2(acornPath);
1979
+ this.child = fork(fileURLToPath(WORKFLOW_PROCESS_URL), [acorn], {
2021
1980
  // Under --permission, Node lets worker threads read everything under the process cwd, so the cwd must
2022
1981
  // hold only public files: acorn's own directory. It also never holds a caller's cwd open on Windows.
2023
- cwd: dirname6(acorn),
1982
+ cwd: dirname5(acorn),
2024
1983
  // No inherited execArgv or NODE_OPTIONS. Only the supervisor may create a worker.
2025
1984
  execArgv: [
2026
1985
  "--permission",
2027
1986
  "--allow-worker",
2028
- `--allow-fs-read=${realpathSync3(fileURLToPath(WORKFLOW_PROCESS_URL))}`,
2029
- `--allow-fs-read=${realpathSync3(fileURLToPath(WORKFLOW_WORKER_URL))}`,
1987
+ `--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_PROCESS_URL))}`,
1988
+ `--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_WORKER_URL))}`,
2030
1989
  `--allow-fs-read=${acorn}`
2031
1990
  ],
2032
1991
  env: process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {},
@@ -2063,8 +2022,8 @@ var WorkflowScriptProcess = class extends EventEmitter {
2063
2022
  async terminate() {
2064
2023
  if (this.exitCode !== void 0) return this.exitCode;
2065
2024
  this.stopping = true;
2066
- return await new Promise((resolve6) => {
2067
- this.once("exit", resolve6);
2025
+ return await new Promise((resolve5) => {
2026
+ this.once("exit", resolve5);
2068
2027
  this.child.kill("SIGKILL");
2069
2028
  });
2070
2029
  }
@@ -2344,25 +2303,25 @@ function omitNonJsonWorkflowResultMetadata(value) {
2344
2303
  return safeResult;
2345
2304
  }
2346
2305
  }
2347
- function assertWorkflowJsonValue(value, path17 = "value", seen = /* @__PURE__ */ new Set()) {
2306
+ function assertWorkflowJsonValue(value, path16 = "value", seen = /* @__PURE__ */ new Set()) {
2348
2307
  if (value === null || typeof value === "string" || typeof value === "boolean") return;
2349
2308
  if (typeof value === "number") {
2350
- if (!Number.isFinite(value)) throw new Error(`${path17} must contain only finite JSON numbers.`);
2309
+ if (!Number.isFinite(value)) throw new Error(`${path16} must contain only finite JSON numbers.`);
2351
2310
  return;
2352
2311
  }
2353
- if (typeof value !== "object") throw new Error(`${path17} must be a JSON value; received ${typeof value}.`);
2354
- if (seen.has(value)) throw new Error(`${path17} must not contain cycles.`);
2312
+ if (typeof value !== "object") throw new Error(`${path16} must be a JSON value; received ${typeof value}.`);
2313
+ if (seen.has(value)) throw new Error(`${path16} must not contain cycles.`);
2355
2314
  seen.add(value);
2356
2315
  if (Array.isArray(value)) {
2357
2316
  for (let index = 0; index < value.length; index++) {
2358
- if (!Object.hasOwn(value, index)) throw new Error(`${path17} must not contain sparse array entries.`);
2359
- assertWorkflowJsonValue(value[index], `${path17}[${index}]`, seen);
2317
+ if (!Object.hasOwn(value, index)) throw new Error(`${path16} must not contain sparse array entries.`);
2318
+ assertWorkflowJsonValue(value[index], `${path16}[${index}]`, seen);
2360
2319
  }
2361
2320
  } else {
2362
2321
  const prototype = Object.getPrototypeOf(value);
2363
- if (prototype !== null && prototype !== Object.prototype) throw new Error(`${path17} must contain only plain JSON objects.`);
2364
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path17} must not contain symbol keys.`);
2365
- for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${path17}.${key}`, seen);
2322
+ if (prototype !== null && prototype !== Object.prototype) throw new Error(`${path16} must contain only plain JSON objects.`);
2323
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path16} must not contain symbol keys.`);
2324
+ for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${path16}.${key}`, seen);
2366
2325
  }
2367
2326
  seen.delete(value);
2368
2327
  }
@@ -2906,9 +2865,9 @@ function resolveWorkflowParserEntry() {
2906
2865
  } catch (primaryError) {
2907
2866
  try {
2908
2867
  const manifestPath = requireFromPackage.resolve("acorn/package.json");
2909
- const manifest = JSON.parse(readFileSync6(manifestPath, "utf8"));
2868
+ const manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
2910
2869
  const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
2911
- return resolvePath(dirname7(manifestPath), entry);
2870
+ return resolvePath(dirname6(manifestPath), entry);
2912
2871
  } catch {
2913
2872
  throw primaryError;
2914
2873
  }
@@ -2953,7 +2912,7 @@ async function runWorkflowScript(options) {
2953
2912
  if (options.processCwd !== void 0) {
2954
2913
  let staleCwd = false;
2955
2914
  try {
2956
- realpathSync4(process.cwd());
2915
+ realpathSync3(process.cwd());
2957
2916
  } catch (error) {
2958
2917
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
2959
2918
  if (code !== "ENOENT") throw new WorkflowScriptError("Workflow current cwd could not be validated.", emptyPartial(), "runtime", { cause: error });
@@ -2962,7 +2921,7 @@ async function runWorkflowScript(options) {
2962
2921
  try {
2963
2922
  if (staleCwd) process.chdir(options.processCwd);
2964
2923
  else {
2965
- const target = realpathSync4(options.processCwd);
2924
+ const target = realpathSync3(options.processCwd);
2966
2925
  if (!statSync4(target).isDirectory()) {
2967
2926
  const error = new Error(`ENOTDIR: not a directory, access '${target}'`);
2968
2927
  error.code = "ENOTDIR";
@@ -3105,7 +3064,7 @@ async function runWorkflowScript(options) {
3105
3064
  };
3106
3065
  options.registerStopChild?.(stopChild);
3107
3066
  options.registerDrain?.(drain);
3108
- return await new Promise((resolve6, reject) => {
3067
+ return await new Promise((resolve5, reject) => {
3109
3068
  const finish = (outcome) => {
3110
3069
  if (settled || finishing) return;
3111
3070
  finishing = true;
@@ -3131,7 +3090,7 @@ async function runWorkflowScript(options) {
3131
3090
  })() : void 0;
3132
3091
  if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), isWorkflowScriptFailureKind(outcome.error.workflowErrorKind) ? outcome.error.workflowErrorKind : void 0));
3133
3092
  else if (completionError) reject(new WorkflowScriptError(completionError.message, partial(), "validation"));
3134
- else resolve6({ value: outcome.value, ...partial() });
3093
+ else resolve5({ value: outcome.value, ...partial() });
3135
3094
  });
3136
3095
  };
3137
3096
  const onAbort = () => {
@@ -3557,10 +3516,10 @@ async function runWorkflowScript(options) {
3557
3516
  }
3558
3517
 
3559
3518
  // src/missions/store.ts
3560
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
3561
- import * as fs8 from "node:fs";
3519
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
3520
+ import * as fs7 from "node:fs";
3562
3521
  import * as os from "node:os";
3563
- import * as path9 from "node:path";
3522
+ import * as path8 from "node:path";
3564
3523
 
3565
3524
  // src/missions/types.ts
3566
3525
  var MISSION_STATUSES = [
@@ -3775,12 +3734,12 @@ function parseMissionRecord(value, source = "mission record") {
3775
3734
  };
3776
3735
  }
3777
3736
  function expandConfiguredPath(value, projectRoot) {
3778
- const expanded = value.startsWith("~/") ? path9.join(os.homedir(), value.slice(2)) : value;
3779
- return path9.isAbsolute(expanded) ? path9.normalize(expanded) : path9.resolve(projectRoot, expanded);
3737
+ const expanded = value.startsWith("~/") ? path8.join(os.homedir(), value.slice(2)) : value;
3738
+ return path8.isAbsolute(expanded) ? path8.normalize(expanded) : path8.resolve(projectRoot, expanded);
3780
3739
  }
3781
3740
  function projectMissionDirectory(agentDir, projectRoot) {
3782
- const projectKey = createHash3("sha256").update(projectRoot).digest("hex");
3783
- return path9.join(agentDir, "missions", "projects", projectKey);
3741
+ const projectKey = createHash2("sha256").update(projectRoot).digest("hex");
3742
+ return path8.join(agentDir, "missions", "projects", projectKey);
3784
3743
  }
3785
3744
  function validateMissionStoreConfig(value, label = "config.missions") {
3786
3745
  if (value === void 0) return void 0;
@@ -3810,23 +3769,23 @@ function canonicalProjectRoot(root) {
3810
3769
  let current = root;
3811
3770
  for (; ; ) {
3812
3771
  try {
3813
- return path9.join(fs8.realpathSync.native(current), ...missing.reverse());
3772
+ return path8.join(fs7.realpathSync.native(current), ...missing.reverse());
3814
3773
  } catch (error) {
3815
3774
  if (error.code !== "ENOENT") throw error;
3816
- const parent = path9.dirname(current);
3775
+ const parent = path8.dirname(current);
3817
3776
  if (parent === current) return root;
3818
- missing.push(path9.basename(current));
3777
+ missing.push(path8.basename(current));
3819
3778
  current = parent;
3820
3779
  }
3821
3780
  }
3822
3781
  }
3823
3782
  function resolveMissionStoreLocation(input) {
3824
- const givenRoot = path9.resolve(input.projectRoot);
3783
+ const givenRoot = path8.resolve(input.projectRoot);
3825
3784
  const configuredDir = input.config?.directory;
3826
3785
  const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
3827
3786
  const agentDir = input.agentDir ?? getAgentDir();
3828
3787
  const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
3829
- const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) : path9.join(agentDir, "missions", "index");
3788
+ const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) : path8.join(agentDir, "missions", "index");
3830
3789
  return {
3831
3790
  projectRoot,
3832
3791
  missionDir,
@@ -3836,7 +3795,7 @@ function resolveMissionStoreLocation(input) {
3836
3795
  };
3837
3796
  }
3838
3797
  function missionRecordPath(location, missionId) {
3839
- return path9.join(location.missionDir, `${validateMissionId(missionId)}.json`);
3798
+ return path8.join(location.missionDir, `${validateMissionId(missionId)}.json`);
3840
3799
  }
3841
3800
  function parseIndexEntry(value, source) {
3842
3801
  const input = asObject(value, source);
@@ -3853,8 +3812,8 @@ function parseIndexEntry(value, source) {
3853
3812
  };
3854
3813
  }
3855
3814
  function indexPath(location, record) {
3856
- const key = createHash3("sha256").update(`${location.projectRoot}\0${record.id}`).digest("hex");
3857
- return path9.join(location.globalIndexDir, `${key}.json`);
3815
+ const key = createHash2("sha256").update(`${location.projectRoot}\0${record.id}`).digest("hex");
3816
+ return path8.join(location.globalIndexDir, `${key}.json`);
3858
3817
  }
3859
3818
  function writeMission(location, record) {
3860
3819
  const validated = parseMissionRecord(record);
@@ -3879,9 +3838,9 @@ function pruneTerminalMissions(location, maxTerminal) {
3879
3838
  const terminal3 = listMissions(location).records.filter((record) => TERMINAL_MISSION_STATUSES.has(record.status)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
3880
3839
  for (const record of terminal3.slice(maxTerminal)) {
3881
3840
  try {
3882
- fs8.rmSync(missionRecordPath(location, record.id), { force: true });
3883
- fs8.rmSync(path9.join(location.missionDir, record.id), { recursive: true, force: true });
3884
- if (location.writeGlobalIndex) fs8.rmSync(indexPath(location, record), { force: true });
3841
+ fs7.rmSync(missionRecordPath(location, record.id), { force: true });
3842
+ fs7.rmSync(path8.join(location.missionDir, record.id), { recursive: true, force: true });
3843
+ if (location.writeGlobalIndex) fs7.rmSync(indexPath(location, record), { force: true });
3885
3844
  } catch {
3886
3845
  }
3887
3846
  }
@@ -3890,7 +3849,7 @@ function createMission(location, input, now = /* @__PURE__ */ new Date(), retain
3890
3849
  const createdAt = now.toISOString();
3891
3850
  const record = {
3892
3851
  schemaVersion: 1,
3893
- id: randomUUID4(),
3852
+ id: randomUUID3(),
3894
3853
  title: requiredString(input.title, "mission.title").trim(),
3895
3854
  objective: requiredString(input.objective, "mission.objective").trim(),
3896
3855
  ...input.goal === true ? { goal: { status: "active" } } : {},
@@ -3928,7 +3887,7 @@ function readMission(location, missionId) {
3928
3887
  const filePath = missionRecordPath(location, missionId);
3929
3888
  let raw;
3930
3889
  try {
3931
- raw = fs8.readFileSync(filePath, "utf-8");
3890
+ raw = fs7.readFileSync(filePath, "utf-8");
3932
3891
  } catch (error) {
3933
3892
  if (error.code === "ENOENT") throw new MissionNotFoundError(missionId, location);
3934
3893
  throw error;
@@ -3940,13 +3899,13 @@ function readMission(location, missionId) {
3940
3899
  }
3941
3900
  }
3942
3901
  function listMissions(location) {
3943
- if (!fs8.existsSync(location.missionDir)) return { records: [], warnings: [] };
3902
+ if (!fs7.existsSync(location.missionDir)) return { records: [], warnings: [] };
3944
3903
  const records = [];
3945
3904
  const warnings = [];
3946
- for (const name of fs8.readdirSync(location.missionDir).filter((item) => item.endsWith(".json")).sort()) {
3947
- const filePath = path9.join(location.missionDir, name);
3905
+ for (const name of fs7.readdirSync(location.missionDir).filter((item) => item.endsWith(".json")).sort()) {
3906
+ const filePath = path8.join(location.missionDir, name);
3948
3907
  try {
3949
- records.push(parseMissionRecord(JSON.parse(fs8.readFileSync(filePath, "utf-8")), filePath));
3908
+ records.push(parseMissionRecord(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath));
3950
3909
  } catch (error) {
3951
3910
  warnings.push(`Skipped corrupt mission '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
3952
3911
  }
@@ -3988,7 +3947,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
3988
3947
  const artifacts = [...current.artifacts];
3989
3948
  for (const candidate of update.addArtifacts ?? []) {
3990
3949
  const artifact = parseArtifact(candidate, "mission.update.addArtifacts[]");
3991
- const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind && path9.resolve(item.path) === path9.resolve(artifact.path));
3950
+ const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind && path8.resolve(item.path) === path8.resolve(artifact.path));
3992
3951
  if (existingIndex === -1) artifacts.push(artifact);
3993
3952
  else artifacts[existingIndex] = { ...artifacts[existingIndex], ...artifact };
3994
3953
  }
@@ -4003,7 +3962,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
4003
3962
  const decisions = [
4004
3963
  ...current.decisions,
4005
3964
  ...(update.addDecisions ?? []).map((decision) => ({
4006
- id: randomUUID4(),
3965
+ id: randomUUID3(),
4007
3966
  status: "open",
4008
3967
  title: requiredString(decision.title, "mission.update.addDecisions[].title"),
4009
3968
  createdAt,
@@ -4058,15 +4017,15 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
4058
4017
  return updated;
4059
4018
  }
4060
4019
  function listGlobalMissions(globalIndexDir) {
4061
- if (!fs8.existsSync(globalIndexDir)) return { entries: [], warnings: [] };
4020
+ if (!fs7.existsSync(globalIndexDir)) return { entries: [], warnings: [] };
4062
4021
  const entries = [];
4063
4022
  const warnings = [];
4064
- for (const name of fs8.readdirSync(globalIndexDir).filter((item) => item.endsWith(".json")).sort()) {
4065
- const filePath = path9.join(globalIndexDir, name);
4023
+ for (const name of fs7.readdirSync(globalIndexDir).filter((item) => item.endsWith(".json")).sort()) {
4024
+ const filePath = path8.join(globalIndexDir, name);
4066
4025
  try {
4067
- const entry = parseIndexEntry(JSON.parse(fs8.readFileSync(filePath, "utf-8")), filePath);
4026
+ const entry = parseIndexEntry(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath);
4068
4027
  try {
4069
- const record = parseMissionRecord(JSON.parse(fs8.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
4028
+ const record = parseMissionRecord(JSON.parse(fs7.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
4070
4029
  if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
4071
4030
  const projection = {
4072
4031
  ...entry,
@@ -4081,7 +4040,7 @@ function listGlobalMissions(globalIndexDir) {
4081
4040
  } catch (error) {
4082
4041
  if (error.code === "ENOENT") {
4083
4042
  try {
4084
- fs8.rmSync(filePath, { force: true });
4043
+ fs7.rmSync(filePath, { force: true });
4085
4044
  warnings.push(`Removed stale global mission pointer '${filePath}' because '${entry.recordPath}' no longer exists.`);
4086
4045
  } catch (removeError) {
4087
4046
  warnings.push(`Failed to remove stale global mission pointer '${filePath}': ${removeError instanceof Error ? removeError.message : String(removeError)}`);
@@ -4100,14 +4059,14 @@ function listGlobalMissions(globalIndexDir) {
4100
4059
 
4101
4060
  // src/missions/workflow-state.ts
4102
4061
  import { execFileSync } from "node:child_process";
4103
- import { randomUUID as randomUUID5 } from "node:crypto";
4104
- import * as fs9 from "node:fs";
4105
- import * as path10 from "node:path";
4062
+ import { randomUUID as randomUUID4 } from "node:crypto";
4063
+ import * as fs8 from "node:fs";
4064
+ import * as path9 from "node:path";
4106
4065
  var STATE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
4107
4066
  var STATE_LOCK_STALE_MS = 6e4;
4108
4067
  var MISSION_STATE_MAX_BYTES = 256 * 1024;
4109
4068
  function missionStatePath(location, missionId) {
4110
- return path10.join(location.missionDir, validateMissionId(missionId), "state.json");
4069
+ return path9.join(location.missionDir, validateMissionId(missionId), "state.json");
4111
4070
  }
4112
4071
  function isProcessAlive(pid) {
4113
4072
  try {
@@ -4119,7 +4078,7 @@ function isProcessAlive(pid) {
4119
4078
  }
4120
4079
  function linuxProcessStartKey(pid) {
4121
4080
  try {
4122
- const raw = fs9.readFileSync(`/proc/${pid}/stat`, "utf-8");
4081
+ const raw = fs8.readFileSync(`/proc/${pid}/stat`, "utf-8");
4123
4082
  const tail = raw.slice(raw.lastIndexOf(")") + 2).trim().split(/\s+/);
4124
4083
  return tail[19] ? `linux:${tail[19]}` : void 0;
4125
4084
  } catch {
@@ -4155,7 +4114,7 @@ function computeProcessStartKey(pid) {
4155
4114
  }
4156
4115
  function readStateLockOwner(lockPath) {
4157
4116
  try {
4158
- const owner = JSON.parse(fs9.readFileSync(path10.join(lockPath, "owner.json"), "utf-8"));
4117
+ const owner = JSON.parse(fs8.readFileSync(path9.join(lockPath, "owner.json"), "utf-8"));
4159
4118
  if (Number.isSafeInteger(owner.pid) && owner.pid > 0 && typeof owner.token === "string" && owner.token && Number.isSafeInteger(owner.createdAt)) {
4160
4119
  return {
4161
4120
  pid: owner.pid,
@@ -4181,7 +4140,7 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
4181
4140
  return false;
4182
4141
  }
4183
4142
  try {
4184
- return now - fs9.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;
4143
+ return now - fs8.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;
4185
4144
  } catch (error) {
4186
4145
  if (error.code === "ENOENT") return false;
4187
4146
  throw error;
@@ -4190,11 +4149,11 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
4190
4149
  function removeOwnedStateLock(lockPath, owner) {
4191
4150
  const current = readStateLockOwner(lockPath);
4192
4151
  if (current?.token !== owner.token) return;
4193
- fs9.rmSync(lockPath, { recursive: true, force: true });
4152
+ fs8.rmSync(lockPath, { recursive: true, force: true });
4194
4153
  }
4195
4154
  function staleDirectoryExists(dirPath, now = Date.now()) {
4196
4155
  try {
4197
- return now - fs9.statSync(dirPath).mtimeMs > STATE_LOCK_STALE_MS;
4156
+ return now - fs8.statSync(dirPath).mtimeMs > STATE_LOCK_STALE_MS;
4198
4157
  } catch (error) {
4199
4158
  if (error.code === "ENOENT") return false;
4200
4159
  throw error;
@@ -4202,7 +4161,7 @@ function staleDirectoryExists(dirPath, now = Date.now()) {
4202
4161
  }
4203
4162
  function tryMakeDirectory(dirPath, mode) {
4204
4163
  try {
4205
- fs9.mkdirSync(dirPath, { mode });
4164
+ fs8.mkdirSync(dirPath, { mode });
4206
4165
  return true;
4207
4166
  } catch (error) {
4208
4167
  if (error.code === "EEXIST") return false;
@@ -4218,21 +4177,21 @@ function reclaimStaleStateLock(lockPath, reclaimPath, options) {
4218
4177
  if (!tryMakeDirectory(reclaimPath, 448)) return false;
4219
4178
  try {
4220
4179
  if (!stateLockIsStale(lockPath, options)) return false;
4221
- fs9.rmSync(lockPath, { recursive: true, force: true });
4180
+ fs8.rmSync(lockPath, { recursive: true, force: true });
4222
4181
  return true;
4223
4182
  } finally {
4224
- fs9.rmSync(reclaimPath, { recursive: true, force: true });
4183
+ fs8.rmSync(reclaimPath, { recursive: true, force: true });
4225
4184
  }
4226
4185
  }
4227
4186
  function withStateFileLock(filePath, operation, options) {
4228
- fs9.mkdirSync(path10.dirname(filePath), { recursive: true });
4187
+ fs8.mkdirSync(path9.dirname(filePath), { recursive: true });
4229
4188
  const lockPath = `${filePath}.lock`;
4230
4189
  const reclaimPath = `${lockPath}.reclaim`;
4231
4190
  let owner;
4232
4191
  for (let attempt = 0; ; attempt++) {
4233
- if (fs9.existsSync(reclaimPath)) {
4192
+ if (fs8.existsSync(reclaimPath)) {
4234
4193
  if (staleDirectoryExists(reclaimPath)) {
4235
- fs9.rmSync(reclaimPath, { recursive: true, force: true });
4194
+ fs8.rmSync(reclaimPath, { recursive: true, force: true });
4236
4195
  continue;
4237
4196
  }
4238
4197
  waitForStateLock(options.retryDelaysMs[attempt], lockPath);
@@ -4254,11 +4213,11 @@ function withStateFileLock(filePath, operation, options) {
4254
4213
  continue;
4255
4214
  }
4256
4215
  const key = options.getProcessStartKey(process.pid);
4257
- owner = { pid: process.pid, token: randomUUID5(), createdAt: Date.now(), ...key ? { processKey: key } : {} };
4216
+ owner = { pid: process.pid, token: randomUUID4(), createdAt: Date.now(), ...key ? { processKey: key } : {} };
4258
4217
  try {
4259
- fs9.writeFileSync(path10.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
4218
+ fs8.writeFileSync(path9.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
4260
4219
  } catch (error) {
4261
- fs9.rmSync(lockPath, { recursive: true, force: true });
4220
+ fs8.rmSync(lockPath, { recursive: true, force: true });
4262
4221
  owner = void 0;
4263
4222
  throw error;
4264
4223
  }
@@ -4288,7 +4247,7 @@ function createMissionWorkflowState(location, missionId, options = {}) {
4288
4247
  const readStateFile = () => {
4289
4248
  let raw;
4290
4249
  try {
4291
- raw = fs9.readFileSync(filePath, "utf-8");
4250
+ raw = fs8.readFileSync(filePath, "utf-8");
4292
4251
  } catch (error) {
4293
4252
  if (error.code === "ENOENT") return /* @__PURE__ */ Object.create(null);
4294
4253
  throw new Error(`Failed to read mission state '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
@@ -4333,13 +4292,13 @@ function createMissionWorkflowState(location, missionId, options = {}) {
4333
4292
  }
4334
4293
 
4335
4294
  // src/missions/actions.ts
4336
- import * as fs11 from "node:fs";
4337
- import * as path12 from "node:path";
4338
-
4339
- // src/missions/lifecycle.ts
4340
4295
  import * as fs10 from "node:fs";
4341
4296
  import * as path11 from "node:path";
4342
- import { createHash as createHash4 } from "node:crypto";
4297
+
4298
+ // src/missions/lifecycle.ts
4299
+ import * as fs9 from "node:fs";
4300
+ import * as path10 from "node:path";
4301
+ import { createHash as createHash3 } from "node:crypto";
4343
4302
  var MISSION_BINDING_FILE = "mission.json";
4344
4303
  function workflowObjective(params) {
4345
4304
  const objective = params.task?.trim() || params.tasks?.find((task) => task.task?.trim())?.task?.trim() || params.chain?.find((step) => step.task?.trim())?.task?.trim();
@@ -4427,8 +4386,8 @@ function artifactsForResult(result) {
4427
4386
  const artifacts = [];
4428
4387
  if (result.details.asyncDir) {
4429
4388
  artifacts.push(
4430
- { kind: "status", path: path11.join(result.details.asyncDir, "status.json") },
4431
- { kind: "other", path: path11.join(result.details.asyncDir, "events.jsonl"), description: "Lifecycle events" }
4389
+ { kind: "status", path: path10.join(result.details.asyncDir, "status.json") },
4390
+ { kind: "other", path: path10.join(result.details.asyncDir, "events.jsonl"), description: "Lifecycle events" }
4432
4391
  );
4433
4392
  }
4434
4393
  for (const child of result.details.results) {
@@ -4458,7 +4417,7 @@ function persistedBinding(binding) {
4458
4417
  };
4459
4418
  }
4460
4419
  function writeMissionAsyncBinding(asyncDir, binding) {
4461
- writePrivateAtomicJson(path11.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
4420
+ writePrivateAtomicJson(path10.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
4462
4421
  }
4463
4422
  function attachMissionToLaunchResult(input) {
4464
4423
  const runId = input.result.details.runId ?? input.result.details.asyncId;
@@ -4502,10 +4461,10 @@ function attachMissionToLaunchResult(input) {
4502
4461
  });
4503
4462
  if (input.result.details.asyncDir) {
4504
4463
  writeMissionAsyncBinding(input.result.details.asyncDir, input.binding);
4505
- const statusPath = path11.join(input.result.details.asyncDir, "status.json");
4506
- if (fs10.existsSync(statusPath)) {
4464
+ const statusPath = path10.join(input.result.details.asyncDir, "status.json");
4465
+ if (fs9.existsSync(statusPath)) {
4507
4466
  try {
4508
- const status = JSON.parse(fs10.readFileSync(statusPath, "utf-8"));
4467
+ const status = JSON.parse(fs9.readFileSync(statusPath, "utf-8"));
4509
4468
  if (typeof status.state === "string" && !["queued", "running"].includes(status.state)) {
4510
4469
  mission = syncMissionFromAsyncCompletion({
4511
4470
  runId,
@@ -4568,9 +4527,9 @@ function parsePersistedBinding(value, source) {
4568
4527
  };
4569
4528
  }
4570
4529
  function readMissionBinding(asyncDir) {
4571
- const bindingPath = path11.join(asyncDir, MISSION_BINDING_FILE);
4572
- if (!fs10.existsSync(bindingPath)) return void 0;
4573
- const raw = fs10.readFileSync(bindingPath, "utf-8");
4530
+ const bindingPath = path10.join(asyncDir, MISSION_BINDING_FILE);
4531
+ if (!fs9.existsSync(bindingPath)) return void 0;
4532
+ const raw = fs9.readFileSync(bindingPath, "utf-8");
4574
4533
  try {
4575
4534
  return parsePersistedBinding(JSON.parse(raw), bindingPath);
4576
4535
  } catch (error) {
@@ -4592,12 +4551,12 @@ function syncMissionFromAsyncCompletion(value) {
4592
4551
  } catch (error) {
4593
4552
  if (!(error instanceof MissionNotFoundError)) throw error;
4594
4553
  const reason = "mission-record-missing";
4595
- const markerId = createHash4("sha256").update(JSON.stringify([runId, binding.missionId, reason])).digest("hex");
4596
- const markerPath3 = path11.join(event.asyncDir, `.mission-sync-skipped-${markerId}.json`);
4554
+ const markerId = createHash3("sha256").update(JSON.stringify([runId, binding.missionId, reason])).digest("hex");
4555
+ const markerPath3 = path10.join(event.asyncDir, `.mission-sync-skipped-${markerId}.json`);
4597
4556
  try {
4598
- fs10.writeFileSync(markerPath3, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}
4557
+ fs9.writeFileSync(markerPath3, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}
4599
4558
  `, { encoding: "utf-8", mode: 384, flag: "wx" });
4600
- fs10.appendFileSync(path11.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
4559
+ fs9.appendFileSync(path10.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
4601
4560
  type: "subagent.mission.sync.skipped",
4602
4561
  ts: Date.now(),
4603
4562
  runId,
@@ -4612,8 +4571,8 @@ function syncMissionFromAsyncCompletion(value) {
4612
4571
  }
4613
4572
  const completedAt = (/* @__PURE__ */ new Date()).toISOString();
4614
4573
  const artifacts = [
4615
- { kind: "status", path: path11.join(event.asyncDir, "status.json") },
4616
- { kind: "other", path: path11.join(event.asyncDir, "events.jsonl"), description: "Lifecycle events" }
4574
+ { kind: "status", path: path10.join(event.asyncDir, "status.json") },
4575
+ { kind: "other", path: path10.join(event.asyncDir, "events.jsonl"), description: "Lifecycle events" }
4617
4576
  ];
4618
4577
  if (event.parallelHandoff && typeof event.parallelHandoff === "object" && typeof event.parallelHandoff.path === "string") {
4619
4578
  artifacts.push({ kind: "manifest", path: event.parallelHandoff.path });
@@ -4809,11 +4768,11 @@ function refreshLinkedRunStatus(location, record) {
4809
4768
  const runAcceptance = [];
4810
4769
  const updates = record.runs.flatMap((run) => {
4811
4770
  if (!run.asyncDir) return [];
4812
- const statusPath = path12.join(run.asyncDir, "status.json");
4813
- if (!fs11.existsSync(statusPath)) return [];
4771
+ const statusPath = path11.join(run.asyncDir, "status.json");
4772
+ if (!fs10.existsSync(statusPath)) return [];
4814
4773
  let status2;
4815
4774
  try {
4816
- status2 = JSON.parse(fs11.readFileSync(statusPath, "utf-8"));
4775
+ status2 = JSON.parse(fs10.readFileSync(statusPath, "utf-8"));
4817
4776
  } catch (error) {
4818
4777
  warnings.push(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`);
4819
4778
  return [];
@@ -4985,9 +4944,9 @@ ${formatMission(record2)}`, { mode: "management", results: [], missionId: record
4985
4944
  }
4986
4945
 
4987
4946
  // src/runs/background/result-files.ts
4988
- import { createHash as createHash5 } from "node:crypto";
4989
- import * as fs12 from "node:fs";
4990
- import * as path13 from "node:path";
4947
+ import { createHash as createHash4 } from "node:crypto";
4948
+ import * as fs11 from "node:fs";
4949
+ import * as path12 from "node:path";
4991
4950
  var RESULT_INDEX_VERSION = 1;
4992
4951
  var RESULT_INDEX_DIR = "result-index";
4993
4952
  var SESSION_INDEX_DIR = "sessions";
@@ -5018,31 +4977,31 @@ function resultFileName(runId) {
5018
4977
  return `${runId}${JSON_EXTENSION}`;
5019
4978
  }
5020
4979
  function resultFilePath(resultsDir, runId) {
5021
- return path13.join(resultsDir, resultFileName(runId));
4980
+ return path12.join(resultsDir, resultFileName(runId));
5022
4981
  }
5023
4982
  function sessionIndexDir2(resultsDir, sessionId) {
5024
- return path13.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, encodeSegment(sessionId));
4983
+ return path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, encodeSegment(sessionId));
5025
4984
  }
5026
4985
  function sessionIndexDirs(resultsDir, sessionId) {
5027
- return indexSegmentAliases(sessionId).map((segment) => path13.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, segment));
4986
+ return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, segment));
5028
4987
  }
5029
4988
  function resultIndexPath(resultsDir, sessionId, runId) {
5030
- return path13.join(sessionIndexDir2(resultsDir, sessionId), encodedJsonFileName(runId));
4989
+ return path12.join(sessionIndexDir2(resultsDir, sessionId), encodedJsonFileName(runId));
5031
4990
  }
5032
4991
  function resultIndexPaths(resultsDir, sessionId, runId) {
5033
- return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) => path13.join(dir, fileName)));
4992
+ return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) => path12.join(dir, fileName)));
5034
4993
  }
5035
4994
  function runIndexPath(resultsDir, runId) {
5036
- return path13.join(resultsDir, RESULT_INDEX_DIR, RUN_INDEX_DIR, encodedJsonFileName(runId));
4995
+ return path12.join(resultsDir, RESULT_INDEX_DIR, RUN_INDEX_DIR, encodedJsonFileName(runId));
5037
4996
  }
5038
4997
  function resultPendingPath(resultsDir, sessionId, runId) {
5039
- return path13.join(resultsDir, RESULT_PENDING_DIR, encodeSegment(sessionId), encodedJsonFileName(runId));
4998
+ return path12.join(resultsDir, RESULT_PENDING_DIR, encodeSegment(sessionId), encodedJsonFileName(runId));
5040
4999
  }
5041
5000
  function resultPendingPaths(resultsDir, sessionId, runId) {
5042
- return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) => path13.join(resultsDir, RESULT_PENDING_DIR, segment, fileName)));
5001
+ return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) => path12.join(resultsDir, RESULT_PENDING_DIR, segment, fileName)));
5043
5002
  }
5044
5003
  function pendingSessionDirs(resultsDir, sessionId) {
5045
- return indexSegmentAliases(sessionId).map((segment) => path13.join(resultsDir, RESULT_PENDING_DIR, segment));
5004
+ return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_PENDING_DIR, segment));
5046
5005
  }
5047
5006
  function firstExistingResultFile(paths) {
5048
5007
  for (const filePath of paths) {
@@ -5051,19 +5010,19 @@ function firstExistingResultFile(paths) {
5051
5010
  return void 0;
5052
5011
  }
5053
5012
  function observerIndexDir(resultsDir, observer) {
5054
- return path13.join(resultsDir, RESULT_INDEX_DIR, OBSERVER_INDEX_DIR, observer);
5013
+ return path12.join(resultsDir, RESULT_INDEX_DIR, OBSERVER_INDEX_DIR, observer);
5055
5014
  }
5056
5015
  function observerIndexPath(resultsDir, observer, runId) {
5057
- return path13.join(observerIndexDir(resultsDir, observer), encodedJsonFileName(runId));
5016
+ return path12.join(observerIndexDir(resultsDir, observer), encodedJsonFileName(runId));
5058
5017
  }
5059
5018
  function missionObserverIndexPath(resultsDir, runId) {
5060
5019
  return observerIndexPath(resultsDir, MISSION_OBSERVER, runId);
5061
5020
  }
5062
5021
  function toolCallIndexDir3(resultsDir, toolCallId) {
5063
- return path13.join(resultsDir, RESULT_INDEX_DIR, TOOL_CALL_INDEX_DIR3, encodeIndexSegment(toolCallId));
5022
+ return path12.join(resultsDir, RESULT_INDEX_DIR, TOOL_CALL_INDEX_DIR3, encodeIndexSegment(toolCallId));
5064
5023
  }
5065
5024
  function toolCallIndexPath2(resultsDir, toolCallId, runId) {
5066
- return path13.join(toolCallIndexDir3(resultsDir, toolCallId), encodedJsonFileName(runId));
5025
+ return path12.join(toolCallIndexDir3(resultsDir, toolCallId), encodedJsonFileName(runId));
5067
5026
  }
5068
5027
  function parseResultIndexEntry(value) {
5069
5028
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
@@ -5079,10 +5038,10 @@ function parseResultIndexEntry(value) {
5079
5038
  };
5080
5039
  }
5081
5040
  function writeResultIndexForData(resultPath, data) {
5082
- const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path13.basename(resultPath, ".json");
5041
+ const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
5083
5042
  const sessionId = nonEmptyString2(data.sessionId);
5084
5043
  if (!runId || !sessionId) return;
5085
- const file = path13.basename(resultPath);
5044
+ const file = path12.basename(resultPath);
5086
5045
  const entry = {
5087
5046
  version: RESULT_INDEX_VERSION,
5088
5047
  runId,
@@ -5091,7 +5050,7 @@ function writeResultIndexForData(resultPath, data) {
5091
5050
  writtenAt: Date.now(),
5092
5051
  ...nonEmptyString2(data.asyncDir) ? { asyncDir: nonEmptyString2(data.asyncDir) } : {}
5093
5052
  };
5094
- const resultsDir = path13.dirname(resultPath);
5053
+ const resultsDir = path12.dirname(resultPath);
5095
5054
  writeAtomicJson(resultIndexPath(resultsDir, sessionId, runId), entry);
5096
5055
  try {
5097
5056
  writeAtomicJson(runIndexPath(resultsDir, runId), entry);
@@ -5105,7 +5064,7 @@ function writeResultIndexForData(resultPath, data) {
5105
5064
  console.error(`Failed to write async result tool-call index for '${resultPath}':`, error);
5106
5065
  }
5107
5066
  try {
5108
- if (entry.asyncDir && fs12.existsSync(path13.join(entry.asyncDir, MISSION_BINDING_FILE))) {
5067
+ if (entry.asyncDir && fs11.existsSync(path12.join(entry.asyncDir, MISSION_BINDING_FILE))) {
5109
5068
  writeAtomicJson(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), entry);
5110
5069
  }
5111
5070
  } catch (error) {
@@ -5113,10 +5072,10 @@ function writeResultIndexForData(resultPath, data) {
5113
5072
  }
5114
5073
  }
5115
5074
  function writeIndexedPendingResultFile(resultPath, data) {
5116
- const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path13.basename(resultPath, ".json");
5075
+ const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
5117
5076
  const sessionId = nonEmptyString2(data.sessionId);
5118
5077
  if (!sessionId) throw new Error(`Cannot write async result '${resultPath}' without a sessionId.`);
5119
- const resultsDir = path13.dirname(resultPath);
5078
+ const resultsDir = path12.dirname(resultPath);
5120
5079
  let indexFailure;
5121
5080
  writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data, () => {
5122
5081
  try {
@@ -5130,54 +5089,54 @@ function writeIndexedPendingResultFile(resultPath, data) {
5130
5089
  }
5131
5090
  function writeAsyncResultFile(resultPath, data) {
5132
5091
  const { runId, sessionId, resultsDir } = writeIndexedPendingResultFile(resultPath, data);
5133
- return promotePendingResultFile(resultsDir, sessionId, runId, path13.basename(resultPath), { logFailure: false }) === "promoted" ? { state: "public" } : { state: "pending" };
5092
+ return promotePendingResultFile(resultsDir, sessionId, runId, path12.basename(resultPath), { logFailure: false }) === "promoted" ? { state: "public" } : { state: "pending" };
5134
5093
  }
5135
5094
  function removeResultIndex(resultsDir, sessionId, runId, toolCallId) {
5136
5095
  if (!runId) return;
5137
5096
  if (sessionId) {
5138
5097
  for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
5139
5098
  try {
5140
- fs12.rmSync(indexPath2, { force: true });
5099
+ fs11.rmSync(indexPath2, { force: true });
5141
5100
  } catch {
5142
5101
  }
5143
5102
  }
5144
5103
  for (const pendingPath of resultPendingPaths(resultsDir, sessionId, runId)) {
5145
5104
  try {
5146
- fs12.rmSync(pendingPath, { force: true });
5105
+ fs11.rmSync(pendingPath, { force: true });
5147
5106
  } catch {
5148
5107
  }
5149
5108
  }
5150
5109
  }
5151
5110
  try {
5152
- fs12.rmSync(runIndexPath(resultsDir, runId), { force: true });
5111
+ fs11.rmSync(runIndexPath(resultsDir, runId), { force: true });
5153
5112
  } catch {
5154
5113
  }
5155
5114
  if (toolCallId) {
5156
5115
  try {
5157
- fs12.rmSync(toolCallIndexPath2(resultsDir, toolCallId, runId), { force: true });
5116
+ fs11.rmSync(toolCallIndexPath2(resultsDir, toolCallId, runId), { force: true });
5158
5117
  } catch {
5159
5118
  }
5160
5119
  }
5161
5120
  try {
5162
- fs12.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
5121
+ fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
5163
5122
  } catch {
5164
5123
  }
5165
5124
  }
5166
5125
  function removeMissionObserverIndex(resultsDir, runId) {
5167
5126
  if (!runId) return;
5168
5127
  try {
5169
- fs12.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
5128
+ fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
5170
5129
  } catch {
5171
5130
  }
5172
5131
  }
5173
5132
  function withResultRunLease(resultsDir, runId, action, waitMs) {
5174
- const leaseDir = path13.join(resultsDir, RESULT_LEASE_DIR);
5175
- fs12.mkdirSync(leaseDir, { recursive: true });
5176
- return withFileLease(path13.join(leaseDir, createHash5("sha256").update(runId).digest("hex")), action, waitMs);
5133
+ const leaseDir = path12.join(resultsDir, RESULT_LEASE_DIR);
5134
+ fs11.mkdirSync(leaseDir, { recursive: true });
5135
+ return withFileLease(path12.join(leaseDir, createHash4("sha256").update(runId).digest("hex")), action, waitMs);
5177
5136
  }
5178
5137
  function readResultPayload(filePath) {
5179
5138
  try {
5180
- return fs12.readFileSync(filePath, "utf-8");
5139
+ return fs11.readFileSync(filePath, "utf-8");
5181
5140
  } catch (error) {
5182
5141
  const code = error.code;
5183
5142
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" || isUnaddressableResultCandidate(error)) return void 0;
@@ -5185,7 +5144,7 @@ function readResultPayload(filePath) {
5185
5144
  }
5186
5145
  }
5187
5146
  function resultPayloadCandidates(publicPath, read) {
5188
- return [...read.sessionId ? resultPendingPaths(path13.dirname(publicPath), read.sessionId, read.runId) : [], publicPath];
5147
+ return [...read.sessionId ? resultPendingPaths(path12.dirname(publicPath), read.sessionId, read.runId) : [], publicPath];
5189
5148
  }
5190
5149
  function readByConsumer(publicPath, read, candidate, current) {
5191
5150
  return current === read.snapshot || candidate === publicPath && current === read.stalePublic;
@@ -5197,10 +5156,10 @@ function resultSnapshotReplaced(publicPath, read) {
5197
5156
  });
5198
5157
  }
5199
5158
  function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseWaitMs) {
5200
- const resultsDir = path13.dirname(publicPath);
5159
+ const resultsDir = path12.dirname(publicPath);
5201
5160
  return withResultRunLease(resultsDir, read.runId, () => {
5202
5161
  if (resultSnapshotReplaced(publicPath, read)) {
5203
- if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs12.rmSync(payloadPath, { force: true });
5162
+ if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs11.rmSync(payloadPath, { force: true });
5204
5163
  return "replaced";
5205
5164
  }
5206
5165
  let removalFailure;
@@ -5208,7 +5167,7 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
5208
5167
  const current = readResultPayload(candidate);
5209
5168
  if (current === void 0 || !readByConsumer(publicPath, read, candidate, current)) continue;
5210
5169
  try {
5211
- fs12.rmSync(candidate, { force: true });
5170
+ fs11.rmSync(candidate, { force: true });
5212
5171
  } catch (error) {
5213
5172
  removalFailure ??= { error };
5214
5173
  }
@@ -5219,8 +5178,8 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
5219
5178
  }, leaseWaitMs);
5220
5179
  }
5221
5180
  function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
5222
- const resultsDir = path13.dirname(publicPath);
5223
- if (!fs12.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
5181
+ const resultsDir = path12.dirname(publicPath);
5182
+ if (!fs11.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
5224
5183
  return withResultRunLease(resultsDir, read.runId, () => {
5225
5184
  if (resultSnapshotReplaced(publicPath, read)) return "replaced";
5226
5185
  removeMissionObserverIndex(resultsDir, read.runId);
@@ -5229,7 +5188,7 @@ function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
5229
5188
  }
5230
5189
  function existingResultFile(resultPath) {
5231
5190
  try {
5232
- return fs12.statSync(resultPath).isFile();
5191
+ return fs11.statSync(resultPath).isFile();
5233
5192
  } catch (error) {
5234
5193
  if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
5235
5194
  return false;
@@ -5245,22 +5204,22 @@ function resultPayloadMatchesSessionRun(data, sessionId, runId) {
5245
5204
  }
5246
5205
  function pendingResultPayloadMatches(filePath, sessionId, runId) {
5247
5206
  try {
5248
- return resultPayloadMatchesSessionRun(JSON.parse(fs12.readFileSync(filePath, "utf-8")), sessionId, runId);
5207
+ return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
5249
5208
  } catch (error) {
5250
5209
  if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
5251
5210
  return false;
5252
5211
  }
5253
5212
  }
5254
5213
  function assertPendingResultPayloadMatches(filePath, sessionId, runId) {
5255
- return resultPayloadMatchesSessionRun(JSON.parse(fs12.readFileSync(filePath, "utf-8")), sessionId, runId);
5214
+ return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
5256
5215
  }
5257
5216
  function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFileName(runId), options = {}) {
5258
- if (file !== path13.basename(file) || !file.endsWith(".json")) return "none";
5217
+ if (file !== path12.basename(file) || !file.endsWith(".json")) return "none";
5259
5218
  const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
5260
5219
  if (!pendingPath) return "none";
5261
- const resultPath = path13.join(resultsDir, file);
5220
+ const resultPath = path12.join(resultsDir, file);
5262
5221
  try {
5263
- fs12.renameSync(pendingPath, resultPath);
5222
+ fs11.renameSync(pendingPath, resultPath);
5264
5223
  return existingResultFile(resultPath) ? "promoted" : "pending";
5265
5224
  } catch (error) {
5266
5225
  const code = error.code;
@@ -5280,7 +5239,7 @@ function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFil
5280
5239
  }
5281
5240
  }
5282
5241
  function pendingResultLocationForSessionRun(resultsDir, sessionId, runId, file = resultFileName(runId)) {
5283
- if (file !== path13.basename(file) || !file.endsWith(".json")) return void 0;
5242
+ if (file !== path12.basename(file) || !file.endsWith(".json")) return void 0;
5284
5243
  const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
5285
5244
  if (!pendingPath || !pendingResultPayloadMatches(pendingPath, sessionId, runId)) return void 0;
5286
5245
  return { file, path: pendingPath, state: "pending" };
@@ -5294,19 +5253,19 @@ function resultPayloadFileForSessionRun(resultsDir, sessionId, runId) {
5294
5253
  return firstExistingResultFile([...resultPendingPaths(resultsDir, sessionId, runId), resultFilePath(resultsDir, runId)]);
5295
5254
  }
5296
5255
  function resultPayloadLocationFromIndex(resultsDir, entry) {
5297
- if (entry.file !== path13.basename(entry.file) || !entry.file.endsWith(".json")) return void 0;
5256
+ if (entry.file !== path12.basename(entry.file) || !entry.file.endsWith(".json")) return void 0;
5298
5257
  const pendingState = promotePendingResultFile(resultsDir, entry.sessionId, entry.runId, entry.file);
5299
5258
  if (pendingState === "pending") {
5300
5259
  return pendingResultLocationForSessionRun(resultsDir, entry.sessionId, entry.runId, entry.file);
5301
5260
  }
5302
- const resultPath = path13.join(resultsDir, entry.file);
5261
+ const resultPath = path12.join(resultsDir, entry.file);
5303
5262
  if (pendingState === "promoted" || existingResultFile(resultPath)) return { file: entry.file, path: resultPath, state: "public" };
5304
5263
  return void 0;
5305
5264
  }
5306
5265
  function readResultIndexForSessionRun(resultsDir, sessionId, runId) {
5307
5266
  for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
5308
5267
  try {
5309
- const entry = parseResultIndexEntry(JSON.parse(fs12.readFileSync(indexPath2, "utf-8")));
5268
+ const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(indexPath2, "utf-8")));
5310
5269
  if (!entry || entry.sessionId !== sessionId || entry.runId !== runId) continue;
5311
5270
  return entry;
5312
5271
  } catch (error) {
@@ -5325,7 +5284,7 @@ function resultPayloadPathForSessionRun(resultsDir, sessionId, runId) {
5325
5284
  }
5326
5285
  function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
5327
5286
  try {
5328
- const entry = parseResultIndexEntry(JSON.parse(fs12.readFileSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), "utf-8")));
5287
+ const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), "utf-8")));
5329
5288
  if (!entry || entry.runId !== runId) return void 0;
5330
5289
  return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
5331
5290
  } catch (error) {
@@ -5337,9 +5296,9 @@ function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
5337
5296
  function resultPayloadPathForIndexedRun(resultsDir, runId) {
5338
5297
  const entryPath = runIndexPath(resultsDir, runId);
5339
5298
  try {
5340
- const entry = parseResultIndexEntry(JSON.parse(fs12.readFileSync(entryPath, "utf-8")));
5299
+ const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
5341
5300
  if (!entry || entry.runId !== runId) {
5342
- fs12.rmSync(entryPath, { force: true });
5301
+ fs11.rmSync(entryPath, { force: true });
5343
5302
  return void 0;
5344
5303
  }
5345
5304
  return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
@@ -5349,7 +5308,7 @@ function resultPayloadPathForIndexedRun(resultsDir, runId) {
5349
5308
  if (code !== "ENOENT" && code !== "ENOTDIR") {
5350
5309
  console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
5351
5310
  try {
5352
- fs12.rmSync(entryPath, { force: true });
5311
+ fs11.rmSync(entryPath, { force: true });
5353
5312
  } catch {
5354
5313
  }
5355
5314
  }
@@ -5364,7 +5323,7 @@ function indexedResultFile(resultsDir, entry, includePending = false) {
5364
5323
  function listIndexFiles(dir) {
5365
5324
  let files;
5366
5325
  try {
5367
- files = fs12.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path13.join(dir, entry.name));
5326
+ files = fs11.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path12.join(dir, entry.name));
5368
5327
  } catch (error) {
5369
5328
  const code = error.code;
5370
5329
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
@@ -5376,9 +5335,9 @@ function resultFilesFromIndexDir(resultsDir, dir, includePending = false) {
5376
5335
  const candidates = /* @__PURE__ */ new Set();
5377
5336
  for (const entryPath of listIndexFiles(dir)) {
5378
5337
  try {
5379
- const entry = parseResultIndexEntry(JSON.parse(fs12.readFileSync(entryPath, "utf-8")));
5338
+ const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
5380
5339
  if (!entry) {
5381
- fs12.rmSync(entryPath, { force: true });
5340
+ fs11.rmSync(entryPath, { force: true });
5382
5341
  continue;
5383
5342
  }
5384
5343
  const resultFile = indexedResultFile(resultsDir, entry, includePending);
@@ -5394,7 +5353,7 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
5394
5353
  for (const dir of pendingSessionDirs(resultsDir, sessionId)) {
5395
5354
  let entries;
5396
5355
  try {
5397
- entries = fs12.readdirSync(dir, { withFileTypes: true });
5356
+ entries = fs11.readdirSync(dir, { withFileTypes: true });
5398
5357
  } catch (error) {
5399
5358
  const code = error.code;
5400
5359
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
@@ -5402,9 +5361,9 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
5402
5361
  }
5403
5362
  for (const entry of entries) {
5404
5363
  if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
5405
- const pendingPath = path13.join(dir, entry.name);
5364
+ const pendingPath = path12.join(dir, entry.name);
5406
5365
  try {
5407
- const data = JSON.parse(fs12.readFileSync(pendingPath, "utf-8"));
5366
+ const data = JSON.parse(fs11.readFileSync(pendingPath, "utf-8"));
5408
5367
  const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id);
5409
5368
  if (runId && nonEmptyString2(data.sessionId) === sessionId) files.add(resultFileName(runId));
5410
5369
  } catch (error) {
@@ -5429,43 +5388,43 @@ function missionObserverResultCandidateFiles(resultsDir) {
5429
5388
  return resultFilesFromIndexDir(resultsDir, observerIndexDir(resultsDir, MISSION_OBSERVER), true);
5430
5389
  }
5431
5390
  function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 * 60 * 1e3) {
5432
- const root = path13.join(resultsDir, RESULT_INDEX_DIR);
5391
+ const root = path12.join(resultsDir, RESULT_INDEX_DIR);
5433
5392
  const cutoff = now - maxAgeMs;
5434
5393
  let removed = 0;
5435
5394
  const visit = (dir) => {
5436
5395
  let entries;
5437
5396
  try {
5438
- entries = fs12.readdirSync(dir, { withFileTypes: true });
5397
+ entries = fs11.readdirSync(dir, { withFileTypes: true });
5439
5398
  } catch (error) {
5440
5399
  const code = error.code;
5441
5400
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
5442
5401
  throw error;
5443
5402
  }
5444
5403
  for (const entry of entries) {
5445
- const fullPath = path13.join(dir, entry.name);
5404
+ const fullPath = path12.join(dir, entry.name);
5446
5405
  if (entry.isDirectory()) {
5447
5406
  visit(fullPath);
5448
5407
  try {
5449
- fs12.rmdirSync(fullPath);
5408
+ fs11.rmdirSync(fullPath);
5450
5409
  } catch {
5451
5410
  }
5452
5411
  continue;
5453
5412
  }
5454
5413
  if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
5455
5414
  try {
5456
- const stat = fs12.statSync(fullPath);
5457
- const index = parseResultIndexEntry(JSON.parse(fs12.readFileSync(fullPath, "utf-8")));
5415
+ const stat = fs11.statSync(fullPath);
5416
+ const index = parseResultIndexEntry(JSON.parse(fs11.readFileSync(fullPath, "utf-8")));
5458
5417
  const resultFile = index ? indexedResultFile(resultsDir, index) : void 0;
5459
5418
  const pendingFile = index ? pendingResultExists(resultsDir, index.sessionId, index.runId) : false;
5460
5419
  if (!index || !resultFile && !pendingFile && stat.mtimeMs <= cutoff) {
5461
- fs12.rmSync(fullPath, { force: true });
5420
+ fs11.rmSync(fullPath, { force: true });
5462
5421
  removed += 1;
5463
5422
  }
5464
5423
  } catch (error) {
5465
5424
  if (isUnaddressableResultCandidate(error)) continue;
5466
5425
  if (error.code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
5467
5426
  try {
5468
- fs12.rmSync(fullPath, { force: true });
5427
+ fs11.rmSync(fullPath, { force: true });
5469
5428
  removed += 1;
5470
5429
  } catch {
5471
5430
  }
@@ -5477,21 +5436,21 @@ function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 *
5477
5436
  }
5478
5437
 
5479
5438
  // src/shared/completion-owner.ts
5480
- import { randomUUID as randomUUID6 } from "node:crypto";
5439
+ import { randomUUID as randomUUID5 } from "node:crypto";
5481
5440
  var COMPLETION_OWNER_KEY = /* @__PURE__ */ Symbol.for("pi-subagents.completion-owner-id");
5482
5441
  var OWNING_SESSION_COMPLETION_OWNER = "owning-session";
5483
5442
  function currentCompletionOwnerId() {
5484
5443
  const runtime2 = globalThis;
5485
- runtime2[COMPLETION_OWNER_KEY] ??= randomUUID6();
5444
+ runtime2[COMPLETION_OWNER_KEY] ??= randomUUID5();
5486
5445
  return runtime2[COMPLETION_OWNER_KEY];
5487
5446
  }
5488
5447
 
5489
5448
  // src/runs/background/boot-id.ts
5490
5449
  import { execFileSync as execFileSync2 } from "node:child_process";
5491
- import * as fs14 from "node:fs";
5450
+ import * as fs13 from "node:fs";
5492
5451
 
5493
5452
  // src/runs/background/pid-namespace.ts
5494
- import * as fs13 from "node:fs";
5453
+ import * as fs12 from "node:fs";
5495
5454
  var resolved = false;
5496
5455
  var cachedScope;
5497
5456
  function currentPidNamespaceScope() {
@@ -5499,7 +5458,7 @@ function currentPidNamespaceScope() {
5499
5458
  resolved = true;
5500
5459
  if (process.platform !== "linux") return void 0;
5501
5460
  try {
5502
- const scope = fs13.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
5461
+ const scope = fs12.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
5503
5462
  cachedScope = scope || void 0;
5504
5463
  } catch {
5505
5464
  cachedScope = void 0;
@@ -5510,7 +5469,7 @@ function currentPidNamespaceScope() {
5510
5469
  // src/runs/background/boot-id.ts
5511
5470
  function readBootIdFromOs() {
5512
5471
  try {
5513
- if (process.platform === "linux") return fs14.readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || void 0;
5472
+ if (process.platform === "linux") return fs13.readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || void 0;
5514
5473
  if (process.platform === "darwin") {
5515
5474
  return execFileSync2("sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf-8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
5516
5475
  }
@@ -5535,8 +5494,8 @@ function currentRecordedPid() {
5535
5494
  }
5536
5495
 
5537
5496
  // src/runs/background/stale-run-reconciler.ts
5538
- import * as fs16 from "node:fs";
5539
- import * as path15 from "node:path";
5497
+ import * as fs15 from "node:fs";
5498
+ import * as path14 from "node:path";
5540
5499
 
5541
5500
  // src/runs/background/parallel-groups.ts
5542
5501
  function isValidParallelGroup(group, stepCount, chainStepCount) {
@@ -5577,16 +5536,16 @@ function isReusableWorkflowStopCause(cause) {
5577
5536
  }
5578
5537
 
5579
5538
  // src/runs/background/workflow-terminal-proof.ts
5580
- import * as fs15 from "node:fs";
5581
- import * as path14 from "node:path";
5539
+ import * as fs14 from "node:fs";
5540
+ import * as path13 from "node:path";
5582
5541
  var TERMINAL_WORKFLOW_STATES = /* @__PURE__ */ new Set(["completed", "failed", "stopped"]);
5583
5542
  function isTerminalAsyncState(state) {
5584
5543
  return state !== "queued" && state !== "running" && state !== "paused";
5585
5544
  }
5586
5545
  function readWorkflowChildRunModel(workflowAsyncDir, step) {
5587
- if (step.async !== true || typeof step.runId !== "string" || path14.basename(step.runId) !== step.runId) return void 0;
5546
+ if (step.async !== true || typeof step.runId !== "string" || path13.basename(step.runId) !== step.runId) return void 0;
5588
5547
  try {
5589
- const child = readStatus(path14.join(path14.dirname(workflowAsyncDir), step.runId));
5548
+ const child = readStatus(path13.join(path13.dirname(workflowAsyncDir), step.runId));
5590
5549
  const first = Array.isArray(child?.steps) ? child.steps[0] : void 0;
5591
5550
  const model = typeof first?.model === "string" && first.model ? first.model : void 0;
5592
5551
  const thinking = typeof first?.thinking === "string" && first.thinking ? first.thinking : void 0;
@@ -5615,15 +5574,15 @@ function readWorkflowChildProcessEvidence(workflowAsyncDir, steps) {
5615
5574
  }
5616
5575
  function launchFailedBeforeRunner(step, childDir) {
5617
5576
  if (step.status !== "failed" || !step.error) return false;
5618
- return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) => fs15.existsSync(path14.join(childDir, file)));
5577
+ return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) => fs14.existsSync(path13.join(childDir, file)));
5619
5578
  }
5620
5579
  function readWorkflowChildEvidence(workflowAsyncDir, step) {
5621
5580
  const label = step.workflowKey ?? step.agent;
5622
5581
  if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
5623
5582
  if (!step.async) return void 0;
5624
- if (!step.runId || path14.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
5625
- const childDir = path14.join(path14.dirname(workflowAsyncDir), step.runId);
5626
- if (!fs15.existsSync(childDir)) return launchFailedBeforeRunner(step) ? void 0 : { state: "unknown", reason: `async workflow child ${label} directory is missing` };
5583
+ if (!step.runId || path13.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
5584
+ const childDir = path13.join(path13.dirname(workflowAsyncDir), step.runId);
5585
+ if (!fs14.existsSync(childDir)) return launchFailedBeforeRunner(step) ? void 0 : { state: "unknown", reason: `async workflow child ${label} directory is missing` };
5627
5586
  const childStatus = readStatus(childDir);
5628
5587
  if (!childStatus) return launchFailedBeforeRunner(step, childDir) ? void 0 : { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
5629
5588
  if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
@@ -5666,21 +5625,21 @@ function getErrorMessage(error) {
5666
5625
  return error instanceof Error ? error.message : String(error);
5667
5626
  }
5668
5627
  function readRunnerStartupDiagnostics(asyncDir) {
5669
- const stderrPath = path15.join(asyncDir, "runner.stderr.log");
5628
+ const stderrPath = path14.join(asyncDir, "runner.stderr.log");
5670
5629
  const maxBytes = 64 * 1024;
5671
5630
  let content;
5672
5631
  try {
5673
- const stat = fs16.statSync(stderrPath);
5632
+ const stat = fs15.statSync(stderrPath);
5674
5633
  if (stat.size <= 0) return void 0;
5675
- const fd = fs16.openSync(stderrPath, "r");
5634
+ const fd = fs15.openSync(stderrPath, "r");
5676
5635
  try {
5677
5636
  const bytesToRead = Math.min(stat.size, maxBytes);
5678
5637
  const start = Math.max(0, stat.size - bytesToRead);
5679
5638
  const buffer = Buffer.alloc(bytesToRead);
5680
- fs16.readSync(fd, buffer, 0, bytesToRead, start);
5639
+ fs15.readSync(fd, buffer, 0, bytesToRead, start);
5681
5640
  content = buffer.toString("utf-8").trim();
5682
5641
  } finally {
5683
- fs16.closeSync(fd);
5642
+ fs15.closeSync(fd);
5684
5643
  }
5685
5644
  } catch {
5686
5645
  return void 0;
@@ -5695,15 +5654,15 @@ function isNotFoundError(error) {
5695
5654
  }
5696
5655
  function appendJsonlBestEffort(filePath, payload) {
5697
5656
  try {
5698
- fs16.mkdirSync(path15.dirname(filePath), { recursive: true });
5699
- fs16.appendFileSync(filePath, `${JSON.stringify(payload)}
5657
+ fs15.mkdirSync(path14.dirname(filePath), { recursive: true });
5658
+ fs15.appendFileSync(filePath, `${JSON.stringify(payload)}
5700
5659
  `, "utf-8");
5701
5660
  } catch {
5702
5661
  }
5703
5662
  }
5704
5663
  function regularFileExists(filePath) {
5705
5664
  try {
5706
- return fs16.statSync(filePath).isFile();
5665
+ return fs15.statSync(filePath).isFile();
5707
5666
  } catch (error) {
5708
5667
  if (isNotFoundError(error)) return false;
5709
5668
  throw error;
@@ -5711,7 +5670,7 @@ function regularFileExists(filePath) {
5711
5670
  }
5712
5671
  function readResultRepairData(resultPath) {
5713
5672
  try {
5714
- const data = JSON.parse(fs16.readFileSync(resultPath, "utf-8"));
5673
+ const data = JSON.parse(fs15.readFileSync(resultPath, "utf-8"));
5715
5674
  if (data.error !== void 0 && typeof data.error !== "string") throw new Error(`Invalid async result file '${resultPath}': error must be a string.`);
5716
5675
  const state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "rejected" ? "rejected" : data.state === "partial" ? "partial" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
5717
5676
  const results = Array.isArray(data.results) ? data.results.map((entry, index) => {
@@ -5785,7 +5744,7 @@ function buildStartedStatus(asyncDir, startedRun, now) {
5785
5744
  const chainStepCount = startedRun.chainStepCount;
5786
5745
  const parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
5787
5746
  return {
5788
- runId: startedRun.runId || path15.basename(asyncDir),
5747
+ runId: startedRun.runId || path14.basename(asyncDir),
5789
5748
  ...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
5790
5749
  ...startedRun.completionOwnerId ? { completionOwnerId: startedRun.completionOwnerId } : {},
5791
5750
  mode: startedRun.mode ?? "single",
@@ -5807,8 +5766,8 @@ function buildStartedStatus(asyncDir, startedRun, now) {
5807
5766
  }
5808
5767
  function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
5809
5768
  const childRunId = step.runId;
5810
- if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !== path15.basename(childRunId) || childRunId === "." || childRunId === "..") return void 0;
5811
- const child = readStatus(path15.join(path15.dirname(asyncDir), childRunId));
5769
+ if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !== path14.basename(childRunId) || childRunId === "." || childRunId === "..") return void 0;
5770
+ const child = readStatus(path14.join(path14.dirname(asyncDir), childRunId));
5812
5771
  if (!child || child.runId !== childRunId || child.parentWorkflowRunId !== workflowRunId || !isTerminalAsyncState(child.state)) return void 0;
5813
5772
  if (step.workflowKey !== void 0 && child.workflowKey !== step.workflowKey) return void 0;
5814
5773
  const state = child.state;
@@ -5829,7 +5788,7 @@ function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
5829
5788
  return settled;
5830
5789
  }
5831
5790
  function buildFailedRepair(status, asyncDir, now, reason, ownerExited = false, adoptCompletionOwnerId) {
5832
- const runId = status.runId || path15.basename(asyncDir);
5791
+ const runId = status.runId || path14.basename(asyncDir);
5833
5792
  const pid = typeof status.pid === "number" ? status.pid : "unknown";
5834
5793
  const exitedWorkflow = ownerExited && status.mode === "workflow" ? status.workflow : void 0;
5835
5794
  const completionOwnerId = exitedWorkflow ? adoptCompletionOwnerId || OWNING_SESSION_COMPLETION_OWNER : status.completionOwnerId;
@@ -5916,9 +5875,9 @@ ${diagnostics}` : baseMessage;
5916
5875
  function writeFailedRepair(asyncDir, status, resultPath, now, reason, ownerExited = false, adoptCompletionOwnerId) {
5917
5876
  const repair = buildFailedRepair(status, asyncDir, now, reason, ownerExited, adoptCompletionOwnerId);
5918
5877
  if (repair.result.sessionId) writeAsyncResultFile(resultPath, repair.result);
5919
- writeAtomicJson(path15.join(asyncDir, "status.json"), repair.status);
5878
+ writeAtomicJson(path14.join(asyncDir, "status.json"), repair.status);
5920
5879
  updateActiveRunIndex(asyncDir, repair.status.state, repair.status.toolCallId);
5921
- appendJsonlBestEffort(path15.join(asyncDir, "events.jsonl"), {
5880
+ appendJsonlBestEffort(path14.join(asyncDir, "events.jsonl"), {
5922
5881
  type: "subagent.run.repaired_stale",
5923
5882
  ts: now,
5924
5883
  runId: repair.status.runId,
@@ -5946,7 +5905,7 @@ function reconcileNestedAsyncDescendants(route, options = {}) {
5946
5905
  if (!asyncDir) continue;
5947
5906
  const result = reconcileAsyncRun(asyncDir, {
5948
5907
  ...options,
5949
- resultsDir: path15.join(options.resultsDir ?? DIRS.results, "nested", route.rootRunId)
5908
+ resultsDir: path14.join(options.resultsDir ?? DIRS.results, "nested", route.rootRunId)
5950
5909
  });
5951
5910
  const status = result.status;
5952
5911
  if (!status) continue;
@@ -5974,7 +5933,7 @@ function checkPidLiveness(pid, kill = process.kill, probeZombie = false) {
5974
5933
  kill(pid, 0);
5975
5934
  if (probeZombie && process.platform === "linux") {
5976
5935
  try {
5977
- const stat = fs16.readFileSync(`/proc/${pid}/stat`, "utf-8");
5936
+ const stat = fs15.readFileSync(`/proc/${pid}/stat`, "utf-8");
5978
5937
  const closeParen = stat.lastIndexOf(") ");
5979
5938
  if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
5980
5939
  } catch {
@@ -6008,19 +5967,28 @@ function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
6008
5967
  const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0;
6009
5968
  const effectiveStatus = status ?? startedStatus;
6010
5969
  if (!effectiveStatus) return { status: null, repaired: false };
6011
- assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path15.join(asyncDir, "status.json"), effectiveStatus.runId);
6012
- const statusPath = path15.join(asyncDir, "status.json");
5970
+ assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path14.join(asyncDir, "status.json"), effectiveStatus.runId);
5971
+ const statusPath = path14.join(asyncDir, "status.json");
6013
5972
  for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
6014
5973
  const stepRecord = step;
6015
5974
  if (stepRecord.model !== void 0 && typeof stepRecord.model !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
6016
5975
  if (stepRecord.thinking !== void 0 && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
6017
5976
  }
6018
- const runId = effectiveStatus.runId || path15.basename(asyncDir);
5977
+ const runId = effectiveStatus.runId || path14.basename(asyncDir);
6019
5978
  const resultsDir = options.resultsDir ?? DIRS.results;
6020
5979
  const resultPath = resultFilePath(resultsDir, runId);
6021
5980
  const existingResultPath = effectiveStatus.sessionId ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : void 0) : regularFileExists(resultPath) ? resultPath : void 0;
5981
+ const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1e3;
5982
+ const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
5983
+ const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
5984
+ const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
5985
+ kill: options.kill,
5986
+ observedScope,
5987
+ observedBootId: options.bootId ? options.bootId() : currentBootId()
5988
+ });
6022
5989
  if (existingResultPath) {
6023
- const terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued" ? terminalStatusFromResult(effectiveStatus, existingResultPath, now) : void 0;
5990
+ const runnerStillFinishing = effectiveStatus.state === "running" && effectiveStatus.mode !== "workflow" && typeof effectiveStatus.pid === "number" && effectiveStatus.pidNamespaceScope === observedScope && now - lastUpdate <= staleAfterMs && runnerLiveness(effectiveStatus.pid) === "alive";
5991
+ const terminalStatus = (effectiveStatus.state === "running" || effectiveStatus.state === "queued") && !runnerStillFinishing ? terminalStatusFromResult(effectiveStatus, existingResultPath, now) : void 0;
6024
5992
  if (terminalStatus) {
6025
5993
  const currentStatus = readStatus(asyncDir);
6026
5994
  const currentRootError = failureDiagnostic(currentStatus?.error);
@@ -6053,14 +6021,8 @@ function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
6053
6021
  return { status: null, repaired: false, resultPath };
6054
6022
  }
6055
6023
  }
6056
- const liveness = checkRecordedPidLiveness({ pid: effectiveStatus.pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
6057
- kill: options.kill,
6058
- observedScope: options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope(),
6059
- observedBootId: options.bootId ? options.bootId() : currentBootId()
6060
- });
6024
+ const liveness = runnerLiveness(effectiveStatus.pid);
6061
6025
  if (liveness !== "dead") {
6062
- const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1e3;
6063
- const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
6064
6026
  if (now - lastUpdate <= staleAfterMs) return { status: status ?? null, repaired: false, resultPath };
6065
6027
  const probe = liveness === "alive" ? "is still live" : "cannot be probed from this process";
6066
6028
  const message = `Async runner PID ${effectiveStatus.pid} ${probe}; status has not updated for ${now - lastUpdate}ms, so stale-run reconciliation marked the run failed because PID ownership is unverified.`;
@@ -6112,19 +6074,19 @@ function validateAuthorityPolicy(value, label = "config.authorityPolicy") {
6112
6074
  }
6113
6075
 
6114
6076
  // src/runs/shared/worktree.ts
6115
- import { createHash as createHash6 } from "node:crypto";
6077
+ import { createHash as createHash5 } from "node:crypto";
6116
6078
  import { spawnSync } from "node:child_process";
6117
6079
 
6118
6080
  // src/runs/shared/worktree-setup-command.ts
6119
6081
  import { spawn as spawn2 } from "node:child_process";
6120
6082
  function terminateCommandTree(pid, controller) {
6121
6083
  if (process.platform !== "win32") return controller.terminate();
6122
- return new Promise((resolve6) => {
6084
+ return new Promise((resolve5) => {
6123
6085
  let settled = false;
6124
6086
  const fallback = () => {
6125
6087
  if (settled) return;
6126
6088
  settled = true;
6127
- void controller.terminate().then(resolve6);
6089
+ void controller.terminate().then(resolve5);
6128
6090
  };
6129
6091
  const cleanup = spawn2("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
6130
6092
  cleanup.once("error", fallback);
@@ -6132,7 +6094,7 @@ function terminateCommandTree(pid, controller) {
6132
6094
  if (settled) return;
6133
6095
  if (status !== 0) return fallback();
6134
6096
  settled = true;
6135
- resolve6({ state: "observed", mechanism: "windows-taskkill", pid, verifiedAt: Date.now() });
6097
+ resolve5({ state: "observed", mechanism: "windows-taskkill", pid, verifiedAt: Date.now() });
6136
6098
  });
6137
6099
  });
6138
6100
  }
@@ -6234,21 +6196,21 @@ async function runSetupCommand(command, args, options) {
6234
6196
  child.stdout.on("data", onStdout);
6235
6197
  child.stderr.on("data", onStderr);
6236
6198
  child.stdin.on("error", fail);
6237
- const close = new Promise((resolve6) => child.once("close", () => resolve6()));
6238
- const directExit = new Promise((resolve6) => {
6199
+ const close = new Promise((resolve5) => child.once("close", () => resolve5()));
6200
+ const directExit = new Promise((resolve5) => {
6239
6201
  child.once("exit", (status, signal) => {
6240
6202
  directSettled = true;
6241
6203
  result.status = status;
6242
6204
  result.signal = signal;
6243
6205
  if (status === null || !(options.acceptedExitCodes ?? [0]).includes(status)) terminate();
6244
6206
  releaseUnknownIO();
6245
- resolve6();
6207
+ resolve5();
6246
6208
  });
6247
6209
  child.once("error", (error) => {
6248
6210
  fail(error);
6249
6211
  if (child.pid === void 0) {
6250
6212
  directSettled = true;
6251
- resolve6();
6213
+ resolve5();
6252
6214
  }
6253
6215
  });
6254
6216
  });
@@ -6296,13 +6258,13 @@ async function runSetupCommand(command, args, options) {
6296
6258
  }
6297
6259
 
6298
6260
  // src/runs/shared/worktree.ts
6299
- import * as fs17 from "node:fs";
6261
+ import * as fs16 from "node:fs";
6300
6262
  import * as os2 from "node:os";
6301
- import * as path16 from "node:path";
6263
+ import * as path15 from "node:path";
6302
6264
  var DEFAULT_WORKTREE_PROVIDER = "auto";
6303
6265
  var DEFAULT_WORKTREE_BASE_REF = "HEAD";
6304
6266
  var DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
6305
- var WORKTREE_AGENT_CWD_PLACEHOLDER = path16.join(path16.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
6267
+ var WORKTREE_AGENT_CWD_PLACEHOLDER = path15.join(path15.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
6306
6268
  var WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
6307
6269
  var WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
6308
6270
  var WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
@@ -6331,8 +6293,8 @@ function assertWorktreeMutationAllowed() {
6331
6293
  async function withWorktreeTransaction(action) {
6332
6294
  const previous = worktreeTurn;
6333
6295
  let release;
6334
- worktreeTurn = new Promise((resolve6) => {
6335
- release = resolve6;
6296
+ worktreeTurn = new Promise((resolve5) => {
6297
+ release = resolve5;
6336
6298
  });
6337
6299
  await previous;
6338
6300
  try {
@@ -6436,7 +6398,7 @@ function findListedWorktreeAgentCwd(repoCwd, branch) {
6436
6398
  const worktree = findListedWorktreeOnBranch(repoCwd, branch);
6437
6399
  if (!worktree) return void 0;
6438
6400
  const cwdRelative = resolveRepoCwdRelative(repoCwd);
6439
- return cwdRelative ? path16.join(worktree, cwdRelative) : worktree;
6401
+ return cwdRelative ? path15.join(worktree, cwdRelative) : worktree;
6440
6402
  }
6441
6403
  function isComparablePathInside(parent, child) {
6442
6404
  return isPathInside(normalizeComparableCwd(parent), normalizeComparableCwd(child));
@@ -6450,11 +6412,11 @@ function currentWorktreePatch(worktreePath, baseCommit) {
6450
6412
  assertWorktreeMutationAllowed();
6451
6413
  let tempDir;
6452
6414
  try {
6453
- tempDir = fs17.mkdtempSync(path16.join(os2.tmpdir(), "pi-worktree-index-"));
6415
+ tempDir = fs16.mkdtempSync(path15.join(os2.tmpdir(), "pi-worktree-index-"));
6454
6416
  } catch (error) {
6455
6417
  return { error: error instanceof Error ? error.message : String(error) };
6456
6418
  }
6457
- const env = { GIT_INDEX_FILE: path16.join(tempDir, "index") };
6419
+ const env = { GIT_INDEX_FILE: path15.join(tempDir, "index") };
6458
6420
  try {
6459
6421
  const readTree = runGit(worktreePath, ["read-tree", "HEAD"], env);
6460
6422
  if (readTree.status !== 0) return { error: readTree.stderr.trim() || readTree.stdout.trim() || "git read-tree failed" };
@@ -6465,7 +6427,7 @@ function currentWorktreePatch(worktreePath, baseCommit) {
6465
6427
  return { patch: diff.stdout };
6466
6428
  } finally {
6467
6429
  try {
6468
- fs17.rmSync(tempDir, { recursive: true, force: true });
6430
+ fs16.rmSync(tempDir, { recursive: true, force: true });
6469
6431
  } catch {
6470
6432
  }
6471
6433
  }
@@ -6475,7 +6437,7 @@ function validateWorktreePatchRepresentsCurrentWorktree(worktreePath, baseCommit
6475
6437
  if (validationError) return validationError;
6476
6438
  let capturedPatch;
6477
6439
  try {
6478
- capturedPatch = fs17.readFileSync(patchPath, "utf-8");
6440
+ capturedPatch = fs16.readFileSync(patchPath, "utf-8");
6479
6441
  } catch (error) {
6480
6442
  return error instanceof Error ? error.message : String(error);
6481
6443
  }
@@ -6508,7 +6470,7 @@ async function preflightWorktreeSource(cwd, options = {}) {
6508
6470
  async function resolveRepoState(tx, cwd, requestedBaseRef) {
6509
6471
  const toplevel = await probeWorktreeSource(tx, cwd);
6510
6472
  const rawPrefix = (await tx.gitChecked(cwd, ["rev-parse", "--show-prefix"])).trim();
6511
- const cwdRelative = rawPrefix ? path16.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
6473
+ const cwdRelative = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
6512
6474
  const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
6513
6475
  let baseCommit;
6514
6476
  try {
@@ -6522,22 +6484,22 @@ async function resolveRepoState(tx, cwd, requestedBaseRef) {
6522
6484
  return { toplevel, cwdRelative, baseCommit };
6523
6485
  }
6524
6486
  function normalizeComparableCwd(cwd) {
6525
- const resolved2 = path16.resolve(cwd);
6487
+ const resolved2 = path15.resolve(cwd);
6526
6488
  let existing = resolved2;
6527
6489
  const missingSegments = [];
6528
6490
  while (true) {
6529
6491
  try {
6530
6492
  let realpath;
6531
6493
  try {
6532
- realpath = fs17.realpathSync.native(existing);
6494
+ realpath = fs16.realpathSync.native(existing);
6533
6495
  } catch {
6534
- realpath = fs17.realpathSync(existing);
6496
+ realpath = fs16.realpathSync(existing);
6535
6497
  }
6536
- return path16.join(realpath, ...missingSegments.reverse());
6498
+ return path15.join(realpath, ...missingSegments.reverse());
6537
6499
  } catch {
6538
- const parent = path16.dirname(existing);
6500
+ const parent = path15.dirname(existing);
6539
6501
  if (parent === existing) return resolved2;
6540
- missingSegments.push(path16.basename(existing));
6502
+ missingSegments.push(path15.basename(existing));
6541
6503
  existing = parent;
6542
6504
  }
6543
6505
  }
@@ -6546,7 +6508,7 @@ function safePatchAgentName(agent) {
6546
6508
  return agent.replace(/[^\w.-]/g, "_");
6547
6509
  }
6548
6510
  function shortWorktreeHash(value) {
6549
- return createHash6("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
6511
+ return createHash5("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
6550
6512
  }
6551
6513
  function truncateUtf8(value, maxBytes) {
6552
6514
  const bytes = Buffer.from(value, "utf-8");
@@ -6631,7 +6593,7 @@ function hasConfiguredWorktreeBaseDir(baseDir) {
6631
6593
  return baseDir !== void 0 ? true : (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
6632
6594
  }
6633
6595
  function isInsidePiExtensionsDirectory(targetPath) {
6634
- const extensionsDir = normalizeComparableCwd(path16.join(getAgentDir(), "extensions"));
6596
+ const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
6635
6597
  return isPathInside(extensionsDir, normalizeComparableCwd(targetPath));
6636
6598
  }
6637
6599
  function runWorktrunk(args, cwd) {
@@ -6713,49 +6675,49 @@ function resolveWorktreeDedicatedRoot(configuredBaseDir, repoRoot, relocateExten
6713
6675
  const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
6714
6676
  let expanded;
6715
6677
  if (rawBaseDir === void 0 || configuredBaseDir === void 0 && !rawBaseDir.trim()) {
6716
- expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ? path16.join(getAgentDir(), "worktrees") : path16.join(path16.dirname(repoRoot), "worktrees");
6678
+ expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ? path15.join(getAgentDir(), "worktrees") : path15.join(path15.dirname(repoRoot), "worktrees");
6717
6679
  } else {
6718
6680
  const trimmed = rawBaseDir.trim();
6719
6681
  if (!trimmed) throw new Error("worktree base directory cannot be empty");
6720
- const candidate = trimmed.startsWith("~/") ? path16.join(os2.homedir(), trimmed.slice(2)) : trimmed;
6721
- expanded = path16.isAbsolute(candidate) ? candidate : path16.resolve(repoRoot, candidate);
6682
+ const candidate = trimmed.startsWith("~/") ? path15.join(os2.homedir(), trimmed.slice(2)) : trimmed;
6683
+ expanded = path15.isAbsolute(candidate) ? candidate : path15.resolve(repoRoot, candidate);
6722
6684
  }
6723
- const extensionsDir = normalizeComparableCwd(path16.join(getAgentDir(), "extensions"));
6685
+ const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
6724
6686
  if (isPathInside(extensionsDir, normalizeComparableCwd(expanded))) {
6725
6687
  throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
6726
6688
  }
6727
6689
  return expanded;
6728
6690
  }
6729
6691
  function buildNativeProjectPath(dedicatedRoot, repoRoot) {
6730
- return path16.join(dedicatedRoot, path16.basename(repoRoot));
6692
+ return path15.join(dedicatedRoot, path15.basename(repoRoot));
6731
6693
  }
6732
6694
  function ensureProjectWorktreeDir(dedicatedRoot, repoRoot) {
6733
6695
  try {
6734
- fs17.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
6696
+ fs16.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
6735
6697
  } catch (error) {
6736
6698
  const message = error instanceof Error ? error.message : String(error);
6737
6699
  throw new Error(`failed to create worktree base directory ${dedicatedRoot}: ${message}`);
6738
6700
  }
6739
6701
  }
6740
6702
  function buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index) {
6741
- return path16.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
6703
+ return path15.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
6742
6704
  }
6743
6705
  function isPathInside(parent, child) {
6744
- const relative4 = path16.relative(parent, child);
6706
+ const relative4 = path15.relative(parent, child);
6745
6707
  if (!relative4 || relative4 === ".") return true;
6746
- return relative4 !== ".." && !relative4.startsWith(`..${path16.sep}`) && !path16.isAbsolute(relative4);
6708
+ return relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
6747
6709
  }
6748
6710
  function isStrictChildPath(parent, child) {
6749
- const relative4 = path16.relative(parent, child);
6750
- return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${path16.sep}`) && !path16.isAbsolute(relative4);
6711
+ const relative4 = path15.relative(parent, child);
6712
+ return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
6751
6713
  }
6752
6714
  function assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot) {
6753
6715
  const resolvedLeaf = normalizeComparableCwd(worktreePath);
6754
6716
  const resolvedRepoRoot = normalizeComparableCwd(repoRoot);
6755
6717
  const projectDir = normalizeComparableCwd(buildNativeProjectPath(dedicatedRoot, repoRoot));
6756
- const repoParent = normalizeComparableCwd(path16.dirname(resolvedRepoRoot));
6757
- const leafParent = normalizeComparableCwd(path16.dirname(resolvedLeaf));
6758
- const extensionsDir = normalizeComparableCwd(path16.join(getAgentDir(), "extensions"));
6718
+ const repoParent = normalizeComparableCwd(path15.dirname(resolvedRepoRoot));
6719
+ const leafParent = normalizeComparableCwd(path15.dirname(resolvedLeaf));
6720
+ const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
6759
6721
  if (isPathInside(extensionsDir, projectDir) || isPathInside(extensionsDir, resolvedLeaf)) {
6760
6722
  throw new Error(`worktree path cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
6761
6723
  }
@@ -6775,7 +6737,7 @@ function resolveRepoCwdRelative(cwd) {
6775
6737
  throw new Error("worktree isolation requires a git repository");
6776
6738
  }
6777
6739
  const rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim();
6778
- const normalizedPrefix = rawPrefix ? path16.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
6740
+ const normalizedPrefix = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
6779
6741
  return normalizedPrefix === "." ? "" : normalizedPrefix;
6780
6742
  }
6781
6743
  function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
@@ -6784,14 +6746,14 @@ function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
6784
6746
  const dedicatedRoot = resolveWorktreeDedicatedRoot(baseDir, repoRoot);
6785
6747
  const worktreePath = buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index);
6786
6748
  assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot);
6787
- return cwdRelative ? path16.join(worktreePath, cwdRelative) : worktreePath;
6749
+ return cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath;
6788
6750
  }
6789
6751
  function linkNodeModulesIfPresent(toplevel, worktreePath) {
6790
- const nodeModulesPath = path16.join(toplevel, "node_modules");
6791
- const nodeModulesLinkPath = path16.join(worktreePath, "node_modules");
6752
+ const nodeModulesPath = path15.join(toplevel, "node_modules");
6753
+ const nodeModulesLinkPath = path15.join(worktreePath, "node_modules");
6792
6754
  const hasDirectoryEntry = (candidate) => {
6793
6755
  try {
6794
- fs17.lstatSync(candidate);
6756
+ fs16.lstatSync(candidate);
6795
6757
  return true;
6796
6758
  } catch (error) {
6797
6759
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
@@ -6802,14 +6764,14 @@ function linkNodeModulesIfPresent(toplevel, worktreePath) {
6802
6764
  if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
6803
6765
  let sourceRealPath;
6804
6766
  try {
6805
- if (!fs17.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
6806
- sourceRealPath = fs17.realpathSync.native(nodeModulesPath);
6767
+ if (!fs16.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
6768
+ sourceRealPath = fs16.realpathSync.native(nodeModulesPath);
6807
6769
  } catch (error) {
6808
6770
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
6809
6771
  throw error;
6810
6772
  }
6811
- fs17.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
6812
- if (!fs17.lstatSync(nodeModulesLinkPath).isSymbolicLink() || fs17.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
6773
+ fs16.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
6774
+ if (!fs16.lstatSync(nodeModulesLinkPath).isSymbolicLink() || fs16.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
6813
6775
  throw new Error("created link does not resolve to the source node_modules");
6814
6776
  }
6815
6777
  return true;
@@ -6834,19 +6796,19 @@ function resolveWorktreeSetupHook(repoRoot, config) {
6834
6796
  if (!hookPath) {
6835
6797
  throw new Error("worktree setup hook path cannot be empty");
6836
6798
  }
6837
- const expandedHookPath = hookPath.startsWith("~/") ? path16.join(os2.homedir(), hookPath.slice(2)) : hookPath;
6799
+ const expandedHookPath = hookPath.startsWith("~/") ? path15.join(os2.homedir(), hookPath.slice(2)) : hookPath;
6838
6800
  let resolvedPath;
6839
- if (path16.isAbsolute(expandedHookPath)) {
6801
+ if (path15.isAbsolute(expandedHookPath)) {
6840
6802
  resolvedPath = expandedHookPath;
6841
6803
  } else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\")) {
6842
- resolvedPath = path16.resolve(repoRoot, expandedHookPath);
6804
+ resolvedPath = path15.resolve(repoRoot, expandedHookPath);
6843
6805
  } else {
6844
6806
  throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
6845
6807
  }
6846
- if (!fs17.existsSync(resolvedPath)) {
6808
+ if (!fs16.existsSync(resolvedPath)) {
6847
6809
  throw new Error(`worktree setup hook not found: ${resolvedPath}`);
6848
6810
  }
6849
- if (fs17.statSync(resolvedPath).isDirectory()) {
6811
+ if (fs16.statSync(resolvedPath).isDirectory()) {
6850
6812
  throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
6851
6813
  }
6852
6814
  return {
@@ -6857,16 +6819,16 @@ function resolveWorktreeSetupHook(repoRoot, config) {
6857
6819
  function normalizeSyntheticPath(worktreePath, rawPath) {
6858
6820
  const trimmed = rawPath.trim();
6859
6821
  if (!trimmed) throw new Error("synthetic path cannot be empty");
6860
- if (path16.isAbsolute(trimmed)) throw new Error(`synthetic path must be relative: ${rawPath}`);
6861
- const resolved2 = path16.resolve(worktreePath, trimmed);
6862
- const relative4 = path16.relative(worktreePath, resolved2);
6822
+ if (path15.isAbsolute(trimmed)) throw new Error(`synthetic path must be relative: ${rawPath}`);
6823
+ const resolved2 = path15.resolve(worktreePath, trimmed);
6824
+ const relative4 = path15.relative(worktreePath, resolved2);
6863
6825
  if (!relative4 || relative4 === ".") {
6864
6826
  throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
6865
6827
  }
6866
- if (relative4 === ".." || relative4.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative4)) {
6828
+ if (relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
6867
6829
  throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
6868
6830
  }
6869
- return path16.normalize(relative4);
6831
+ return path15.normalize(relative4);
6870
6832
  }
6871
6833
  function parseWorktreeSetupHookOutput(rawStdout) {
6872
6834
  const trimmed = rawStdout.trim();
@@ -6920,7 +6882,7 @@ async function runWorktreeSetupHook(tx, hook, input) {
6920
6882
  }
6921
6883
  }
6922
6884
  async function finalizeCreatedWorktree(tx, toplevel, cwdRelative, runId, baseCommit, setupHook, agent, worktree) {
6923
- const agentCwd = cwdRelative ? path16.join(worktree.path, cwdRelative) : worktree.path;
6885
+ const agentCwd = cwdRelative ? path15.join(worktree.path, cwdRelative) : worktree.path;
6924
6886
  tx.check();
6925
6887
  const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
6926
6888
  const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
@@ -6947,7 +6909,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
6947
6909
  const branch = await tx.git(toplevel, ["show-ref", "--verify", "--quiet", `refs/heads/${naming.requestedBranch}`], [0, 1]);
6948
6910
  let pathExists = false;
6949
6911
  try {
6950
- fs17.lstatSync(worktreePath);
6912
+ fs16.lstatSync(worktreePath);
6951
6913
  pathExists = true;
6952
6914
  } catch (error) {
6953
6915
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
@@ -6955,7 +6917,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
6955
6917
  if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
6956
6918
  tx.attempt(index, naming.requestedBranch, worktreePath);
6957
6919
  ensureProjectWorktreeDir(dedicatedRoot, toplevel);
6958
- const recordedBaseDir = normalizeComparableCwd(path16.dirname(worktreePath));
6920
+ const recordedBaseDir = normalizeComparableCwd(path15.dirname(worktreePath));
6959
6921
  await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
6960
6922
  const worktree = {
6961
6923
  path: worktreePath,
@@ -6995,11 +6957,11 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
6995
6957
  if (output.action !== "created" || output.created_branch !== true || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
6996
6958
  throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
6997
6959
  }
6998
- if (typeof output.path !== "string" || !path16.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
6999
- const worktreePathCandidate = path16.resolve(output.path);
6960
+ if (typeof output.path !== "string" || !path15.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
6961
+ const worktreePathCandidate = path15.resolve(output.path);
7000
6962
  let stat;
7001
6963
  try {
7002
- stat = fs17.lstatSync(worktreePathCandidate);
6964
+ stat = fs16.lstatSync(worktreePathCandidate);
7003
6965
  } catch (error) {
7004
6966
  throw new Error(`Worktrunk provisioning returned a missing worktree path: ${worktreePathCandidate}`, { cause: error instanceof Error ? error : void 0 });
7005
6967
  }
@@ -7008,8 +6970,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
7008
6970
  if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
7009
6971
  const sourceCommonDirRaw = (await tx.gitChecked(toplevel, ["rev-parse", "--git-common-dir"])).trim();
7010
6972
  const returnedCommonDirRaw = (await tx.gitChecked(worktreePath, ["rev-parse", "--git-common-dir"])).trim();
7011
- const sourceCommonDir = normalizeComparableCwd(path16.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path16.resolve(toplevel, sourceCommonDirRaw));
7012
- const returnedCommonDir = normalizeComparableCwd(path16.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path16.resolve(worktreePath, returnedCommonDirRaw));
6973
+ const sourceCommonDir = normalizeComparableCwd(path15.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path15.resolve(toplevel, sourceCommonDirRaw));
6974
+ const returnedCommonDir = normalizeComparableCwd(path15.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path15.resolve(worktreePath, returnedCommonDirRaw));
7013
6975
  if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
7014
6976
  const returnedBranch = (await tx.gitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"])).trim();
7015
6977
  if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
@@ -7017,8 +6979,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
7017
6979
  if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
7018
6980
  const worktree = {
7019
6981
  path: worktreePath,
7020
- recordedBaseDir: normalizeComparableCwd(path16.dirname(worktreePath)),
7021
- agentCwd: cwdRelative ? path16.join(worktreePath, cwdRelative) : worktreePath,
6982
+ recordedBaseDir: normalizeComparableCwd(path15.dirname(worktreePath)),
6983
+ agentCwd: cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath,
7022
6984
  branch: naming.requestedBranch,
7023
6985
  index,
7024
6986
  nodeModulesLinked: false,
@@ -7035,28 +6997,28 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
7035
6997
  }
7036
6998
  function removeSyntheticPath(worktree, syntheticPath) {
7037
6999
  assertWorktreeMutationAllowed();
7038
- const resolved2 = path16.resolve(worktree.path, syntheticPath);
7039
- const relative4 = path16.relative(worktree.path, resolved2);
7040
- if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative4)) {
7000
+ const resolved2 = path15.resolve(worktree.path, syntheticPath);
7001
+ const relative4 = path15.relative(worktree.path, resolved2);
7002
+ if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
7041
7003
  return;
7042
7004
  }
7043
7005
  let stat;
7044
7006
  try {
7045
- stat = fs17.lstatSync(resolved2);
7007
+ stat = fs16.lstatSync(resolved2);
7046
7008
  } catch (error) {
7047
7009
  const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
7048
7010
  if (code === "ENOENT") return;
7049
7011
  throw error;
7050
7012
  }
7051
7013
  if (stat.isSymbolicLink()) {
7052
- fs17.unlinkSync(resolved2);
7014
+ fs16.unlinkSync(resolved2);
7053
7015
  return;
7054
7016
  }
7055
7017
  if (stat.isDirectory()) {
7056
- fs17.rmSync(resolved2, { recursive: true, force: true });
7018
+ fs16.rmSync(resolved2, { recursive: true, force: true });
7057
7019
  return;
7058
7020
  }
7059
- fs17.rmSync(resolved2, { force: true });
7021
+ fs16.rmSync(resolved2, { force: true });
7060
7022
  }
7061
7023
  function removeSyntheticPathsBeforeDiff(worktree) {
7062
7024
  if (worktree.syntheticPaths.length === 0) return;
@@ -7100,7 +7062,7 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
7100
7062
  const diffStat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--stat", setup.baseCommit]).trim();
7101
7063
  const patch = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, setup.baseCommit]);
7102
7064
  const numstat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--numstat", setup.baseCommit]);
7103
- fs17.writeFileSync(patchPath, patch, "utf-8");
7065
+ fs16.writeFileSync(patchPath, patch, "utf-8");
7104
7066
  if (!patch.trim()) {
7105
7067
  return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
7106
7068
  }
@@ -7120,18 +7082,18 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
7120
7082
  }
7121
7083
  function writeEmptyPatch(patchPath) {
7122
7084
  try {
7123
- fs17.writeFileSync(patchPath, "", "utf-8");
7085
+ fs16.writeFileSync(patchPath, "", "utf-8");
7124
7086
  } catch {
7125
7087
  }
7126
7088
  }
7127
7089
  function handoffRecordsPatch(manifestPath, patchPath) {
7128
- if (!manifestPath || !fs17.existsSync(manifestPath)) return false;
7090
+ if (!manifestPath || !fs16.existsSync(manifestPath)) return false;
7129
7091
  try {
7130
- const manifest = JSON.parse(fs17.readFileSync(manifestPath, "utf-8"));
7092
+ const manifest = JSON.parse(fs16.readFileSync(manifestPath, "utf-8"));
7131
7093
  if (manifest.version !== 1 || !Array.isArray(manifest.groups)) return false;
7132
- const resolvedPatchPath = path16.resolve(patchPath);
7094
+ const resolvedPatchPath = path15.resolve(patchPath);
7133
7095
  return manifest.groups.some((group) => Array.isArray(group.children) && group.children.some(
7134
- (child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" && path16.resolve(child.patch.path) === resolvedPatchPath
7096
+ (child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" && path15.resolve(child.patch.path) === resolvedPatchPath
7135
7097
  ));
7136
7098
  } catch {
7137
7099
  return false;
@@ -7184,9 +7146,9 @@ function cleanupSingleWorktree(setup, worktree, intent) {
7184
7146
  const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
7185
7147
  let patchValidationError;
7186
7148
  let patchCaptured = false;
7187
- if (captured !== void 0 && captured.error === void 0 && fs17.existsSync(captured.patchPath) && handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath)) {
7149
+ if (captured !== void 0 && captured.error === void 0 && fs16.existsSync(captured.patchPath) && handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath)) {
7188
7150
  try {
7189
- if (fs17.statSync(captured.patchPath).size > 0) {
7151
+ if (fs16.statSync(captured.patchPath).size > 0) {
7190
7152
  patchValidationError = validateWorktreePatchRepresentsCurrentWorktree(worktree.path, setup.baseCommit, captured.patchPath);
7191
7153
  patchCaptured = patchValidationError === void 0;
7192
7154
  }
@@ -7316,7 +7278,7 @@ async function compensateSetup(tx) {
7316
7278
  throw new Error(tx.progress.unknown);
7317
7279
  }
7318
7280
  await git(["worktree", "remove", "--force", attempt.path]);
7319
- } else if (fs17.existsSync(attempt.path)) {
7281
+ } else if (fs16.existsSync(attempt.path)) {
7320
7282
  tx.unknown("Unregistered partial allocation retained");
7321
7283
  throw new Error(tx.progress.unknown);
7322
7284
  }
@@ -7436,7 +7398,7 @@ async function createWorktrees(cwd, runId, count, options = {}) {
7436
7398
  function diffWorktrees(setup, agents, diffsDir) {
7437
7399
  assertWorktreeMutationAllowed();
7438
7400
  try {
7439
- fs17.mkdirSync(diffsDir, { recursive: true });
7401
+ fs16.mkdirSync(diffsDir, { recursive: true });
7440
7402
  } catch {
7441
7403
  return [];
7442
7404
  }
@@ -7444,7 +7406,7 @@ function diffWorktrees(setup, agents, diffsDir) {
7444
7406
  for (let index = 0; index < setup.worktrees.length; index++) {
7445
7407
  const worktree = setup.worktrees[index];
7446
7408
  const agent = agents[index] ?? `task-${index + 1}`;
7447
- const patchPath = path16.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
7409
+ const patchPath = path15.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
7448
7410
  try {
7449
7411
  diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
7450
7412
  } catch (error) {
@@ -7491,7 +7453,7 @@ function formatWorktreeDiffSummary(diffs) {
7491
7453
  }
7492
7454
  lines.push("");
7493
7455
  }
7494
- const patchesDir = path16.dirname(changed[0].patchPath);
7456
+ const patchesDir = path15.dirname(changed[0].patchPath);
7495
7457
  lines.push(`Full patches: ${patchesDir}`);
7496
7458
  return lines.join("\n").trimEnd();
7497
7459
  }