@martinloop/mcp 0.3.9 → 0.5.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 (96) hide show
  1. package/README.md +82 -141
  2. package/dist/discovery-metadata.d.ts +1 -1
  3. package/dist/discovery-metadata.js +1 -1
  4. package/dist/resources.d.ts +1 -2
  5. package/dist/resources.js +47 -95
  6. package/dist/server-validation.d.ts +1 -1
  7. package/dist/server-validation.js +16 -11
  8. package/dist/server.d.ts +23 -0
  9. package/dist/server.js +152 -7
  10. package/dist/tools/preflight.d.ts +2 -0
  11. package/dist/tools/preflight.js +42 -2
  12. package/dist/tools/run-dossier.d.ts +3 -1
  13. package/dist/tools/run-dossier.js +40 -2
  14. package/dist/tools/run-loop.d.ts +1 -4
  15. package/dist/tools/run-loop.js +6 -15
  16. package/dist/tools/tool-support.d.ts +2 -1
  17. package/dist/tools/tool-support.js +1 -12
  18. package/dist/vendor/adapters/claude-cli.js +38 -35
  19. package/dist/vendor/adapters/cli-bridge.d.ts +9 -1
  20. package/dist/vendor/adapters/cli-bridge.js +54 -13
  21. package/dist/vendor/adapters/codex-launcher.d.ts +61 -1
  22. package/dist/vendor/adapters/codex-launcher.js +118 -19
  23. package/dist/vendor/adapters/index.d.ts +1 -3
  24. package/dist/vendor/adapters/index.js +1 -3
  25. package/dist/vendor/adapters/openai-compatible.js +51 -12
  26. package/dist/vendor/contracts/adapter-capabilities.d.ts +1 -1
  27. package/dist/vendor/contracts/context-handoff.d.ts +100 -0
  28. package/dist/vendor/contracts/context-handoff.js +11 -0
  29. package/dist/vendor/contracts/context-manifest.d.ts +195 -0
  30. package/dist/vendor/contracts/context-manifest.js +17 -0
  31. package/dist/vendor/contracts/context-shadow.d.ts +75 -0
  32. package/dist/vendor/contracts/context-shadow.js +8 -0
  33. package/dist/vendor/contracts/delivery.d.ts +47 -0
  34. package/dist/vendor/contracts/delivery.js +18 -0
  35. package/dist/vendor/contracts/exits.d.ts +126 -0
  36. package/dist/vendor/contracts/exits.js +32 -0
  37. package/dist/vendor/contracts/index.d.ts +41 -2
  38. package/dist/vendor/contracts/index.js +24 -0
  39. package/dist/vendor/contracts/mission.d.ts +102 -0
  40. package/dist/vendor/contracts/mission.js +64 -0
  41. package/dist/vendor/contracts/operator.d.ts +3 -1
  42. package/dist/vendor/contracts/operator.js +2 -1
  43. package/dist/vendor/contracts/verified-handoff.d.ts +100 -0
  44. package/dist/vendor/contracts/verified-handoff.js +35 -0
  45. package/dist/vendor/core/context-chain-gate.d.ts +89 -0
  46. package/dist/vendor/core/context-chain-gate.js +173 -0
  47. package/dist/vendor/core/context-compiler.d.ts +53 -0
  48. package/dist/vendor/core/context-compiler.js +261 -0
  49. package/dist/vendor/core/context-handoff.d.ts +42 -0
  50. package/dist/vendor/core/context-handoff.js +167 -0
  51. package/dist/vendor/core/context-shadow.d.ts +39 -0
  52. package/dist/vendor/core/context-shadow.js +200 -0
  53. package/dist/vendor/core/delivery/index.d.ts +6 -0
  54. package/dist/vendor/core/delivery/index.js +4 -0
  55. package/dist/vendor/core/delivery/message-client.d.ts +18 -0
  56. package/dist/vendor/core/delivery/message-client.js +38 -0
  57. package/dist/vendor/core/delivery/message-ledger.d.ts +35 -0
  58. package/dist/vendor/core/delivery/message-ledger.js +97 -0
  59. package/dist/vendor/core/delivery/message-schema.d.ts +16 -0
  60. package/dist/vendor/core/delivery/message-schema.js +111 -0
  61. package/dist/vendor/core/delivery/update-check.d.ts +19 -0
  62. package/dist/vendor/core/delivery/update-check.js +107 -0
  63. package/dist/vendor/core/exit-signal.d.ts +88 -0
  64. package/dist/vendor/core/exit-signal.js +339 -0
  65. package/dist/vendor/core/exits.d.ts +41 -0
  66. package/dist/vendor/core/exits.js +258 -0
  67. package/dist/vendor/core/index.d.ts +44 -1
  68. package/dist/vendor/core/index.js +1088 -662
  69. package/dist/vendor/core/mission/aggregate.d.ts +27 -0
  70. package/dist/vendor/core/mission/aggregate.js +42 -0
  71. package/dist/vendor/core/mission/index.d.ts +2 -0
  72. package/dist/vendor/core/mission/index.js +1 -0
  73. package/dist/vendor/core/persistence/compiler.d.ts +8 -0
  74. package/dist/vendor/core/persistence/compiler.js +156 -0
  75. package/dist/vendor/core/persistence/context-handoff-store.d.ts +68 -0
  76. package/dist/vendor/core/persistence/context-handoff-store.js +112 -0
  77. package/dist/vendor/core/persistence/index.d.ts +4 -0
  78. package/dist/vendor/core/persistence/index.js +2 -0
  79. package/dist/vendor/core/persistence/ledger.d.ts +1 -1
  80. package/dist/vendor/core/persistence/mission-store.d.ts +56 -0
  81. package/dist/vendor/core/persistence/mission-store.js +281 -0
  82. package/dist/vendor/core/policy.d.ts +2 -0
  83. package/dist/vendor/core/policy.js +5 -2
  84. package/dist/vendor/core/rollback.js +15 -1
  85. package/dist/vendor/core/savings.d.ts +13 -0
  86. package/dist/vendor/core/savings.js +22 -0
  87. package/dist/vendor/core/termination-store.d.ts +15 -0
  88. package/dist/vendor/core/termination-store.js +44 -0
  89. package/dist/vendor/core/verified-handoff.d.ts +67 -0
  90. package/dist/vendor/core/verified-handoff.js +210 -0
  91. package/package.json +3 -13
  92. package/server.json +3 -3
  93. package/dist/vendor/adapters/stub-agent-cli.d.ts +0 -8
  94. package/dist/vendor/adapters/stub-agent-cli.js +0 -40
  95. package/dist/vendor/adapters/verifier-only.d.ts +0 -9
  96. package/dist/vendor/adapters/verifier-only.js +0 -63
