@memnexus-ai/mx-agent-cli 0.1.246 → 0.1.248

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 (68) hide show
  1. package/dist/__tests__/codex-agent-gate.test.d.ts +2 -0
  2. package/dist/__tests__/codex-agent-gate.test.d.ts.map +1 -0
  3. package/dist/__tests__/codex-agent-gate.test.js +182 -0
  4. package/dist/__tests__/codex-agent-gate.test.js.map +1 -0
  5. package/dist/__tests__/runtime-claude-adapter.test.d.ts +2 -0
  6. package/dist/__tests__/runtime-claude-adapter.test.d.ts.map +1 -0
  7. package/dist/__tests__/runtime-claude-adapter.test.js +70 -0
  8. package/dist/__tests__/runtime-claude-adapter.test.js.map +1 -0
  9. package/dist/__tests__/runtime-codex-adapter.test.d.ts +2 -0
  10. package/dist/__tests__/runtime-codex-adapter.test.d.ts.map +1 -0
  11. package/dist/__tests__/runtime-codex-adapter.test.js +513 -0
  12. package/dist/__tests__/runtime-codex-adapter.test.js.map +1 -0
  13. package/dist/__tests__/runtime-codex-config.test.d.ts +2 -0
  14. package/dist/__tests__/runtime-codex-config.test.d.ts.map +1 -0
  15. package/dist/__tests__/runtime-codex-config.test.js +523 -0
  16. package/dist/__tests__/runtime-codex-config.test.js.map +1 -0
  17. package/dist/__tests__/runtime-codex-version-pin.test.d.ts +2 -0
  18. package/dist/__tests__/runtime-codex-version-pin.test.d.ts.map +1 -0
  19. package/dist/__tests__/runtime-codex-version-pin.test.js +86 -0
  20. package/dist/__tests__/runtime-codex-version-pin.test.js.map +1 -0
  21. package/dist/__tests__/runtime-resolve.test.d.ts +2 -0
  22. package/dist/__tests__/runtime-resolve.test.d.ts.map +1 -0
  23. package/dist/__tests__/runtime-resolve.test.js +172 -0
  24. package/dist/__tests__/runtime-resolve.test.js.map +1 -0
  25. package/dist/__tests__/start-rebase-never-ran.test.d.ts +25 -0
  26. package/dist/__tests__/start-rebase-never-ran.test.d.ts.map +1 -0
  27. package/dist/__tests__/start-rebase-never-ran.test.js +227 -0
  28. package/dist/__tests__/start-rebase-never-ran.test.js.map +1 -0
  29. package/dist/__tests__/start-runtime-wiring.test.d.ts +31 -0
  30. package/dist/__tests__/start-runtime-wiring.test.d.ts.map +1 -0
  31. package/dist/__tests__/start-runtime-wiring.test.js +498 -0
  32. package/dist/__tests__/start-runtime-wiring.test.js.map +1 -0
  33. package/dist/commands/codex-agent-gate.d.ts +23 -0
  34. package/dist/commands/codex-agent-gate.d.ts.map +1 -0
  35. package/dist/commands/codex-agent-gate.js +139 -0
  36. package/dist/commands/codex-agent-gate.js.map +1 -0
  37. package/dist/commands/start.d.ts +21 -0
  38. package/dist/commands/start.d.ts.map +1 -1
  39. package/dist/commands/start.js +190 -25
  40. package/dist/commands/start.js.map +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +23 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/lib/claude.d.ts +72 -10
  45. package/dist/lib/claude.d.ts.map +1 -1
  46. package/dist/lib/claude.js +71 -32
  47. package/dist/lib/claude.js.map +1 -1
  48. package/dist/lib/runtime/claude-adapter.d.ts +16 -0
  49. package/dist/lib/runtime/claude-adapter.d.ts.map +1 -0
  50. package/dist/lib/runtime/claude-adapter.js +43 -0
  51. package/dist/lib/runtime/claude-adapter.js.map +1 -0
  52. package/dist/lib/runtime/codex-adapter.d.ts +90 -0
  53. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -0
  54. package/dist/lib/runtime/codex-adapter.js +367 -0
  55. package/dist/lib/runtime/codex-adapter.js.map +1 -0
  56. package/dist/lib/runtime/codex-config.d.ts +254 -0
  57. package/dist/lib/runtime/codex-config.d.ts.map +1 -0
  58. package/dist/lib/runtime/codex-config.js +620 -0
  59. package/dist/lib/runtime/codex-config.js.map +1 -0
  60. package/dist/lib/runtime/resolve.d.ts +46 -0
  61. package/dist/lib/runtime/resolve.d.ts.map +1 -0
  62. package/dist/lib/runtime/resolve.js +113 -0
  63. package/dist/lib/runtime/resolve.js.map +1 -0
  64. package/dist/lib/runtime/types.d.ts +81 -0
  65. package/dist/lib/runtime/types.d.ts.map +1 -0
  66. package/dist/lib/runtime/types.js +39 -0
  67. package/dist/lib/runtime/types.js.map +1 -0
  68. package/package.json +1 -1
