opencode-model-router 2.8.0 → 2.9.0

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 (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -63,6 +63,7 @@ import { fileKeyOfId } from "./baseline";
63
63
  import { isTestPath } from "./risk";
64
64
  import { DEFAULT_MATERIALIZE_TIMEOUT_MS, gcStaleReferences, materialize, nodeReferenceFs } from "./reference";
65
65
  import { acquireSlot, type SlotHandle } from "./slot";
66
+ import type { ServiceObservation } from "../executor/observations";
66
67
 
67
68
  // ---------------------------------------------------------------------------
68
69
  // MutexRegistry — per-key serialization via promise-chaining
@@ -848,6 +849,7 @@ export interface CheckScope extends VerificationScope {
848
849
  export type OpenCheckScope = (meta: Parameters<OpenVerificationScope>[0]) => CheckScope;
849
850
 
850
851
  export interface ScopeOpenerDeps {
852
+ service?: ServiceObservation;
851
853
  argv: ArgvSeam;
852
854
  exec: ExecSeam;
853
855
  fs: RunnerFs;
@@ -958,6 +960,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
958
960
  // at the deadline, even when the wait's own timer fires a few ms before remaining() reads 0.
959
961
  const waitMs = deadline.bound(budget.slotWaitMs);
960
962
  const cutByDeadline = waitMs < budget.slotWaitMs;
963
+ const wait = deps.service?.start("service-wait", "verification-slot");
961
964
  try {
962
965
  const r = await acquire({
963
966
  max: budget.maxConcurrentVerifications,
@@ -967,21 +970,25 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
967
970
  onLost,
968
971
  });
969
972
  if ("busy" in r) {
973
+ wait?.end("busy");
970
974
  return {
971
975
  ok: false,
972
976
  outcome: { kind: "slot-busy", waitedMs: Math.max(0, now() - started), deadlineCut: cutByDeadline || deadline.remaining() === 0 },
973
977
  };
974
978
  }
979
+ wait?.end("acquired");
975
980
  return { ok: true, handle: r };
976
981
  } catch (err) {
977
982
  return { ok: false, outcome: { kind: "error", reason: `verification slot failed: ${errorText(err)}` } };
978
- }
983
+ } finally { wait?.end("error"); }
979
984
  };
980
985
 
981
986
  const attempt = async (
982
987
  deadline: Deadline,
983
988
  launch: (opts: ExecOptions) => Promise<ExecResult>,
984
989
  ownMs: number = checkTimeoutMs,
990
+ stage = "command",
991
+ candidate?: string,
985
992
  ): Promise<Blocked | Spawned> => {
986
993
  if (closed) return { kind: "error", reason: "verification scope already closed" };
987
994
  holdP ??= acquireHold(deadline);
@@ -997,12 +1004,15 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
997
1004
  deadline.signal.addEventListener("abort", onAbort, { once: true });
998
1005
  let execResult: ExecResult;
999
1006
  let threw: string | undefined;
1007
+ const service = deps.service?.execution(stage, candidate);
1000
1008
  try {
1001
- execResult = await launch({ lowPriority: budget.lowPriority, signal: run.signal, timeoutMs: boundMs });
1009
+ execResult = await launch({ lowPriority: budget.lowPriority, signal: run.signal, timeoutMs: boundMs,
1010
+ ...(service === undefined ? {} : { service }) });
1011
+ service?.end(run.signal.aborted ? "interrupted" : execResult.timedOut ? "timed-out" : execResult.code === 0 ? "pass" : "fail");
1002
1012
  } catch (err) {
1003
1013
  threw = errorText(err);
1004
1014
  execResult = { code: -1, stdout: "", stderr: threw };
1005
- }
1015
+ } finally { service?.end("error"); }
1006
1016
  deadline.signal.removeEventListener("abort", onAbort);
1007
1017
  if (threw !== undefined || execResult.timedOut === true) {
1008
1018
  run.abort(new Error(threw ?? `run exceeded its ${boundMs}ms bound`));
@@ -1060,6 +1070,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1060
1070
  liveCwd: string,
1061
1071
  failingFiles: readonly string[],
1062
1072
  rd: Deadline,
1073
+ candidate: string,
1063
1074
  ): Promise<RecheckOutcome> => {
1064
1075
  if (!ref.exact) return { kind: "approximate", inexactReasons: ref.inexactReasons };
1065
1076
  const platform = host?.platform ?? process.platform;
@@ -1098,7 +1109,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1098
1109
  const a = await attempt(
1099
1110
  rd,
1100
1111
  opts => argv(spec.file, spec.args, { ...opts, cwd: spec.cwd, env: { ...spec.env } }),
1101
- budget.recheckTimeoutMs,
1112
+ budget.recheckTimeoutMs, "recheck", candidate,
1102
1113
  );
1103
1114
  if (a.kind === "aborted") return { kind: "skipped-deadline", remainingMs: rd.remaining() };
1104
1115
  if (a.kind === "slot-busy") return unusable("error", "the verification slot was not available for the recheck");
@@ -1153,6 +1164,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1153
1164
  }
1154
1165
 
1155
1166
  const rd = deriveDeadline(deadline, budget.recheckTimeoutMs, { now });
1167
+ const preparation = deps.service?.start("service-prep", "reference-materialization");
1156
1168
  try {
1157
1169
  // QA-1.5-10: GC, then materialize, both inside the hold.
1158
1170
  const gc = await seams.gcStaleReferences(reference.root, { ...refDeps, timeoutMs: rd.bound(RECHECK_GC_MS) });
@@ -1170,13 +1182,15 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1170
1182
  : unusable("materialize-failed", `materialize ${m.reason}: ${m.detail}`);
1171
1183
  }
1172
1184
  const ref = m.reference;
1185
+ preparation?.end("completed");
1173
1186
  try {
1174
- return await rerunAt(ref, runner, liveCwd, failingFiles, rd);
1187
+ return await rerunAt(ref, runner, liveCwd, failingFiles, rd, reference.commit);
1175
1188
  } finally {
1176
1189
  // T4.l: the rerun tree has exited here; close() waits for this before releasing the slot.
1177
1190
  track(ref.dispose().catch((err: unknown) => logger?.warn(`reference dispose failed: ${errorText(err)}`)));
1178
1191
  }
1179
1192
  } finally {
1193
+ preparation?.end("error");
1180
1194
  rd.dispose();
1181
1195
  }