@@ -11,8 +11,8 @@
11
11
  *
12
12
  * MCP tools and integration tests use the same factories.
13
13
  */
14
- import { readGitExecutionArtifacts, resolveGitRepositoryRoot, runSubprocess, runVerification } from "./cli-bridge.js";
15
- import { buildCodexExecArgs, DEFAULT_CODEX_CHATGPT_MODEL } from "./codex-launcher.js";
14
+ import { readGitChangedFiles, readGitExecutionArtifacts, resolveGitRepositoryRoot, runSubprocess, runVerification } from "./cli-bridge.js";
15
+ import { buildCodexExecArgs } from "./codex-launcher.js";
16
16
  import { createAdapterCapabilities, normalizeStructuredErrors, normalizeUsage } from "./runtime-support.js";
17
17
  // ---------------------------------------------------------------------------
18
18
  // Cost estimation
@@ -381,14 +381,10 @@ function createStreamingUsageInspector(capUsd, modelLabel, promptTokenEstimate)
381
381
  catch {
382
382
  return;
383
383
  }
384
- // result events contain aggregate usage that duplicates previously streamed
385
- // assistant-message usage events — skip to avoid double-counting.
384
+ extractUsageFromEvent(event, terminate);
386
385
  if (event.type === "result") {
387
386
  finalResult = event;
388
387
  }
389
- else {
390
- extractUsageFromEvent(event, terminate);
391
- }
392
388
  };