@@ -0,0 +1,139 @@
1
+ /**
2
+ * `mx-agent internal-codex-agent-gate` — the RUNTIME enforcement point for Codex
3
+ * agent eligibility (#4227, security review MF2).
4
+ *
5
+ * WHY THIS EXISTS. `checkCodexAgentEligibility` encoded FR-14b (security-reviewer is
6
+ * ineligible) and FR-15 (every Bash-holding agent is ineligible until its guard is
7
+ * proven firing) and was called from nowhere. Twenty tests asserted refusal text that
8
+ * no code path could produce, so the "controls" were documentation. This command is
9
+ * the call site: the generated `.codex/hooks.json` registers it as a SubagentStart
10
+ * hook, so Codex asks it before a subagent starts and a refusal blocks the spawn.
11
+ *
12
+ * FAIL CLOSED. Two inputs are uncertain and both resolve to refusal:
13
+ *
14
+ * 1. WHICH FIELD carries the agent name in Codex's SubagentStart payload is NOT
15
+ * machine-verified — unlike the PreToolUse payload, which was probed on
16
+ * codex-cli 0.145.0 (see codex-config.ts). Several plausible field names are
17
+ * accepted; if none is present, the spawn is REFUSED rather than allowed. A gate
18
+ * that cannot identify its subject must not wave it through.
19
+ * 2. WHICH GUARDS are proven comes from `--proven-guards`, written by the generator
20
+ * from the adapter's own list. Absent or empty → nothing is proven → every
21
+ * hook-gated agent is refused, which is the correct pre-G-7 state.
22
+ *
23
+ * The generated hooks.json is therefore the trust anchor for this decision. An agent
24
+ * that can edit that file can widen its own allowlist, which is why the G-7 paired
25
+ * proof must include a mid-session tamper check (see codex-config.ts) and why Codex's
26
+ * own hook-trust mechanism, not this file's contents, is the boundary that matters.
27
+ */
28
+ import { checkCodexAgentEligibility } from '../lib/runtime/codex-adapter.js';
29
+ /**
30
+ * Field names that might carry the subagent's identity in a SubagentStart payload.
31
+ * Ordered most- to least-specific. NOT machine-verified — see the file header.
32
+ */
33
+ const AGENT_NAME_FIELDS = [
34
+ 'agent_name',
35
+ 'agentName',
36
+ 'subagent_type',
37
+ 'subagentType',
38
+ 'agent',
39
+ 'agent_type',
40
+ 'name',
41
+ ];
42
+ /** Pull the agent name out of a SubagentStart payload, or null if none is present. */
43
+ export function extractAgentName(payload) {
44
+ if (!payload || typeof payload !== 'object')
45
+ return null;
46
+ const obj = payload;
47
+ for (const field of AGENT_NAME_FIELDS) {
48
+ const value = obj[field];
49
+ if (typeof value === 'string' && value.trim())
50
+ return value.trim();
51
+ }
52
+ // One level of nesting: some hook payloads wrap the subject.
53
+ // `tool_input` is DELIBERATELY NOT in this list (security review round 2): it is the
54
+ // one candidate whose contents the model writes, so a name read from it is a name the
55
+ // gated party chose. Dropping it can only widen the fail-closed path — an unresolved
56
+ // name is refused, never allowed.
57
+ for (const key of ['subagent', 'agent_info']) {
58
+ const nested = obj[key];
59
+ if (nested && typeof nested === 'object') {
60
+ const inner = extractAgentName(nested);
61
+ if (inner)
62
+ return inner;
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+ /**
68
+ * Decide whether a subagent spawn may proceed. Pure — no I/O, no process exit — so
69
+ * the decision is directly testable.
70
+ */
71
+ export function decideCodexAgentGate(opts) {
72
+ let payload;
73
+ try {
74
+ payload = JSON.parse(opts.rawPayload);
75
+ }
76
+ catch {
77
+ return {
78
+ exitCode: 2,
79
+ message: 'codex agent gate: could not parse the SubagentStart payload as JSON — refusing the ' +
80
+ 'spawn. A gate that cannot read its input does not allow the operation.',
81
+ };
82
+ }
83
+ const agent = extractAgentName(payload);
84
+ if (!agent) {
85
+ return {
86
+ exitCode: 2,
87
+ message: 'codex agent gate: no agent name found in the SubagentStart payload — refusing the ' +
88
+ `spawn. Checked fields: ${AGENT_NAME_FIELDS.join(', ')}.`,
89
+ };
90
+ }
91
+ const result = checkCodexAgentEligibility(agent, {
92
+ ...(opts.provenGuards ? { provenGuards: opts.provenGuards } : {}),
93
+ });
94
+ if (result.eligible)
95
+ return { exitCode: 0, agent };
96
+ return { exitCode: 2, agent, message: `codex agent gate: ${result.reason}` };
97
+ }
98
+ /** Parse the repeatable `--proven-guards a,b` form the generator emits. */
99
+ export function parseProvenGuardsArgs(argv) {
100
+ const guards = [];
101
+ for (let i = 0; i < argv.length; i++) {
102
+ if (argv[i] !== '--proven-guards')
103
+ continue;
104
+ const value = argv[i + 1];
105
+ if (!value || value.startsWith('--'))
106
+ continue;
107
+ for (const part of value.split(',')) {
108
+ const trimmed = part.trim();
109
+ if (trimmed)
110
+ guards.push(trimmed);
111
+ }
112
+ }
113
+ return guards;
114
+ }
115
+ function readStdin() {
116
+ return new Promise((resolve) => {
117
+ let data = '';
118
+ // No TTY on the hook path; if stdin never opens, an empty payload is refused by
119
+ // decideCodexAgentGate, which is the fail-closed direction.
120
+ process.stdin.setEncoding('utf-8');
121
+ process.stdin.on('data', (chunk) => {
122
+ data += chunk;
123
+ });
124
+ process.stdin.on('end', () => resolve(data));
125
+ process.stdin.on('error', () => resolve(data));
126
+ });
127
+ }
128
+ /** CLI entry point. Reads the hook payload from stdin and exits 0 (allow) or 2 (block). */
129
+ export async function runCodexAgentGate(argv = []) {
130
+ const rawPayload = await readStdin();
131
+ const decision = decideCodexAgentGate({
132
+ rawPayload,
133
+ provenGuards: parseProvenGuardsArgs(argv),
134
+ });
135
+ if (decision.message)
136
+ console.error(decision.message);
137
+ process.exit(decision.exitCode);
138
+ }
139
+ //# sourceMappingURL=codex-agent-gate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-agent-gate.js","sourceRoot":"","sources":["../../src/commands/codex-agent-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAE7E;;;GAGG;AACH,MAAM,iBAAiB,GAAG;IACxB,YAAY;IACZ,WAAW;IACX,eAAe;IACf,cAAc;IACd,OAAO;IACP,YAAY;IACZ,MAAM;CACE,CAAC;AAWX,s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CAAC,OAAO,EAAE,EAAE;QAC7B,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,gFAAgF;QAChF,4DAA4D;QAC5D,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YACjC,IAAI,IAAI,KAAK,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC,CAAC;AACL,CAAC;AAED,2FAA2F;AAC3F,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,OAA0B,EAAE;IAClE,MAAM,UAAU,GAAG,MAAM,SAAS,EAAE,CAAC;IACrC,MAAM,QAAQ,GAAG,oBAAoB,CAAC;QACpC,UAAU;QACV,YAAY,EAAE,qBAAqB,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,OAAO;QAAE,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACtD,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAClC,CAAC"}
@@ -23,6 +23,19 @@
23
23
  */
24
24
  export declare const AGENT_CONFIG_CONFLICT_PREFIXES: string[];
25
25
  export declare const AGENT_CONFIG_CONFLICT_FILES: Set<string>;
26
+ /**
27
+ * Files regenerated on every start, and therefore excluded from the pre-rebase
28
+ * auto-stash and from divergence handling.
29
+ *
30
+ * Stashing a file that `deployClaudeMd` / `writeClaudeLocal` / `syncClaudeConfig` /
31
+ * `CodexAdapter.deployConfig` rewrites right after the rebase buys nothing and
32
+ * causes stash-pop conflicts when the regenerated version differs from the stashed
33
+ * one. `.mx-leader.lock` and `.mx-runtime` are per-session runtime coordination
34
+ * state: they change on every start and must never be treated as product work.
35
+ *
36
+ * Exported so FR-3 is assertable directly rather than through a full session run.
37
+ */
38
+ export declare const ALWAYS_REGEN: ReadonlySet<string>;
26
39
  /**
27
40
  * True iff `file` (a worktree-root-relative path from `git diff --name-only`)
28
41
  * is an agent-config / hook path whose rebase conflict must block session
@@ -97,6 +110,14 @@ export interface StartOptions {
97
110
  name: string;
98
111
  /** Use experimental Agent SDK runtime instead of claude CLI. */
99
112
  experimental?: boolean;
113
+ /**
114
+ * Agent runtime to launch: `claude` (default) or `codex` (#4227 FR-1).
115
+ *
116
+ * Raw string, validated here rather than at the commander layer so an unknown
117
+ * value produces the exact FR-1 message and a non-zero exit. When absent, the
118
+ * worktree-persisted choice is used, then the default.
119
+ */
120
+ runtime?: string;
100
121
  /** Startup directive — focuses the agent on a specific task before roleguide-driven work. */
101
122
  directive?: string;
102
123
  /** Inject a test message 5s after session start (--exp only, for verification). Part of #2517. */
@@ -1 +1 @@
1
- {"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../../src/commands/start.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgCH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,8BAA8B,UAG1C,CAAC;AACF,eAAO,MAAM,2BAA2B,aAEtC,CAAC;AAEH;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAK3D;AA4BD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAgFjG;AAgDD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC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,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GACjG,OAAO,CAAC,IAAI,CAAC,CAiBf;AAmBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAsC5E;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,gEAAgE;IAChE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kGAAkG;IAClG,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAID,wBAAsB,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAi8BnE"}
@@ -11,7 +11,7 @@ import { createRequire } from 'module';
11
11
  import { dirname, join } from 'path';
12
12
  import { fileURLToPath } from 'url';
13
13
  import { findProjectRoot, findWorktreePath, getSlot, getCurrentBranch, repairWorktreeLinkIfBroken, } from '../lib/worktree.js';
14
- import { syncClaudeConfig, deployBaseHooks, deployClaudeMd, writeClaudeLocalWithBehavioralSelfHeal, launchClaudeSession, checkPriorSyncFailure, verifyAndHealHooks, logSuccess, logDim, logWarning } from '../lib/claude.js';
14
+ import { syncClaudeConfig, deployBaseHooks, deployClaudeMd, writeClaudeLocalWithBehavioralSelfHeal, checkPriorSyncFailure, verifyAndHealHooks, logSuccess, logDim, logWarning } from '../lib/claude.js';
15
15
  import { launchAgentSession } from '../lib/agent-session.js';
16
16
  import { getTeam } from '../lib/catalog.js';
17
17
  import { loadProjectConfig, resolveProjectConfig } from '../lib/project-config.js';
@@ -24,6 +24,11 @@ import { formatRegressionForTranscript, runStartupDoctorCheck } from './doctor.j
24
24
  import { startupReport } from '../lib/startup-report.js';
25
25
  import { flushSpool, shipEvent } from '../lib/startup-shipper.js';
26
26
  import { runStartupMonitorCheck, shouldRunMonitorCheck, recordMonitorCheck } from './monitor.js';
27
+ import { parseRuntimeFlag } from '../lib/runtime/types.js';
28
+ import { persistRuntime, resolveRuntime, RUNTIME_FILENAME } from '../lib/runtime/resolve.js';
29
+ import { ClaudeAdapter } from '../lib/runtime/claude-adapter.js';
30
+ import { CodexAdapter } from '../lib/runtime/codex-adapter.js';
31
+ import { AGENTS_OVERRIDE_FILENAME, CODEX_CONFIG_FILENAME, CODEX_HOOKS_FILENAME, } from '../lib/runtime/codex-config.js';
27
32
  const PACKAGE_NAME = '@memnexus-ai/mx-agent-cli';
28
33
  /**
29
34
  * Agent-config / hook paths whose rebase conflict must FAIL CLOSED
@@ -50,6 +55,31 @@ export const AGENT_CONFIG_CONFLICT_PREFIXES = [
50
55
  export const AGENT_CONFIG_CONFLICT_FILES = new Set([
51
56
  '.claude/settings.json',
52
57
  ]);
58
+ /**
59
+ * Files regenerated on every start, and therefore excluded from the pre-rebase
60
+ * auto-stash and from divergence handling.
61
+ *
62
+ * Stashing a file that `deployClaudeMd` / `writeClaudeLocal` / `syncClaudeConfig` /
63
+ * `CodexAdapter.deployConfig` rewrites right after the rebase buys nothing and
64
+ * causes stash-pop conflicts when the regenerated version differs from the stashed
65
+ * one. `.mx-leader.lock` and `.mx-runtime` are per-session runtime coordination
66
+ * state: they change on every start and must never be treated as product work.
67
+ *
68
+ * Exported so FR-3 is assertable directly rather than through a full session run.
69
+ */
70
+ export const ALWAYS_REGEN = new Set([
71
+ 'AGENTS.md',
72
+ 'CLAUDE.md',
73
+ 'CLAUDE.local.md',
74
+ '.claude/settings.json',
75
+ // Runtime coordination state. Created before the rebase, changes every session.
76
+ '.mx-leader.lock',
77
+ // Runtime selection + generated Codex config (#4227 FR-3).
78
+ RUNTIME_FILENAME,
79
+ AGENTS_OVERRIDE_FILENAME,
80
+ CODEX_CONFIG_FILENAME,
81
+ CODEX_HOOKS_FILENAME,
82
+ ]);
53
83
  /**
54
84
  * True iff `file` (a worktree-root-relative path from `git diff --name-only`)
55
85
  * is an agent-config / hook path whose rebase conflict must block session
@@ -374,6 +404,30 @@ export async function runStart(options) {
374
404
  startupReport.finalize('refused');
375
405
  process.exit(1);
376
406
  }
407
+ // ── --runtime validation (#4227 FR-1) ──────────────────────────────
408
+ // Validated before any filesystem work so a typo costs nothing. An unknown
409
+ // value exits non-zero naming the valid set; it never silently falls back.
410
+ let runtimeFlag;
411
+ try {
412
+ runtimeFlag = parseRuntimeFlag(options.runtime);
413
+ }
414
+ catch (err) {
415
+ console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
416
+ startupReport.finalize('refused');
417
+ process.exit(1);
418
+ }
419
+ // `--runtime codex` and `--exp` are mutually exclusive (#4227 security review S3).
420
+ // The experimental Agent SDK path is Anthropic-specific and has its own launcher, so
421
+ // the combination previously printed `Runtime: codex`, persisted `codex` to
422
+ // `.mx-runtime`, and then launched CLAUDE via the experimental branch — the banner
423
+ // and the persisted state both said Codex while Claude ran. Refused here, before any
424
+ // persistence or output, rather than resolved into a lie.
425
+ if (runtimeFlag === 'codex' && experimental) {
426
+ console.error(chalk.red('Error: --runtime codex cannot be combined with --exp. The experimental Agent SDK ' +
427
+ 'runtime is Anthropic-specific; pick one.'));
428
+ startupReport.finalize('refused');
429
+ process.exit(1);
430
+ }
377
431
  let projectRoot;
378
432
  try {
379
433
  projectRoot = findProjectRoot();
@@ -503,6 +557,22 @@ export async function runStart(options) {
503
557
  roleguide = `${cfg.roleguidesDir}/${name}-leader.md`;
504
558
  }
505
559
  const branch = getCurrentBranch(worktreePath);
560
+ // ── 3a. Resolve runtime (#4227 FR-1/FR-2) ──────────────────────────
561
+ // Precedence: flag > `.mx-runtime` > default claude. Resolution is pure; the
562
+ // `.mx-runtime` write happens in 3a-2, after preflight and the launch gate pass
563
+ // (security review S7).
564
+ const runtimeResolution = resolveRuntime(runtimeFlag, worktreePath);
565
+ // A PERSISTED `codex` plus `--exp` is the same contradiction the flag form is
566
+ // refused for above (S3) — and it needs its own check, because no flag was passed.
567
+ if (runtimeResolution.runtime === 'codex' && experimental) {
568
+ console.error(chalk.red(`Error: this worktree's persisted runtime is codex (${RUNTIME_FILENAME}), which cannot be ` +
569
+ 'combined with --exp. Run without --exp, or switch back with --runtime claude.'));
570
+ startupReport.finalize('refused');
571
+ process.exit(1);
572
+ }
573
+ const adapter = runtimeResolution.runtime === 'codex'
574
+ ? new CodexAdapter({ projectRoot, ...(cfg.projectSlug ? { projectSlug: cfg.projectSlug } : {}) })
575
+ : new ClaudeAdapter({ sessionModel: cfg.sessionModel });
506
576
  console.log();
507
577
  console.log(chalk.cyan.bold('Starting Agent Team'));
508
578
  console.log(chalk.dim('─'.repeat(50)));
@@ -514,10 +584,45 @@ export async function runStart(options) {
514
584
  // #4487: show the resolved model so a typo in mx-agent.config.json is visible
515
585
  // here, not after every team in the fleet fails to launch.
516
586
  console.log(` ${chalk.bold('Model:')} ${cfg.sessionModel}`);
587
+ // #4227 FR-1: name the runtime, its model, and WHERE the choice came from, so a
588
+ // session that silently inherited `.mx-runtime` is visible at a glance.
589
+ console.log(` ${chalk.bold('Runtime:')} ${adapter.id} (${adapter.model}, ${runtimeResolution.source})`);
590
+ if (runtimeResolution.warning) {
591
+ console.log(chalk.yellow(` ⚠ ${runtimeResolution.warning}`));
592
+ }
593
+ if (adapter instanceof CodexAdapter) {
594
+ for (const notice of adapter.bannerNotices({ worktreePath })) {
595
+ console.log(chalk.yellow(` ⚠ ${notice}`));
596
+ }
597
+ }
517
598
  if (directive) {
518
599
  console.log(` ${chalk.bold('Directive:')} ${chalk.yellow(directive)}`);
519
600
  }
520
601
  console.log();
602
+ // ── 3a-2. Runtime preflight, launch gate, then persistence (#4227) ──
603
+ // Refuse BEFORE the leader lock is claimed: a missing binary or an ungated runtime
604
+ // must not leave a lock behind, and neither must ever fall back to another runtime
605
+ // silently (FR-8).
606
+ // ORDERING IS LOAD-BEARING and pinned by start-runtime-wiring.test.ts — moving any
607
+ // of these three below the lock claim, or persisting before the checks, fails tests
608
+ // there.
609
+ try {
610
+ adapter.preflight();
611
+ // Gate before persistence (security review S7): a refused runtime must not leave
612
+ // `.mx-runtime` naming it, or the next flagless start adopts a session that was
613
+ // never allowed to run.
614
+ adapter.assertLaunchAllowed({ worktreePath });
615
+ }
616
+ catch (err) {
617
+ console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
618
+ startupReport.finalize('refused');
619
+ process.exit(1);
620
+ }
621
+ // FR-2: the flag persists, so a later flagless start keeps this runtime. Reached
622
+ // only once the runtime is known usable AND allowed.
623
+ if (runtimeResolution.shouldPersist && !persistRuntime(worktreePath, runtimeResolution.runtime)) {
624
+ console.log(chalk.yellow(` ⚠ Could not write ${RUNTIME_FILENAME} — this runtime choice will not survive a restart.`));
625
+ }
521
626
  // ── 3b. Leader-session start guard + atomic claim (#3946) ───────────
522
627
  // Claim the leader lock BEFORE the fetch/rebase sequence so the exclusive
523
628
  // create is THE mutual-exclusion decision — two simultaneous starts cannot
@@ -582,21 +687,9 @@ export async function runStart(options) {
582
687
  const statusR = spawnSync('git', ['status', '--porcelain'], {
583
688
  cwd: worktreePath, stdio: 'pipe', encoding: 'utf-8',
584
689
  });
585
- // AGENTS.md, CLAUDE.md, CLAUDE.local.md, and .claude/settings.json are always
586
- // regenerated by deployClaudeMd, writeClaudeLocal, and syncClaudeConfig
587
- // after the rebase — stashing them is unnecessary and causes stash pop
588
- // conflicts when the regenerated version differs from the stashed one.
589
- // AGENTS.md joined this set in Phase 0 (#4227): it is now the canonical
590
- // generated instruction file (CLAUDE.md is a @AGENTS.md import shim).
591
- const ALWAYS_REGEN = new Set([
592
- 'AGENTS.md',
593
- 'CLAUDE.md',
594
- 'CLAUDE.local.md',
595
- '.claude/settings.json',
596
- // Runtime coordination state. This file is created before the rebase,
597
- // changes for every session, and must never be treated as product work.
598
- '.mx-leader.lock',
599
- ]);
690
+ // Files in ALWAYS_REGEN (module scope) are rewritten right after the rebase, so
691
+ // they are excluded from the stash and from divergence handling — see that
692
+ // constant's docblock for the per-file rationale.
600
693
  const dirtyLines = statusR.stdout.trim().split('\n').filter(l => l.trim());
601
694
  const hasDirtyFiles = dirtyLines.some(line => {
602
695
  // git status --porcelain format: "XY filename" (or "XY old -> new" for renames)
@@ -651,14 +744,36 @@ export async function runStart(options) {
651
744
  const MAX_AUTO_SKIP = 20; // safety cap
652
745
  let skipped = 0;
653
746
  let resolved = false;
747
+ /**
748
+ * The rebase FAILED WITHOUT STARTING (#4227 security review MF1b).
749
+ *
750
+ * `git rebase` exits non-zero for two very different reasons: it started and
751
+ * hit a conflict (a rebase is now in progress, REBASE_HEAD resolves), or it
752
+ * refused to start at all — "cannot rebase: You have unstaged changes",
753
+ * unmerged index, missing upstream. The pre-fix code could not tell these
754
+ * apart: a missing REBASE_HEAD on the FIRST iteration was read as
755
+ * `resolved = true`, i.e. success, so a rebase that never ran was treated as
756
+ * one that completed. The worktree then silently stayed on its old base with
757
+ * no `rebaseFailed` signal and no accurate message.
758
+ *
759
+ * A missing REBASE_HEAD on a LATER iteration is genuinely resolved: we only
760
+ * reach one after a `rebase --skip` that continued the rebase.
761
+ */
762
+ let neverStarted = false;
654
763
  for (let i = 0; i < MAX_AUTO_SKIP; i++) {
655
764
  // Check if we're still mid-rebase
656
765
  const rebaseHeadR = spawnSync('git', ['rev-parse', '--verify', 'REBASE_HEAD'], {
657
766
  cwd: worktreePath, stdio: 'pipe', encoding: 'utf-8',
658
767
  });
659
768
  if (rebaseHeadR.status !== 0) {
660
- // No longer in rebase — either resolved or something unexpected
661
- resolved = true;
769
+ if (i === 0) {
770
+ // No rebase in progress and we have skipped nothing → it never began.
771
+ neverStarted = true;
772
+ }
773
+ else {
774
+ // No longer in rebase after a successful skip — genuinely resolved.
775
+ resolved = true;
776
+ }
662
777
  break;
663
778
  }
664
779
  const rebaseHead = rebaseHeadR.stdout.trim();
@@ -726,7 +841,26 @@ export async function runStart(options) {
726
841
  // Genuine conflict — not already upstream. Abort and block.
727
842
  break;
728
843
  }
729
- if (!resolved) {
844
+ if (neverStarted) {
845
+ // The rebase refused to start. There is nothing to abort and no conflict
846
+ // list to classify — the worktree is untouched on its old base. Report what
847
+ // git actually said and mark the base stale so the synchronization gate
848
+ // below warns instead of the session implying it rebased.
849
+ const why = (rebaseResult.stderr || '').trim().split('\n')[0]
850
+ || 'git gave no reason';
851
+ console.log();
852
+ console.log(chalk.yellow.bold(` ⚠ Rebase onto origin/${cfg.baseBranch} did not run.`));
853
+ console.log(chalk.yellow(` git refused before starting: ${why}`));
854
+ console.log(chalk.dim(` The worktree is unchanged, on its pre-rebase base.`));
855
+ console.log(chalk.dim(` Resolve when ready: git -C ${worktreePath} rebase origin/${cfg.baseBranch}`));
856
+ console.log();
857
+ if (didStash) {
858
+ restoreOwnStash(worktreePath, stashSha);
859
+ didStash = false;
860
+ }
861
+ rebaseFailed = true;
862
+ }
863
+ else if (!resolved) {
730
864
  // Genuine conflict that couldn't be auto-resolved.
731
865
  const conflictR = spawnSync('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: worktreePath, stdio: 'pipe', encoding: 'utf-8' });
732
866
  const conflictFiles = conflictR.stdout.trim().split('\n').filter(Boolean);
@@ -1048,10 +1182,17 @@ export async function runStart(options) {
1048
1182
  // is confirmed to spawn, so a post-finalize launch failure is not reflected in
1049
1183
  // the recorded outcome. Phase 2 (central shipping + launch-result signal) will
1050
1184
  // revisit whether the outcome should be deferred until spawn is confirmed.
1051
- startupReport.finalize('ok');
1185
+ //
1186
+ // #4227 / security review NEW-15: `finalize` is FIRST-CALL-WINS, so this cannot run
1187
+ // before a step that is still able to refuse. `adapter.deployConfig` became such a
1188
+ // step (it throws on an over-budget instruction file), which is why the non-
1189
+ // experimental path below finalizes after its deploy rather than here.
1052
1190
  if (experimental) {
1191
+ startupReport.finalize('ok');
1053
1192
  // Experimental: Agent SDK runtime with async Slack communication support.
1054
1193
  // Same setup (steps 1-8) — only the session launcher differs.
1194
+ // #4227: the `--exp` SDK path is Anthropic-specific and explicitly deferred, so
1195
+ // it keeps its own launcher and ignores the runtime adapter.
1055
1196
  console.log(chalk.dim(' [experimental] Using Agent SDK runtime'));
1056
1197
  await launchAgentSession({
1057
1198
  worktreePath,
@@ -1066,17 +1207,41 @@ export async function runStart(options) {
1066
1207
  }
1067
1208
  else {
1068
1209
  // The leader lock was already claimed atomically in section 3b (before the
1069
- // rebase). launchClaudeSession patches childPid into it and removes it on
1070
- // exit; the section-3b cleanup backstop covers any earlier exit path.
1071
- await launchClaudeSession({
1210
+ // rebase). The adapter patches childPid into it and removes it on exit; the
1211
+ // section-3b cleanup backstop covers any earlier exit path.
1212
+ const launchContext = {
1072
1213
  worktreePath,
1073
1214
  worktreeName: worktreeDirName,
1074
1215
  branch,
1075
1216
  slot,
1076
1217
  initialPrompt,
1077
1218
  teamName: name,
1078
- sessionModel: cfg.sessionModel,
1079
- });
1219
+ // #4707: the Codex adapter forwards this to the instruction-file generator so a
1220
+ // Codex session resolves its roleguide from the same ref the Claude path uses.
1221
+ baseBranch: cfg.baseBranch,
1222
+ };
1223
+ try {
1224
+ // Runtime-specific config deployment (`.codex/*`, `AGENTS.override.md`). A
1225
+ // no-op on the Claude path — start.ts already deployed `.claude/*` above.
1226
+ // Runs BEFORE finalize because it can refuse (over-budget instruction file),
1227
+ // and a refusal after the lock claim must not leave the lock behind either.
1228
+ adapter.deployConfig(launchContext);
1229
+ // Handoff point: everything the start command owns has now succeeded.
1230
+ startupReport.finalize('ok');
1231
+ await adapter.launch(launchContext);
1232
+ }
1233
+ catch (err) {
1234
+ // A refusal from the adapter (e.g. the Phase 1 gate on --runtime codex, or the
1235
+ // over-budget instruction file) must not leave a leader lock behind for the next
1236
+ // start to trip over, and must be RECORDED as a refusal rather than inheriting
1237
+ // the 'ok' the happy path writes (security review NEW-15). A deployConfig
1238
+ // refusal reaches this before any finalize; a post-finalize launch failure is
1239
+ // the #4350 Phase 2 known limitation and stays 'ok'.
1240
+ removeLock(worktreePath);
1241
+ startupReport.finalize('refused');
1242
+ console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
1243
+ process.exit(1);
1244
+ }
1080
1245
  }
1081
1246
  }
1082
1247
  //# sourceMappingURL=start.js.map