1182
1196
  };
@@ -1231,6 +1245,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1231
1245
  // -----------------------------------------------------------------------------------------------
1232
1246
 
1233
1247
  export interface DirectTestsPassHookDeps {
1248
+ service?: ServiceObservation;
1234
1249
  openScope: OpenCheckScope;
1235
1250
  /** Built in wiring.ts (2.1.3, T9). */
1236
1251
  plannerFs: PlannerFs;
@@ -1440,9 +1455,11 @@ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsP
1440
1455
  return async (req): Promise<TestsPassRun> => {
1441
1456
  let scope: CheckScope | undefined;
1442
1457
  let scoped: ScopedOutcome | undefined;
1458
+ const preparation = deps.service?.start("service-prep", "test-planning");
1443
1459
  try {
1444
1460
  if (req.testScope === "full") {
1445
1461
  scope = deps.openScope({ cwd: req.cwd, command: req.command });
1462
+ preparation?.end("completed");
1446
1463
  scoped = await runFull(req, scope);
1447
1464
  } else {
1448
1465
  // Cross-repo P3a (D23): a cross-link request also passes W's ignored modules (its build output), or is S6 without them.
@@ -1468,6 +1485,7 @@ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsP
1468
1485
  return { scoped: { kind: "unverifiable", code: planned.code, reason: planned.reason }, recheck: undefined };
1469
1486
  }
1470
1487
  scope = deps.openScope({ cwd: req.cwd, command: req.command });
1488
+ preparation?.end("completed");
1471
1489
  scoped = await scope.execute(planned, req.deadline);
1472
1490
  }
1473
1491
  return { scoped, recheck: await recheckFor(req, scope, scoped) };
@@ -1476,6 +1494,7 @@ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsP
1476
1494
  if (scoped !== undefined) return { scoped, recheck: { kind: "unusable", cause: "error", reason: `the reference recheck errored: ${reason}` } };
1477
1495
  return { scoped: { kind: "error", reason: `testsPass hook errored: ${reason}` }, recheck: undefined };
1478
1496
  } finally {
1497
+ preparation?.end(scoped === undefined ? "no-run" : "error");
1479
1498
  if (scope !== undefined) await closeWithinDeadline(scope, req.deadline, deps.logger);
1480
1499
  }
1481
1500
  };