393
389
  return {
394
390
  onChunk: (chunk, terminate) => {
@@ -514,6 +510,14 @@ export function createAgentCliAdapter(options) {
514
510
  async execute(request) {
515
511
  const prompt = buildPrompt(request);
516
512
  const estimatedUsage = estimateUsage(prompt, options.model ?? options.command, options.command);
513
+ const repoRoot = request.context.repoRoot;
514
+ const gitRepoRoot = repoRoot ? resolveGitRepositoryRoot(repoRoot) : undefined;
515
+ // A governed run may begin in a deliberately dirty workspace. Capture that
516
+ // baseline so existing operator work is neither reported as this run's
517
+ // execution nor treated as scope creep.
518
+ const baselineChangedFiles = gitRepoRoot
519
+ ? new Set(await readGitChangedFiles(gitRepoRoot, 5_000, options.spawnImpl))
520
+ : new Set();
517
521
  // Preflight: bail if projected cost exceeds remaining budget
518
522
  if (request.context.remainingBudgetUsd > 0) {
519
523
  const projected = estimatePromptCost(prompt, options.model ?? "", options.command);
@@ -549,7 +553,8 @@ export function createAgentCliAdapter(options) {
549
553
  timeoutMs,
550
554
  spawnImpl: options.spawnImpl,
551
555
  ...(stdinData === undefined ? {} : { stdinData }),
552
- ...(streamingUsage ? { onStdoutChunk: streamingUsage.onChunk } : {})
556
+ ...(streamingUsage ? { onStdoutChunk: streamingUsage.onChunk } : {}),
557
+ ...(request.signal !== undefined ? { signal: request.signal } : {})
553
558
  });
554
559
  if (agentResult.terminationReason) {
555
560
  const snapshot = streamingUsage?.snapshot();
@@ -695,30 +700,36 @@ export function createAgentCliAdapter(options) {
695
700
  : undefined
696
701
  });
697
702
  const verificationStack = request.context.verificationStack;
698
- const verification = await runVerification(request.context.verificationPlan, workingDirectory, verifyTimeoutMs, verificationStack, options.spawnImpl);
703
+ const verification = await runVerification(request.context.verificationPlan, workingDirectory, verifyTimeoutMs, verificationStack, options.spawnImpl, {
704
+ runId: request.loopId,
705
+ workspaceId: request.workspaceId,
706
+ cwd: workingDirectory,
707
+ });
699
708
  // Check for zero-diff (agent ran but made no file changes)
700
- const repoRoot = request.context.repoRoot;
701
- const gitRepoRoot = repoRoot ? resolveGitRepositoryRoot(repoRoot) : undefined;
702
- let noDiff = false;
703
- if (gitRepoRoot) {
704
- noDiff = await checkNoDiff(gitRepoRoot, options.spawnImpl);
705
- }
709
+ const postRunChangedFiles = gitRepoRoot
710
+ ? await readGitChangedFiles(gitRepoRoot, 5_000, options.spawnImpl)
711
+ : [];
712
+ const agentChangedFiles = postRunChangedFiles.filter((file) => !baselineChangedFiles.has(file));
713
+ const noDiff = gitRepoRoot !== undefined && agentChangedFiles.length === 0;
706
714
  // Extract structured errors from stderr/stdout for better failure context
707
715
  const structuredErrors = normalizeStructuredErrors(extractStructuredErrors(agentResult.stderr, agentResult.stdout));
708
- const executionArtifacts = gitRepoRoot
716
+ const rawExecutionArtifacts = gitRepoRoot
709
717
  ? await readGitExecutionArtifacts(gitRepoRoot, 5000, options.spawnImpl)
710
718
  : undefined;
719
+ const executionArtifacts = rawExecutionArtifacts
720
+ ? {
721
+ ...(agentChangedFiles.length > 0 ? { changedFiles: agentChangedFiles } : {}),
722
+ ...(baselineChangedFiles.size === 0 && rawExecutionArtifacts.diffStats
723
+ ? { diffStats: rawExecutionArtifacts.diffStats }
724
+ : {})
725
+ }
726
+ : undefined;
711
727
  // Scope contract enforcement: check touched files against allowedPaths/deniedPaths
712
728
  let scopeViolations = [];
713
729
  const scopeCtx = request.context;
714
730
  if (gitRepoRoot && (scopeCtx.allowedPaths?.length || scopeCtx.deniedPaths?.length)) {
715
- const diffResult = await runSubprocess("git", ["diff", "--name-only", "HEAD"], {
716
- cwd: gitRepoRoot,
717
- timeoutMs: 5000,
718
- spawnImpl: options.spawnImpl
719
- });
720
- if (diffResult.exitCode === 0 && diffResult.stdout.trim()) {
721
- const touchedFiles = diffResult.stdout.trim().split("\n").filter(Boolean);
731
+ if (agentChangedFiles.length > 0) {
732
+ const touchedFiles = agentChangedFiles;
722
733
  const allowed = scopeCtx.allowedPaths ?? [];
723
734
  const denied = scopeCtx.deniedPaths ?? [];
724
735
  for (const file of touchedFiles) {
@@ -741,7 +752,7 @@ export function createAgentCliAdapter(options) {
741
752
  status: "completed",
742
753
  summary,
743
754
  usage,
744
- verification: { passed: true, summary: verification.summary },
755
+ verification,
745
756
  ...(executionArtifacts
746
757
  ? {
747
758
  execution: {
@@ -786,7 +797,7 @@ export function createAgentCliAdapter(options) {
786
797
  }
787
798
  // Reset tracked files to HEAD so next attempt starts from clean state
788
799
  try {
789
- if (gitRepoRoot) {
800
+ if (gitRepoRoot && baselineChangedFiles.size === 0) {
790
801
  await runSubprocess("git", ["restore", "--staged", "--worktree", "."], {
791
802
  cwd: gitRepoRoot,
792
803
  timeoutMs: 5000
@@ -803,7 +814,7 @@ export function createAgentCliAdapter(options) {
803
814
  ? `${summary}${errorBlock}${scopeViolations.length > 0 ? `\nScope violations: ${scopeViolations.join(", ")}` : ""}`
804
815
  : summary,
805
816
  usage,
806
- verification: { passed: false, summary: verification.summary },
817
+ verification,
807
818
  ...(executionArtifacts
808
819
  ? {
809
820
  execution: {
@@ -906,7 +917,7 @@ export function createCodexCliAdapter(options = {}) {
906
917
  const sandbox = options.sandbox ?? "workspace-write";
907
918
  const workingDirectory = options.workingDirectory ?? process.cwd();
908
919
  const command = options.command ?? "codex";
909
- const launchModel = options.model ?? DEFAULT_CODEX_CHATGPT_MODEL;
920
+ const launchModel = options.model;
910
921
  return createAgentCliAdapter({
911
922
  command,
912
923
  adapterIdSuffix: "codex",
@@ -1152,11 +1163,3 @@ function extractStructuredErrors(stderr, stdout) {
1152
1163
  }
1153
1164
  return errors.slice(0, 10); // cap at 10 to avoid bloating prompts
1154
1165
  }
1155
- async function checkNoDiff(repoRoot, spawnImpl) {
1156
- const result = await runSubprocess("git", ["diff", "--name-only", "HEAD"], {
1157
- cwd: repoRoot,
1158
- timeoutMs: 5000,
1159
- spawnImpl
1160
- });
1161
- return result.exitCode === 0 && result.stdout.trim().length === 0;
1162
- }
@@ -1,11 +1,14 @@
1
1
  import { type ChildProcess, type SpawnOptions } from "node:child_process";
2
2
  import { diffStatsFromNumstat } from "./runtime-support.js";
3
+ import type { VerifierExecutionBinding } from "../core/index.js";
3
4
  export type SpawnLike = (command: string, args?: readonly string[], options?: SpawnOptions) => ChildProcess;
4
5
  export interface SubprocessResult {
5
6
  exitCode: number;
6
7
  stdout: string;
7
8
  stderr: string;
8
9
  timedOut: boolean;
10
+ completed: boolean;
11
+ crashed: boolean;
9
12
  /**
10
13
  * True when the subprocess was terminated early because its combined
11
14
  * stdout+stderr exceeded `maxOutputBytes` — a circuit breaker against
@@ -30,10 +33,13 @@ export interface VerificationOutcome {
30
33
  summary: string;
31
34
  steps: VerificationStepOutcome[];
32
35
  warnings?: string[];
36
+ binding: VerifierExecutionBinding;
33
37
  }
34
38
  export interface VerificationStepOutcome {
35
39
  command: string;
36
40
  launched: boolean;
41
+ completed: boolean;
42
+ crashed: boolean;
37
43
  exitCode?: number;
38
44
  timedOut: boolean;
39
45
  fastFail: boolean;
@@ -60,12 +66,14 @@ export declare function runSubprocess(command: string, args: string[], options:
60
66
  * a runaway final usage figure.
61
67
  */
62
68
  onStdoutChunk?: (chunk: Buffer, terminate: (reason: string) => void) => void;
69
+ /** Optional abort signal — kills the subprocess when aborted. */
70
+ signal?: AbortSignal;
63
71
  }): Promise<SubprocessResult>;
64
72
  export declare function runVerification(commands: string[], cwd: string, timeoutMs: number, verificationStack?: Array<{
65
73
  command: string;
66
74
  type: string;
67
75
  fastFail?: boolean;
68
- }>, spawnImpl?: SpawnLike): Promise<VerificationOutcome>;
76
+ }>, spawnImpl?: SpawnLike, binding?: Omit<VerifierExecutionBinding, "commands">): Promise<VerificationOutcome>;
69
77
  export declare function readGitExecutionArtifacts(repoRoot: string, timeoutMs: number, spawnImpl?: SpawnLike): Promise<{
70
78
  changedFiles?: string[];
71
79
  diffStats?: ReturnType<typeof diffStatsFromNumstat>;
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { delimiter, dirname, extname, isAbsolute, join, resolve } from "node:path";
2
+ import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from "node:path";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { diffStatsFromNumstat } from "./runtime-support.js";
5
5
  const gitRepositoryRootCache = new Map();
@@ -32,7 +32,7 @@ export async function runSubprocess(command, args, options) {
32
32
  }
33
33
  catch (error) {
34
34
  const message = error instanceof Error ? error.message : String(error);
35
- resolveOnce({ exitCode: 1, stdout: "", stderr: message, launched: false });
35
+ resolveOnce({ exitCode: 1, stdout: "", stderr: message, launched: false, completed: false, crashed: true });
36
36
  return;
37
37
  }
38
38
  const trackOutput = (chunks, chunk) => {
@@ -53,6 +53,18 @@ export async function runSubprocess(command, args, options) {
53
53
  terminationReason = reason;
54
54
  proc.kill("SIGTERM");
55
55
  };
56
+ // Honour the harness abort signal — kill the subprocess immediately
57
+ if (options.signal !== undefined) {
58
+ const sig = options.signal;
59
+ if (sig.aborted) {
60
+ proc.kill("SIGTERM");
61
+ }
62
+ else {
63
+ const onAbort = () => { proc.kill("SIGTERM"); };
64
+ sig.addEventListener("abort", onAbort, { once: true });
65
+ proc.on("close", () => { sig.removeEventListener("abort", onAbort); });
66
+ }
67
+ }
56
68
  proc.stdout?.on("data", (chunk) => {
57
69
  if (outputCapped || timedOut || terminationReason) {
58
70
  return;
@@ -93,15 +105,18 @@ export async function runSubprocess(command, args, options) {
93
105
  });
94
106
  proc.on("error", (error) => {
95
107
  clearTimeout(timer);
96
- resolveOnce({ exitCode: 1, stdout: "", stderr: error.message, launched: false });
108
+ resolveOnce({ exitCode: 1, stdout: "", stderr: error.message, launched: false, completed: false, crashed: true });
97
109
  });
98
110
  proc.on("close", (code) => {
99
111
  clearTimeout(timer);
112
+ const completed = code !== null && !timedOut && !outputCapped && !terminationReason;
100
113
  resolveOnce({
101
114
  exitCode: code ?? 1,
102
115
  stdout: Buffer.concat(stdoutChunks).toString("utf8"),
103
116
  stderr: Buffer.concat(stderrChunks).toString("utf8"),
104
- launched: true
117
+ launched: true,
118
+ completed,
119
+ crashed: !completed && !timedOut && !outputCapped && !terminationReason,
105
120
  });
106
121
  });
107
122
  if (options.stdinData !== undefined && proc.stdin) {
@@ -116,22 +131,30 @@ export async function runSubprocess(command, args, options) {
116
131
  exitCode: 1,
117
132
  stdout: Buffer.concat(stdoutChunks).toString("utf8"),
118
133
  stderr: stdinError.message,
119
- launched: false
134
+ launched: false,
135
+ completed: false,
136
+ crashed: true,
120
137
  });
121
138
  }
122
139
  }
123
140
  }
124
141
  });
125
142
  }
126
- export async function runVerification(commands, cwd, timeoutMs, verificationStack, spawnImpl) {
143
+ export async function runVerification(commands, cwd, timeoutMs, verificationStack, spawnImpl, binding) {
127
144
  const steps = verificationStack && verificationStack.length > 0
128
145
  ? verificationStack.map((step) => ({
129
146
  command: step.command,
130
147
  fastFail: step.fastFail !== false
131
148
  }))
132
149
  : commands.map((command) => ({ command, fastFail: true }));
150
+ const executionBinding = {
151
+ runId: binding?.runId ?? "unbound",
152
+ workspaceId: binding?.workspaceId ?? "unbound",
153
+ cwd: binding?.cwd ?? cwd,
154
+ commands: steps.map((step) => step.command),
155
+ };
133
156
  if (steps.length === 0) {
134
- return { passed: true, summary: "No verification commands specified.", steps: [] };
157
+ return { passed: true, summary: "No verification commands specified.", steps: [], binding: executionBinding };
135
158
  }
136
159
  const failedSteps = [];
137
160
  const stepOutcomes = [];
@@ -169,6 +192,8 @@ export async function runVerification(commands, cwd, timeoutMs, verificationStac
169
192
  stepOutcomes.push({
170
193
  command: step.command,
171
194
  launched: result.launched,
195
+ completed: result.completed,
196
+ crashed: result.crashed,
172
197
  exitCode: result.exitCode,
173
198
  timedOut: result.timedOut,
174
199
  fastFail: step.fastFail,
@@ -179,6 +204,7 @@ export async function runVerification(commands, cwd, timeoutMs, verificationStac
179
204
  passed: false,
180
205
  summary: `Verification timed out: ${step.command}`,
181
206
  steps: stepOutcomes,
207
+ binding: executionBinding,
182
208
  ...(warnings.length ? { warnings } : {})
183
209
  };
184
210
  }
@@ -188,7 +214,7 @@ export async function runVerification(commands, cwd, timeoutMs, verificationStac
188
214
  warnings.push(`Verifier never launched: ${step.command}`);
189
215
  }
190
216
  if (step.fastFail) {
191
- return { passed: false, summary, steps: stepOutcomes, ...(warnings.length ? { warnings } : {}) };
217
+ return { passed: false, summary, steps: stepOutcomes, binding: executionBinding, ...(warnings.length ? { warnings } : {}) };
192
218
  }
193
219
  failedSteps.push(step.command);
194
220
  }
@@ -198,6 +224,7 @@ export async function runVerification(commands, cwd, timeoutMs, verificationStac
198
224
  passed: false,
199
225
  summary: `Failed steps: ${failedSteps.join(", ")}`,
200
226
  steps: stepOutcomes,
227
+ binding: executionBinding,
201
228
  ...(warnings.length ? { warnings } : {})
202
229
  };
203
230
  }
@@ -205,6 +232,7 @@ export async function runVerification(commands, cwd, timeoutMs, verificationStac
205
232
  passed: true,
206
233
  summary: `All ${String(steps.length)} verification step(s) passed.`,
207
234
  steps: stepOutcomes,
235
+ binding: executionBinding,
208
236
  ...(warnings.length ? { warnings } : {})
209
237
  };
210
238
  }
@@ -365,19 +393,32 @@ export function resolveNpmShimScript(shimPath) {
365
393
  }
366
394
  const shimDir = dirname(shimPath);
367
395
  const scriptPathPattern = /["']?(?:%~?dp0%?|\$basedir)[\\/]([^"'\s]+\.[cm]?js)["']?/gi;
368
- const matches = contents.matchAll(scriptPathPattern);
396
+ const matches = [...contents.matchAll(scriptPathPattern)];
397
+ // Collect all candidate scripts that exist on disk.
398
+ const candidates = [];
369
399
  for (const match of matches) {
370
400
  const relativeScript = match[1];
371
- if (!relativeScript) {
401
+ if (!relativeScript)
372
402
  continue;
373
- }
374
403
  const segments = relativeScript.split(/[\\/]+/u).filter(Boolean);
375
404
  const resolvedScript = resolve(shimDir, ...segments);
376
405
  if (existsSync(resolvedScript)) {
377
- return resolvedScript;
406
+ candidates.push(resolvedScript);
378
407
  }
379
408
  }
380
- return undefined;
409
+ if (candidates.length === 0)
410
+ return undefined;
411
+ // npm.cmd / npm.ps1 / npm.bat shims reference both npm-prefix.js and npm-cli.js.
412
+ // npm-cli.js is the semantic npm CLI entry point — never pick npm-prefix.js for
413
+ // these. Fail closed: if npm-cli.js is not among the resolved candidates, return
414
+ // undefined so the caller falls back to wrapper-shell behavior.
415
+ const shimBasename = basename(shimPath).toLowerCase();
416
+ if (/^npm(\.(cmd|ps1|bat))?$/.test(shimBasename)) {
417
+ return candidates.find((p) => basename(p).toLowerCase() === "npm-cli.js");
418
+ }
419
+ // For all other npm-installed executables (codex.cmd, claude.ps1, etc.), the
420
+ // shim wraps exactly one package bin target — use the first resolving candidate.
421
+ return candidates[0];
381
422
  }
382
423
  /**
383
424
  * Resolve a reliable `node` executable for spawning CLI scripts on Windows.
@@ -43,7 +43,67 @@ export interface CodexExecArgsOptions {
43
43
  mode?: "prompt" | "probe";
44
44
  }
45
45
  type SpawnSyncLike = typeof spawnSync;
46
- export declare const DEFAULT_CODEX_CHATGPT_MODEL = "gpt-5.4";
46
+ /**
47
+ * Outcome when the preflight probe confirms the working directory is writable.
48
+ * capabilitySource is always "probe" — result is measured, not assumed.
49
+ */
50
+ export interface CodexSandboxPreflightOk {
51
+ ok: true;
52
+ effectiveSandbox: "read-only" | "workspace-write";
53
+ capabilitySource: "probe";
54
+ writableRoot: string;
55
+ }
56
+ /**
57
+ * Outcome when the working directory cannot be written but workspace-write
58
+ * was requested. This is a first-class typed failure — distinct from a
59
+ * provider-unavailable or environment-mismatch error. No model call has
60
+ * been attempted when this is returned.
61
+ */
62
+ export interface CodexSandboxPreflightReadOnly {
63
+ ok: false;
64
+ code: "provider_sandbox_read_only";
65
+ requestedCapability: "workspace-write";
66
+ detectedCapability: "read-only";
67
+ effectiveSandbox: "read-only";
68
+ affectedPath: string;
69
+ writableRoot: string;
70
+ capabilitySource: "probe";
71
+ remediation: string;
72
+ }
73
+ export type CodexSandboxPreflightOutcome = CodexSandboxPreflightOk | CodexSandboxPreflightReadOnly;
74
+ /**
75
+ * Probes whether the given directory is writable by the current process.
76
+ *
77
+ * Strategy: create a uniquely named temp file inside the directory, write a
78
+ * sentinel byte, then remove it. This is a real filesystem action — not an
79
+ * inference from binary metadata or launch-probe output.
80
+ *
81
+ * The probe leaves no file behind on either success or failure.
82
+ *
83
+ * Exported for unit testing with a real tmp directory.
84
+ */
85
+ export declare function probeFilesystemWriteCapability(directory: string): {
86
+ writable: true;
87
+ } | {
88
+ writable: false;
89
+ reason: string;
90
+ };
91
+ /**
92
+ * Checks whether the requested sandbox mode is achievable for the given
93
+ * working directory. The adapter receives `requestedSandbox` from CLI/core —
94
+ * it does not decide the mode itself.
95
+ *
96
+ * When `requestedSandbox` is "workspace-write" and the working directory is not
97
+ * writable, this function returns `provider_sandbox_read_only` before any model
98
+ * execution is attempted.
99
+ *
100
+ * When `requestedSandbox` is "read-only" no write probe is performed; the
101
+ * outcome is `ok: true, effectiveSandbox: "read-only"` immediately.
102
+ */
103
+ export declare function checkCodexSandboxPreflight(input: {
104
+ requestedSandbox: "read-only" | "workspace-write";
105
+ workingDirectory: string;
106
+ }): CodexSandboxPreflightOutcome;
47
107
  export interface CodexProbeCandidateResult {
48
108
  path: string;
49
109
  installKind: CodexInstallKind;
@@ -1,9 +1,100 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { dirname, extname, join, resolve } from "node:path";
4
4
  import { resolveNpmShimScript } from "./cli-bridge.js";
5
5
  const codexLaunchProbeCache = new Map();
6
- export const DEFAULT_CODEX_CHATGPT_MODEL = "gpt-5.4";
6
+ /**
7
+ * Probes whether the given directory is writable by the current process.
8
+ *
9
+ * Strategy: create a uniquely named temp file inside the directory, write a
10
+ * sentinel byte, then remove it. This is a real filesystem action — not an
11
+ * inference from binary metadata or launch-probe output.
12
+ *
13
+ * The probe leaves no file behind on either success or failure.
14
+ *
15
+ * Exported for unit testing with a real tmp directory.
16
+ */
17
+ export function probeFilesystemWriteCapability(directory) {
18
+ // Ensure the directory exists before probing.
19
+ try {
20
+ mkdirSync(directory, { recursive: true });
21
+ }
22
+ catch (err) {
23
+ return {
24
+ writable: false,
25
+ reason: `Could not create directory ${directory}: ${err instanceof Error ? err.message : String(err)}`
26
+ };
27
+ }
28
+ // Use mkdtempSync so the filename is guaranteed unique even under concurrent runs.
29
+ let tempDir;
30
+ try {
31
+ tempDir = mkdtempSync(join(directory, ".ml-write-probe-"));
32
+ const tempFile = join(tempDir, "capability.tmp");
33
+ writeFileSync(tempFile, "\x01", { encoding: "binary", flag: "wx" });
34
+ unlinkSync(tempFile);
35
+ return { writable: true };
36
+ }
37
+ catch (err) {
38
+ return {
39
+ writable: false,
40
+ reason: err instanceof Error ? err.message : String(err)
41
+ };
42
+ }
43
+ finally {
44
+ if (tempDir) {
45
+ try {
46
+ rmSync(tempDir, { recursive: true, force: true });
47
+ }
48
+ catch { /* ignore cleanup errors */ }
49
+ }
50
+ }
51
+ }
52
+ /**
53
+ * Checks whether the requested sandbox mode is achievable for the given
54
+ * working directory. The adapter receives `requestedSandbox` from CLI/core —
55
+ * it does not decide the mode itself.
56
+ *
57
+ * When `requestedSandbox` is "workspace-write" and the working directory is not
58
+ * writable, this function returns `provider_sandbox_read_only` before any model
59
+ * execution is attempted.
60
+ *
61
+ * When `requestedSandbox` is "read-only" no write probe is performed; the
62
+ * outcome is `ok: true, effectiveSandbox: "read-only"` immediately.
63
+ */
64
+ export function checkCodexSandboxPreflight(input) {
65
+ const dir = resolve(input.workingDirectory);
66
+ if (input.requestedSandbox === "read-only") {
67
+ return {
68
+ ok: true,
69
+ effectiveSandbox: "read-only",
70
+ capabilitySource: "probe",
71
+ writableRoot: dir
72
+ };
73
+ }
74
+ // workspace-write: run the actual filesystem probe.
75
+ const probeResult = probeFilesystemWriteCapability(dir);
76
+ if (probeResult.writable) {
77
+ return {
78
+ ok: true,
79
+ effectiveSandbox: "workspace-write",
80
+ capabilitySource: "probe",
81
+ writableRoot: dir
82
+ };
83
+ }
84
+ return {
85
+ ok: false,
86
+ code: "provider_sandbox_read_only",
87
+ requestedCapability: "workspace-write",
88
+ detectedCapability: "read-only",
89
+ effectiveSandbox: "read-only",
90
+ affectedPath: dir,
91
+ writableRoot: dir,
92
+ capabilitySource: "probe",
93
+ remediation: `The working directory ${dir} is not writable by the current process. ` +
94
+ "Launch MartinLoop in a session with write access to that directory, or use " +
95
+ "`--sandbox read-only` for inspection-only work."
96
+ };
97
+ }
7
98
  const CODEX_LAUNCH_PROBE_PROMPT = [
8
99
  "You are validating MartinLoop Codex host readiness.",
9
100
  "Do not edit files.",
@@ -17,7 +108,7 @@ function buildProbeCacheKey(input) {
17
108
  workingDirectory: resolve(input.workingDirectory),
18
109
  platform: input.platform,
19
110
  candidatePaths: input.candidatePaths,
20
- model: input.model ?? DEFAULT_CODEX_CHATGPT_MODEL
111
+ model: input.model
21
112
  });
22
113
  }
23
114
  function isInsideGitRepository(workingDirectory) {
@@ -89,6 +180,17 @@ function codexProbePreference(diagnosis) {
89
180
  }
90
181
  return 3;
91
182
  }
183
+ function codexProbeCandidatePreference(path, diagnosis, platform) {
184
+ const hostPreference = codexProbePreference(diagnosis) * 10;
185
+ if (platform !== "win32" || diagnosis.installKind !== "windows_shim") {
186
+ return hostPreference;
187
+ }
188
+ // `where codex` commonly returns npm's extensionless POSIX shim before
189
+ // `codex.cmd`. Node cannot spawn that text shim directly on Windows, while
190
+ // the .cmd/.ps1 shim has a supported invocation path (or can be unwrapped).
191
+ const extension = extname(path).toLowerCase();
192
+ return hostPreference + (extension === ".cmd" || extension === ".bat" || extension === ".ps1" ? 0 : 1);
193
+ }
92
194
  function buildProbeCandidates(input) {
93
195
  const pathCandidates = normalizeCandidates(input.availability.candidatePaths ?? [input.availability.resolvedPath ?? input.availability.command]);
94
196
  const desktopCandidates = input.platform === "win32" && input.includeDesktopCandidates
@@ -106,7 +208,9 @@ function buildProbeCandidates(input) {
106
208
  return {
107
209
  path,
108
210
  diagnosis,
109
- preference: input.platform === "win32" ? codexProbePreference(diagnosis) : 0,
211
+ preference: input.platform === "win32"
212
+ ? codexProbeCandidatePreference(path, diagnosis, input.platform)
213
+ : 0,
110
214
  discoveryIndex
111
215
  };
112
216
  })
@@ -205,11 +309,11 @@ function classifyProbeFailure(stderr, stdout, diagnosis) {
205
309
  warnings.push(unsupportedModelWarning);
206
310
  }
207
311
  return {
208
- summary: `Codex launched with a model that is not supported for ChatGPT-account authentication. Use an explicit supported model such as \`${DEFAULT_CODEX_CHATGPT_MODEL}\` for governed Codex work.`,
312
+ summary: "Codex launched with a model that is not supported for ChatGPT-account authentication. Pass an explicit model that your ChatGPT account supports for governed Codex work.",
209
313
  diagnosis: {
210
314
  ...diagnosis,
211
315
  warnings,
212
- remediation: `Override the Codex launch model to a ChatGPT-account-supported option such as \`${DEFAULT_CODEX_CHATGPT_MODEL}\` before running governed Codex work.`
316
+ remediation: "Override the Codex launch model to a ChatGPT-account-supported option before running governed Codex work."
213
317
  }
214
318
  };
215
319
  }
@@ -275,14 +379,18 @@ export function buildCodexExecArgs(options) {
275
379
  const sandbox = options.sandbox ?? "workspace-write";
276
380
  const modelArgs = options.model ? ["--model", options.model] : [];
277
381
  const extraArgs = options.extraArgs ?? [];
382
+ const sandboxArgs = sandbox === "workspace-write"
383
+ // In Codex CLI, --approve-for-me is the write-enabled automatic-review
384
+ // mode and is mutually exclusive with --sandbox workspace-write.
385
+ ? ["--approve-for-me"]
386
+ : ["--sandbox", sandbox];
278
387
  return [
279
388
  "exec",
280
389
  // Governed MartinLoop runs should not inherit auth-sensitive default MCP/plugin state.
281
390
  "--ignore-user-config",
282
391
  "--cd",
283
392
  options.workingDirectory,
284
- "--sandbox",
285
- sandbox,
393
+ ...sandboxArgs,
286
394
  "--json",
287
395
  "--color",
288
396
  "never",
@@ -357,10 +465,6 @@ function discoverCommandOffPath(command, platform, env) {
357
465
  const localAppData = env.LOCALAPPDATA;
358
466
  if (localAppData)
359
467
  dirs.push(join(localAppData, "OpenAI", "Codex", "bin"));
360
- // Claude Code native installer places binary at %USERPROFILE%\.local\bin
361
- const userProfile = env.USERPROFILE ?? env.HOMEPATH;
362
- if (userProfile)
363
- dirs.push(join(userProfile, ".local", "bin"));
364
468
  if (home)
365
469
  dirs.push(join(home, "scoop", "shims"));
366
470
  }
@@ -387,13 +491,8 @@ function discoverCommandOffPath(command, platform, env) {
387
491
  return undefined;
388
492
  }
389
493
  function suggestInstall(command) {
390
- if (command === "claude") {
391
- const installCmd = process.platform === "win32"
392
- ? "irm https://claude.ai/install.ps1 | iex"
393
- : "curl -fsSL https://claude.ai/install.sh | bash";
394
- return `Install with: ${installCmd}`;
395
- }
396
494
  const installs = {
495
+ claude: "Install with: npm install -g @anthropic-ai/claude-code",
397
496
  codex: "Install with: npm install -g @openai/codex",
398
497
  gemini: "Install with: npm install -g @google/gemini-cli"
399
498
  };
@@ -471,7 +570,7 @@ export function probeCodexLaunch(input) {
471
570
  });
472
571
  const args = buildCodexExecArgs({
473
572
  workingDirectory: input.workingDirectory,
474
- model: input.model ?? DEFAULT_CODEX_CHATGPT_MODEL,
573
+ model: input.model,
475
574
  mode: "probe"
476
575
  });
477
576
  if (!availability.available) {
@@ -1,8 +1,6 @@
1
1
  export { createDirectProviderAdapter, type DirectProviderAdapterOptions } from "./direct-provider.js";
2
2
  export { createStubDirectProviderAdapter, type StubDirectProviderAdapterOptions } from "./stub-direct-provider.js";
3
- export { createStubAgentCliAdapter, type StubAgentCliAdapterOptions } from "./stub-agent-cli.js";
4
3
  export { createAgentCliAdapter, createClaudeCliAdapter, createCodexCliAdapter, createGeminiCliAdapter, type AgentCliAdapterOptions, type ClaudeCliAdapterOptions, type CodexCliAdapterOptions, type GeminiCliAdapterOptions, type CliArgsBuilder } from "./claude-cli.js";
5
- export { createVerifierOnlyAdapter, type VerifierOnlyAdapterOptions } from "./verifier-only.js";
6
4
  export { createOpenAiCompatibleAdapter, resolveOpenAiCompatibleRuntimeConfig, type OpenAiCompatibleAdapterOptions } from "./openai-compatible.js";
7
- export { detectCodexHostPlatform, diagnoseCodexHost, probeCodexLaunch, resolveCliCommandAvailability, type CliCommandAvailability, type CodexHostDiagnosis, type CodexHostPlatform, type CodexLaunchProbeResult } from "./codex-launcher.js";
5
+ export { detectCodexHostPlatform, diagnoseCodexHost, probeCodexLaunch, resolveCliCommandAvailability, type CliCommandAvailability, type CodexHostDiagnosis, type CodexHostPlatform, type CodexLaunchProbeResult, checkCodexSandboxPreflight, probeFilesystemWriteCapability, type CodexSandboxPreflightOk, type CodexSandboxPreflightOutcome, type CodexSandboxPreflightReadOnly } from "./codex-launcher.js";
8
6
  export { createSpawnPlan, type SpawnLike, type SpawnPlan, type SubprocessResult, type VerificationOutcome } from "./cli-bridge.js";
@@ -1,8 +1,6 @@
1
1
  export { createDirectProviderAdapter } from "./direct-provider.js";
2
2
  export { createStubDirectProviderAdapter } from "./stub-direct-provider.js";
3
- export { createStubAgentCliAdapter } from "./stub-agent-cli.js";
4
3
  export { createAgentCliAdapter, createClaudeCliAdapter, createCodexCliAdapter, createGeminiCliAdapter } from "./claude-cli.js";
5
- export { createVerifierOnlyAdapter } from "./verifier-only.js";
6
4
  export { createOpenAiCompatibleAdapter, resolveOpenAiCompatibleRuntimeConfig } from "./openai-compatible.js";
7
- export { detectCodexHostPlatform, diagnoseCodexHost, probeCodexLaunch, resolveCliCommandAvailability } from "./codex-launcher.js";
5
+ export { detectCodexHostPlatform, diagnoseCodexHost, probeCodexLaunch, resolveCliCommandAvailability, checkCodexSandboxPreflight, probeFilesystemWriteCapability } from "./codex-launcher.js";
8
6
  export { createSpawnPlan } from "./cli-bridge.js";