@@ -1879,9 +1898,14 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
1879
1898
  }
1880
1899
 
1881
1900
  switch (check.kind) {
1882
- case "fileExists":
1883
- result = await runFileExists(check, cd);
1901
+ case "fileExists": {
1902
+ const service = cd.service?.start("service", "file-exists");
1903
+ try {
1904
+ result = await runFileExists(check, cd);
1905
+ service?.end(result.ok ? "pass" : result.unverifiable ? "unverifiable" : "fail");
1906
+ } finally { service?.end("error"); }
1884
1907
  break;
1908
+ }
1885
1909
  case "run":
1886
1910
  result = await runRun(check, cd, allowlist, timeoutMs);
1887
1911
  break;
@@ -1890,9 +1914,14 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
1890
1914
  case "lintClean":
1891
1915
  result = await runCommandCheck(check, check.kind, cd, allowlist, timeoutMs, placement?.scope, crossLink);
1892
1916
  break;
1893
- case "schemaMatch":
1894
- result = await runSchemaMatch(check, cd);
1917
+ case "schemaMatch": {
1918
+ const service = cd.service?.start("service", "schema-match");
1919
+ try {
1920
+ result = await runSchemaMatch(check, cd);
1921
+ service?.end(result.ok ? "pass" : result.unverifiable ? "unverifiable" : "fail");
1922
+ } finally { service?.end("error"); }
1895
1923
  break;
1924
+ }
1896
1925
  default: {
1897
1926
  // Defensive: TypeScript proves this is unreachable; guards runtime extensions.
1898
1927
  const exhaustive: never = check.kind;
@@ -13,13 +13,15 @@ import type { DoD, InferHints } from "./dod";
13
13
  import { isIncompleteReason } from "./checker";
14
14
  import { stripDispatchHeader } from "../router/dispatch-header";
15
15
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
16
- import { basename, dirname, join, resolve } from "node:path";
17
- import { existsSync, realpathSync } from "node:fs";
16
+ import { resolve } from "node:path";
17
+ import { existsSync } from "node:fs";
18
+ import { canonicalPath } from "./canonical-path";
18
19
  import type { ReferenceState, Verdict } from "./types";
19
20
  import type { DispatchReference } from "./reference";
20
21
  import { REFERENCE_NONE } from "./baseline";
21
22
  import { neutralizeDirectives } from "./pending";
22
23
  import { withTimeout } from "./timeout";
24
+ import { applyPatchHeaderPaths } from "../router/tool-paths";
23
25
  import type { HeadRead } from "./head";
24
26
 
25
27
  export interface TreeSnapshot {
@@ -152,29 +154,8 @@ function none(reason: string): ReferenceState {
152
154
  return { kind: "none", reason };
153
155
  }
154
156
 
155
- /**
156
- * QA-2.1-8: the canonical spelling of `path`, so a Windows 8.3 short name (`C:\Users\MARQUI~1\…`),
157
- * a junction or symlink alias, and the long real path of one file key the same change-set entry.
158
- * The native realpath of the path, or of its nearest existing ancestor with the missing tail
159
- * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
160
- * ancestor resolves.
161
- */
162
- export function canonicalPath(path: string): string {
163
- const absolute = resolve(path);
164
- let head = absolute;
165
- const tail: string[] = [];
166
- for (;;) {
167
- try {
168
- const real = realpathSync.native(head);
169
- return tail.length === 0 ? real : join(real, ...tail.reverse());
170
- } catch {
171
- const parent = dirname(head);
172
- if (parent === head) return absolute;
173
- tail.push(basename(head));
174
- head = parent;
175
- }
176
- }
177
- }
157
+ // QA-2.1-8 / QA-1.3-16: canonicalPath lives in the leaf module canonical-path.ts; re-exported for every caller.
158
+ export { canonicalPath };
178
159
 
179
160
  /** A change-set key: the canonical path with "/" separators, case-folded on win32. */
180
161
  function pathKey(path: string): string {
@@ -263,6 +244,20 @@ export interface ChangedFile {
263
244
  previousPath?: string;
264
245
  }
265
246
 
247
+ /**
248
+ * Phase 2.1.4.b: the change set of a dispatch, computed when its child ends (captureDelta) so a background
249
+ * completion verifies what the child changed, not what the tree holds when the processor finally runs.
250
+ */
251
+ export interface DispatchDelta {
252
+ readonly callID: string;
253
+ readonly childSessionID: string;
254
+ /** Files attributed to the dispatch; "unavailable" when attribution failed (never [] for a failure). */
255
+ readonly files: readonly ChangedFile[] | "unavailable";
256
+ /** Set when a foreign write contaminated the dispatch's snapshot (the change set is then unavailable). */
257
+ readonly contaminatedBy?: string;
258
+ readonly capturedAt: number;
259
+ }
260
+
266
261
  /** Derive a {path,status} record from a write/edit tool call, or null. */
267
262
  export function extractChangedFile(tool: string, args: unknown): ChangedFile | null {
268
263
  const name = tool.toLowerCase();
@@ -709,6 +704,16 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
709
704
  baselineHead(id: string): Promise<HeadRead> | undefined {
710
705
  return dispatches.get(id)?.head;
711
706
  },
707
+ /**
708
+ * QA-SYNC1-3: the unattributed writers `delta(id, childID)` would report (sorted), read without joining `childID` to the
709
+ * lineage: a held registration journals them, so the gate re-run after a restart keeps them.
710
+ */
711
+ unattributedWritersOf(id: string, childID: string): string[] {
712
+ const d = dispatches.get(id);
713
+ const writers = new Set<string>(d ? d.writers : []);
714
+ for (const producer of d ? [...d.producers, childID] : [childID]) for (const tool of writersBySession.get(producer) ?? []) writers.add(tool);
715
+ return [...writers].sort();
716
+ },
712
717
  /**
713
718
  * QA-3.1-2: how many other dispatches were live at some moment of this one's window so far and
714
719
  * work in the git tree at `root` (default: this dispatch's own root, else its cwd). Their edits
@@ -744,10 +749,8 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
744
749
  writersBySession.set(sessionID, w);
745
750
  }
746
751
  if (tool.toLowerCase() === "apply_patch") {
747
- const a = args && typeof args === "object" ? args as Record<string, unknown> : {};
748
- const patch = typeof a.patchText === "string" ? a.patchText : typeof a.patch === "string" ? a.patch : "";
749
752
  const files = bySession.get(sessionID) ?? new Map<string, string>();
750
- for (const match of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)) files.set(match[1].trim(), "modified");
753
+ for (const p of applyPatchHeaderPaths(args)) files.set(p, "modified");
751
754
  bySession.set(sessionID, files);
752
755
  }
753
756
  const cf = extractChangedFile(tool, args);
@@ -766,6 +769,39 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
766
769
  if (!m) return [];
767
770
  return [...m.entries()].map(([path, status]) => ({ path, status }));
768
771
  },
772
+ /**
773
+ * Phase 2.1.4.b: freezes the files the child changed so far (the tool calls observed in its session)
774
+ * at child end. A contaminated dispatch snapshot makes the set "unavailable", as the foreground gate
775
+ * treats it. Pure read: the child's record stays until clear(). QA-2.1-7: the dispatch record is keyed by its dispatch
776
+ * id (`task:<parent>:<callID>`), which the caller passes as `dispatchID`; it defaults to `callID`.
777
+ */
778
+ captureDelta(callID: string, childSessionID: string, dispatchID: string = callID): DispatchDelta {
779
+ const contaminatedBy = dispatches.get(dispatchID)?.snapshotContaminatedBy;
780
+ const files = contaminatedBy !== undefined ? "unavailable" : [...(bySession.get(childSessionID)?.entries() ?? [])].map(
781
+ ([path, status]): ChangedFile => ({ path, status }),
782
+ );
783
+ return {
784
+ callID,
785
+ childSessionID,
786
+ files,
787
+ ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
788
+ capturedAt: now(),
789
+ };
790
+ },
791
+ /**
792
+ * QA-2.1-17 (v2 only): a gate re-run after a restart has no observed tool calls for the child; the change set the
793
+ * restored pending entry persisted at child end is put back under the child's session, so the gate verifies what
794
+ * the child changed instead of a read-only delegation. Merges with anything recorded since.
795
+ */
796
+ seed(sessionID: string, files: readonly ChangedFile[]): void {
797
+ touch(sessionID);
798
+ let m = bySession.get(sessionID);
799
+ if (!m) {
800
+ m = new Map();
801
+ bySession.set(sessionID, m);
802
+ }
803
+ for (const file of files) if (!m.has(file.path)) m.set(file.path, file.status);
804
+ },
769
805
  clear(sessionID: string): void {
770
806
  evict(sessionID);
771
807
  },
@@ -42,9 +42,10 @@
42
42
  * Windows what an already-exited direct child left running (only the sweep
43
43
  * reaches that).
44
44
  */
45
- import { execFile, spawn, spawnSync, type ChildProcess } from "node:child_process";
45
+ import { execFile, spawn, spawnSync, type ChildProcess, type SpawnOptions } from "node:child_process";
46
46
  import { constants as osConstants, setPriority, tmpdir } from "node:os";
47
47
  import { join } from "node:path";
48
+ import type { SlotEnv } from "../executor/slots/env";
48
49
  import type { ArgvSeam, ExecOptions, ExecSeam } from "./types";
49
50
 
50
51
  export interface ShellResult {
@@ -77,6 +78,14 @@ export interface RunOptions extends ExecOptions {
77
78
  maxBuffer?: number;
78
79
  }
79
80
 
81
+ /** A diagnostic hook must never affect spawning, cancellation or settlement (including injected hooks). */
82
+ function observeProcess(opts: RunOptions, event: "prepare" | "start" | "end", result = "error"): void {
83
+ try {
84
+ if (event === "end") opts.service?.end(result);
85
+ else opts.service?.[event]();
86
+ } catch { /* Diagnostics only. */ }
87
+ }
88
+
80
89
  export const DEFAULT_TIMEOUT_MS = 120_000;
81
90
  /** After a kill, the longest the result waits for the output pipes to close. */
82
91
  export const KILL_GRACE_MS = 2000;
@@ -122,6 +131,7 @@ const DEFAULT_POWERSHELL = SYSTEM32 ? join(SYSTEM32, "WindowsPowerShell", "v1.0"
122
131
 
123
132
  /** Run `command` through the platform shell (`cmd.exe` / `/bin/sh`). */
124
133
  export function runShell(command: string, opts: RunOptions = {}): Promise<ShellResult> {
134
+ observeProcess(opts, "prepare");
125
135
  // POSIX low priority: `nice -n 10 -- /bin/sh -c <command>` is exactly what
126
136
  // `shell: true` would spawn, just prefixed, so the command string keeps its
127
137
  // shell semantics and is never re-quoted. niceness is inherited by every
@@ -153,7 +163,11 @@ const BATCH_REFUSED = "exec failed: Error: spawn EINVAL (batch files must run th
153
163
  * the argv adapters pass absolute `.js`/`.exe` targets.
154
164
  */
155
165
  export function runArgv(file: string, args: readonly string[], opts: RunOptions = {}): Promise<ShellResult> {
156
- if (isWin && BATCH_FILE.test(file)) return Promise.resolve({ code: 1, stdout: "", stderr: BATCH_REFUSED, timedOut: false });
166
+ observeProcess(opts, "prepare");
167
+ if (isWin && BATCH_FILE.test(file)) {
168
+ observeProcess(opts, "end");
169
+ return Promise.resolve({ code: 1, stdout: "", stderr: BATCH_REFUSED, timedOut: false });
170
+ }
157
171
  // `--` keeps a target whose name starts with "-" from being read as a nice option.
158
172
  if (opts.lowPriority && !isWin) return run("nice", ["-n", "10", "--", file, ...args], false, opts, file);
159
173
  return run(file, [...args], false, opts);
@@ -168,7 +182,10 @@ export const argvSeam: ArgvSeam = runArgv;
168
182
  * reports a target it cannot exec as exit 127/126 instead of a spawn error.
169
183
  */
170
184
  function run(file: string, args: string[], shell: boolean, opts: RunOptions, niceTarget?: string): Promise<ShellResult> {
171
- if (opts.signal?.aborted) return Promise.resolve({ code: 1, stdout: "", stderr: "", timedOut: true });
185
+ if (opts.signal?.aborted) {
186
+ observeProcess(opts, "end", "interrupted");
187
+ return Promise.resolve({ code: 1, stdout: "", stderr: "", timedOut: true });
188
+ }
172
189
  const deadline = deadlineOf(opts);
173
190
  return new Promise((resolve) => {
174
191
  const limit = opts.maxBuffer === undefined || Number.isNaN(opts.maxBuffer) ? DEFAULT_MAX_BUFFER : Math.max(0, opts.maxBuffer);
@@ -194,16 +211,19 @@ function run(file: string, args: string[], shell: boolean, opts: RunOptions, nic
194
211
  const spawnedAt = Date.now();
195
212
  let child: ChildProcess;
196
213
  try {
197
- child = spawn(file, args, {
214
+ const spawnOptions: SpawnOptions = {
198
215
  cwd: opts.cwd,
199
- env: mergeEnv(opts.env),
216
+ env: opts.envMode === "replace" ? { ...opts.env } : mergeEnv(opts.env, opts.cwd),
200
217
  shell,
201
218
  windowsHide: true,
202
219
  // Its own process group on POSIX, so the whole tree can be signalled at once.
203
220
  detached: !isWin,
204
221
  stdio: ["ignore", "pipe", "pipe"],
205
- });
222
+ };
223
+ observeProcess(opts, "start");
224
+ child = spawn(file, args, spawnOptions);
206
225
  } catch (e) {
226
+ observeProcess(opts, "end");
207
227
  resolve({ code: 1, stdout: "", stderr: `exec failed: ${String(e)}`, timedOut: false });
208
228
  return;
209
229
  }
@@ -240,6 +260,7 @@ function run(file: string, args: string[], shell: boolean, opts: RunOptions, nic
240
260
  const finish = (code: number | null, error?: unknown) => {
241
261
  if (settled) return;
242
262
  settled = true;
263
+ observeProcess(opts, "end", opts.signal?.aborted ? "interrupted" : killed ? "timed-out" : error ? "error" : code === 0 ? "pass" : "fail");
243
264
  clearTimeout(timer);
244
265
  clearTimeout(grace);
245
266
  clearTimeout(armTimer);
@@ -387,15 +408,37 @@ export function deadlineOf(opts: RunOptions): number | undefined {
387
408
  return Math.min(Math.max(t, 0), MAX_TIMER_MS);
388
409
  }
389
410
 
411
+ interface SlotEnvHook {
412
+ slotEnvFor(cwd: string, platform: NodeJS.Platform): SlotEnv | null;
413
+ applySlotEnv(env: NodeJS.ProcessEnv, s: SlotEnv | null, platform: NodeJS.Platform): NodeJS.ProcessEnv;
414
+ }
415
+
416
+ /**
417
+ * The slot-environment functions executor/slots/env.ts publishes when it loads. This file
418
+ * is also loaded alone by Node's type stripping (no module resolution beyond node:
419
+ * built-ins), so it reads the hook from globalThis instead of importing the module. Absent
420
+ * (v1, or no executor loaded), nothing changes.
421
+ */
422
+ function slotEnvHook(): SlotEnvHook | null {
423
+ const hook: unknown = Reflect.get(globalThis, Symbol.for("omr.executor.slotEnvHook"));
424
+ if (typeof hook !== "object" || hook === null) return null;
425
+ const find: unknown = Reflect.get(hook, "slotEnvFor");
426
+ const apply: unknown = Reflect.get(hook, "applySlotEnv");
427
+ return typeof find === "function" && typeof apply === "function" ? (hook as SlotEnvHook) : null;
428
+ }
429
+
390
430
  /**
391
431
  * Overrides merged over process.env. Windows environment names are
392
432
  * case-insensitive and Node keeps only one of two keys that differ in case
393
433
  * (the first in sort order, not the override), so an inherited key that
394
434
  * matches an override case-insensitively is dropped first.
395
435
  */
396
- function mergeEnv(overrides: Record<string, string> | undefined): NodeJS.ProcessEnv {
397
- if (!overrides) return process.env;
398
- const env: NodeJS.ProcessEnv = { ...process.env };
436
+ function mergeEnv(overrides: Record<string, string> | undefined, cwd?: string): NodeJS.ProcessEnv {
437
+ const hook = cwd === undefined ? null : slotEnvHook();
438
+ const slot = hook === null || cwd === undefined ? null : hook.slotEnvFor(cwd, process.platform);
439
+ if (!slot && !overrides) return process.env;
440
+ const env: NodeJS.ProcessEnv = slot && hook ? hook.applySlotEnv({ ...process.env }, slot, process.platform) : { ...process.env };
441
+ if (!overrides) return env;
399
442
  for (const [key, value] of Object.entries(overrides)) {
400
443
  if (isWin) {
401
444
  const upper = key.toUpperCase();