harnessed 4.45.0 → 4.47.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.
package/dist/cli.mjs CHANGED
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdir
3
3
  import { homedir, tmpdir } from 'os';
4
4
  import { join, resolve, dirname, basename, sep, isAbsolute, relative, win32, posix } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
- import { readFile, readdir, stat, rm, unlink, writeFile, cp, mkdir, access, rename, appendFile, copyFile, chmod } from 'fs/promises';
6
+ import { readFile, readdir, stat, rm, unlink, writeFile, cp, mkdir, access, rename, appendFile, copyFile, chmod, mkdtemp } from 'fs/promises';
7
7
  import { Value } from '@sinclair/typebox/value';
8
8
  import lockfile from 'proper-lockfile';
9
9
  import { LineCounter, parseDocument, parse, isSeq, isScalar, stringify } from 'yaml';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.45.0",
41
+ version: "4.47.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -447,10 +447,52 @@ var init_checkpoint_v1 = __esm({
447
447
  );
448
448
  }
449
449
  });
450
+
451
+ // src/workflow/lib/spawnFailure.ts
452
+ var spawnFailure_exports = {};
453
+ __export(spawnFailure_exports, {
454
+ SPAWN_FAILURES: () => SPAWN_FAILURES,
455
+ SpawnFailureError: () => SpawnFailureError,
456
+ classifySpawnError: () => classifySpawnError,
457
+ isRetryableSpawnFailure: () => isRetryableSpawnFailure,
458
+ isSpawnFailure: () => isSpawnFailure
459
+ });
460
+ function isSpawnFailure(v) {
461
+ return typeof v === "string" && SPAWN_FAILURES.includes(v);
462
+ }
463
+ function classifySpawnError(err2) {
464
+ if (!err2 || typeof err2 !== "object") return void 0;
465
+ const tag = err2.failure;
466
+ return isSpawnFailure(tag) ? tag : void 0;
467
+ }
468
+ function isRetryableSpawnFailure(failure) {
469
+ return failure === "SpawnTimeout";
470
+ }
471
+ var SPAWN_FAILURES, SpawnFailureError;
472
+ var init_spawnFailure = __esm({
473
+ "src/workflow/lib/spawnFailure.ts"() {
474
+ SPAWN_FAILURES = [
475
+ "SpawnTimeout",
476
+ "SpawnExitNonZero",
477
+ "SpawnOutputMalformed",
478
+ "SpawnAuthFailed",
479
+ "SpawnRefused"
480
+ ];
481
+ SpawnFailureError = class extends Error {
482
+ constructor(failure, detail) {
483
+ super(detail);
484
+ this.failure = failure;
485
+ this.name = failure;
486
+ }
487
+ failure;
488
+ };
489
+ }
490
+ });
450
491
  var WorkflowStatus, EvidenceRef, SubProgressEntry, CurrentWorkflowV1;
451
492
  var init_currentWorkflow_v1 = __esm({
452
493
  "src/checkpoint/schema/currentWorkflow.v1.ts"() {
453
494
  init_schemaVersion();
495
+ init_spawnFailure();
454
496
  WorkflowStatus = Type.Union([
455
497
  Type.Literal("active"),
456
498
  Type.Literal("paused"),
@@ -526,7 +568,22 @@ var init_currentWorkflow_v1 = __esm({
526
568
  // attempt_budget — the sub's resolved `ralph_max_iterations` ceiling, persisted at
527
569
  // the first failure so the PURE per-turn injector can compare it against
528
570
  // fail_count without reading yaml (src/checkpoint/budget.ts resolves it).
529
- attempt_budget: Type.Optional(Type.Integer({ minimum: 1 }))
571
+ attempt_budget: Type.Optional(Type.Integer({ minimum: 1 })),
572
+ // ── v16.0 Phase 66 T4 — WHICH of the five named spawn failures ended the last
573
+ // attempt (src/workflow/lib/spawnFailure.ts). Before this the kind was flattened
574
+ // into a message string at src/workflow/run.ts's catch and lost for good, so the
575
+ // ledger recorded "failed" with no way to tell a wall-clock timeout (retryable)
576
+ // from a sandbox refusal or a logged-out harness (both deterministic).
577
+ //
578
+ // Additive-optional, and strictly so: an attempt that never supplied a kind must
579
+ // leave the key ABSENT, not null. 13 eval goldens compare the serialized ledger
580
+ // verbatim, and both writers (markSub / annotateSpawnFailure) only assign when
581
+ // the caller passed something. NO schemaVersion bump — old files Value.Check-pass.
582
+ //
583
+ // The enum, not a free string: an unrecognised kind is a wiring bug and should
584
+ // fail the write, which is also what `checkpoint fail --failure` enforces at the
585
+ // CLI boundary before anything is persisted.
586
+ spawn_failure: Type.Optional(Type.Union(SPAWN_FAILURES.map((f) => Type.Literal(f))))
530
587
  },
531
588
  { additionalProperties: false }
532
589
  );
@@ -917,6 +974,7 @@ var init_subAnchor = __esm({
917
974
  // src/checkpoint/ledger.ts
918
975
  var ledger_exports = {};
919
976
  __export(ledger_exports, {
977
+ annotateSpawnFailure: () => annotateSpawnFailure,
920
978
  findSerialBlockers: () => findSerialBlockers,
921
979
  markSub: () => markSub,
922
980
  nextPending: () => nextPending,
@@ -964,10 +1022,18 @@ function markSub(entries, sub, status, opts) {
964
1022
  if (opts?.completion_claim !== void 0) updated.completion_claim = opts.completion_claim;
965
1023
  if (opts?.progress !== void 0) updated.progress = opts.progress;
966
1024
  if (opts?.attempt_budget !== void 0) updated.attempt_budget = opts.attempt_budget;
1025
+ if (opts?.spawn_failure !== void 0) updated.spawn_failure = opts.spawn_failure;
967
1026
  const next = entries.slice();
968
1027
  next[idx] = updated;
969
1028
  return next;
970
1029
  }
1030
+ function annotateSpawnFailure(entries, sub, failure) {
1031
+ const idx = entries.findIndex((e) => e.sub === sub);
1032
+ if (idx === -1) return entries;
1033
+ const next = entries.slice();
1034
+ next[idx] = { ...entries[idx], spawn_failure: failure };
1035
+ return next;
1036
+ }
971
1037
  function reopenSub(entries, sub, reason) {
972
1038
  const idx = entries.findIndex((e) => e.sub === sub);
973
1039
  if (idx === -1) {
@@ -1994,6 +2060,8 @@ var init_en = __esm({
1994
2060
  "doctor.summary.fail": "\nsome checks failed (see fix hints above)",
1995
2061
  "doctor.summary.warn": "\nall checks ok (with warnings \u2014 see hints above)",
1996
2062
  "doctor.summary.pass": "\nall checks passed",
2063
+ "doctor.host_scope": "host: {{host}} \u2014 {{applied}} of {{total}} checks apply\n",
2064
+ "doctor.matrix.legend": "\nn/a = the check is not declared for that host in the registry, so it was not run",
1997
2065
  "check_docs.clean": "documentation discipline: no violations",
1998
2066
  "check_docs.state_line_limit": "STATE.md is {{lines}} lines > the {{limit}}-line digest limit \u2014 archive older phase narrative to RETROSPECTIVE.md (override for one run: HARNESSED_ALLOW_LONG_STATE=1)",
1999
2067
  "check_docs.state_key_decisions": "{{count}} '\u5173\u952E\u51B3\u8BAE ship \u603B\u7ED3' section(s) > {{limit}} \u2014 keep only the current one; move the rest to RETROSPECTIVE.md",
@@ -2586,6 +2654,46 @@ var init_safeCwd = __esm({
2586
2654
  }
2587
2655
  });
2588
2656
 
2657
+ // src/installers/lib/codexMcpServers.ts
2658
+ function parseCodexMcpList(stdout2) {
2659
+ const text = stdout2.trim();
2660
+ if (!text.startsWith("[")) return null;
2661
+ try {
2662
+ const parsed = JSON.parse(text);
2663
+ if (!Array.isArray(parsed)) return null;
2664
+ const names = /* @__PURE__ */ new Set();
2665
+ for (const entry of parsed) {
2666
+ if (typeof entry?.name === "string" && entry.name !== "") names.add(entry.name);
2667
+ }
2668
+ return names;
2669
+ } catch {
2670
+ return null;
2671
+ }
2672
+ }
2673
+ function invalidateCodexMcpCache() {
2674
+ cache2 = null;
2675
+ }
2676
+ async function listOnce() {
2677
+ const r = await runHarnessArgs("codex", ["mcp", "list", "--json"], getMcpSpawnCwd(), 3e4);
2678
+ return r.exitCode === 0 ? parseCodexMcpList(r.stdout) : null;
2679
+ }
2680
+ function listCodexMcpServers() {
2681
+ cache2 = cache2 ?? listOnce();
2682
+ return cache2;
2683
+ }
2684
+ async function isCodexMcpServerRegistered(name) {
2685
+ const names = await listCodexMcpServers();
2686
+ return names ? names.has(name) : false;
2687
+ }
2688
+ var cache2;
2689
+ var init_codexMcpServers = __esm({
2690
+ "src/installers/lib/codexMcpServers.ts"() {
2691
+ init_runClaudeArgs();
2692
+ init_safeCwd();
2693
+ cache2 = null;
2694
+ }
2695
+ });
2696
+
2589
2697
  // src/installers/lib/codexPlugins.ts
2590
2698
  function parseCodexPluginList(stdout2) {
2591
2699
  const text = stdout2.trim();
@@ -2608,9 +2716,9 @@ function parseCodexPluginList(stdout2) {
2608
2716
  return ids;
2609
2717
  }
2610
2718
  function invalidateCodexPluginCache() {
2611
- cache2 = null;
2719
+ cache3 = null;
2612
2720
  }
2613
- async function listOnce() {
2721
+ async function listOnce2() {
2614
2722
  const cwd = getMcpSpawnCwd();
2615
2723
  const json2 = await runHarnessArgs("codex", ["plugin", "list", "--json"], cwd, 3e4);
2616
2724
  const fromJson = json2.exitCode === 0 ? parseCodexPluginList(json2.stdout) : null;
@@ -2620,8 +2728,8 @@ async function listOnce() {
2620
2728
  return table.exitCode === 0 ? parseCodexPluginList(table.stdout) : null;
2621
2729
  }
2622
2730
  function listInstalledCodexPlugins() {
2623
- cache2 = cache2 ?? listOnce();
2624
- return cache2;
2731
+ cache3 = cache3 ?? listOnce2();
2732
+ return cache3;
2625
2733
  }
2626
2734
  async function isCodexPluginInstalled(name) {
2627
2735
  const ids = await listInstalledCodexPlugins();
@@ -2635,12 +2743,12 @@ function withCodexPluginLock(fn) {
2635
2743
  lock = run.catch(() => void 0);
2636
2744
  return run;
2637
2745
  }
2638
- var cache2, lock;
2746
+ var cache3, lock;
2639
2747
  var init_codexPlugins = __esm({
2640
2748
  "src/installers/lib/codexPlugins.ts"() {
2641
2749
  init_runClaudeArgs();
2642
2750
  init_safeCwd();
2643
- cache2 = null;
2751
+ cache3 = null;
2644
2752
  lock = Promise.resolve();
2645
2753
  }
2646
2754
  });
@@ -2648,6 +2756,7 @@ function getUserClaudeJsonPath() {
2648
2756
  return getMcpConfigPath();
2649
2757
  }
2650
2758
  async function readUserClaudeJson() {
2759
+ if (detectPlatform().id === "codex") return {};
2651
2760
  const path = getUserClaudeJsonPath();
2652
2761
  let raw;
2653
2762
  try {
@@ -2664,23 +2773,9 @@ async function readUserClaudeJson() {
2664
2773
  return {};
2665
2774
  }
2666
2775
  }
2667
- function isMcpServerInToml(raw, name) {
2668
- const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2669
- const re = new RegExp(`^\\s*\\[mcp_servers\\.(?:${esc}|"${esc}"|'${esc}')(?:\\]|\\.)`, "m");
2670
- return re.test(raw);
2671
- }
2672
2776
  async function isMcpServerRegistered(name) {
2673
2777
  const platform = detectPlatform();
2674
- if (platform.id === "codex") {
2675
- let raw;
2676
- try {
2677
- raw = await readFile(platform.mcpConfigPath, "utf8");
2678
- } catch (err2) {
2679
- if (err2.code === "ENOENT") return false;
2680
- throw err2;
2681
- }
2682
- return isMcpServerInToml(raw, name);
2683
- }
2778
+ if (platform.id === "codex") return isCodexMcpServerRegistered(name);
2684
2779
  const config = await readUserClaudeJson();
2685
2780
  const servers = config.mcpServers;
2686
2781
  if (!servers || typeof servers !== "object") return false;
@@ -2720,6 +2815,7 @@ async function isPluginRegistered(pluginName) {
2720
2815
  var init_readClaudeConfig = __esm({
2721
2816
  "src/installers/lib/readClaudeConfig.ts"() {
2722
2817
  init_platform();
2818
+ init_codexMcpServers();
2723
2819
  init_codexPlugins();
2724
2820
  }
2725
2821
  });
@@ -3550,8 +3646,8 @@ var init_scale = __esm({
3550
3646
  }
3551
3647
  });
3552
3648
  function extractVerifyBinary(verifyCmd, fallback) {
3553
- const token = verifyCmd?.trim().split(/\s+/)[0];
3554
- if (token && BARE_BIN_RE.test(token) && !NON_COMPONENT_TOKENS.has(token)) return token;
3649
+ const token2 = verifyCmd?.trim().split(/\s+/)[0];
3650
+ if (token2 && BARE_BIN_RE.test(token2) && !NON_COMPONENT_TOKENS.has(token2)) return token2;
3555
3651
  if (BARE_BIN_RE.test(fallback) && !NON_COMPONENT_TOKENS.has(fallback)) return fallback;
3556
3652
  return null;
3557
3653
  }
@@ -4355,6 +4451,15 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
4355
4451
  }
4356
4452
  async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
4357
4453
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
4454
+ const { isSpawnFailure: isSpawnFailure2, SPAWN_FAILURES: SPAWN_FAILURES2 } = await Promise.resolve().then(() => (init_spawnFailure(), spawnFailure_exports));
4455
+ if (opts.failure !== void 0 && !isSpawnFailure2(opts.failure)) {
4456
+ deps.error(
4457
+ `[harnessed] checkpoint fail: unknown --failure kind '${opts.failure}' \u2014 expected one of ${SPAWN_FAILURES2.join(", ")}`
4458
+ );
4459
+ deps.exit(1);
4460
+ return;
4461
+ }
4462
+ const spawnFailure = isSpawnFailure2(opts.failure) ? opts.failure : void 0;
4358
4463
  const preLedger = await readLedgerSafe(deps);
4359
4464
  if (!enforceSerialOrder("fail", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
4360
4465
  deps.exit(1);
@@ -4381,7 +4486,10 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
4381
4486
  await mutateSubProgress2(
4382
4487
  (e) => markIfSeeded(e, sub, "failed", {
4383
4488
  attempt_budget: budget,
4384
- ...nextProgress ? { progress: nextProgress } : {}
4489
+ ...nextProgress ? { progress: nextProgress } : {},
4490
+ // T4 — omitted when absent so an untagged failure leaves NO key on the entry
4491
+ // (13 eval goldens compare the serialized ledger verbatim).
4492
+ ...spawnFailure ? { spawn_failure: spawnFailure } : {}
4385
4493
  })
4386
4494
  );
4387
4495
  await absorbIntentFor(sub);
@@ -4493,6 +4601,9 @@ function registerCheckpoint(program2) {
4493
4601
  ).option(
4494
4602
  "--failing-tests <n>",
4495
4603
  "fail only \u2014 number of tests still failing after this attempt; drives the no-progress circuit breaker (falls back to the evidence-artifact digest when omitted)"
4604
+ ).option(
4605
+ "--failure <kind>",
4606
+ "fail only \u2014 which named spawn failure ended the attempt: SpawnTimeout | SpawnExitNonZero | SpawnOutputMalformed | SpawnAuthFailed | SpawnRefused (recorded on the ledger entry; an unknown value is rejected)"
4496
4607
  ).action(
4497
4608
  async (action, sub, opts) => {
4498
4609
  if (!isAction(action)) {
@@ -4595,9 +4706,9 @@ function defaultDeps2() {
4595
4706
  };
4596
4707
  }
4597
4708
  function resolveBash(deps) {
4598
- if (cache3) return cache3;
4599
- cache3 = compute({ ...defaultDeps2(), ...deps });
4600
- return cache3;
4709
+ if (cache4) return cache4;
4710
+ cache4 = compute({ ...defaultDeps2(), ...deps });
4711
+ return cache4;
4601
4712
  }
4602
4713
  function compute(d) {
4603
4714
  if (d.platform !== "win32") {
@@ -4644,12 +4755,12 @@ function compute(d) {
4644
4755
  }
4645
4756
  return { path: "bash", source: "path-fallback" };
4646
4757
  }
4647
- var dirname9, join22, WSL_STUB_RE, cache3;
4758
+ var dirname9, join22, WSL_STUB_RE, cache4;
4648
4759
  var init_resolveBash = __esm({
4649
4760
  "src/installers/lib/resolveBash.ts"() {
4650
4761
  ({ dirname: dirname9, join: join22 } = win32);
4651
4762
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
4652
- cache3 = null;
4763
+ cache4 = null;
4653
4764
  }
4654
4765
  });
4655
4766
 
@@ -4699,7 +4810,7 @@ async function checkMcpScope() {
4699
4810
  if (detectPlatform().id !== "claude") {
4700
4811
  return {
4701
4812
  name: "mcp scope",
4702
- status: "pass",
4813
+ status: "skipped",
4703
4814
  message: "skipped (claude-only check)"
4704
4815
  };
4705
4816
  }
@@ -5047,7 +5158,7 @@ async function checkAgentTeamsDoctor() {
5047
5158
  if (detectPlatform().id !== "claude") {
5048
5159
  return {
5049
5160
  name: "Agent Teams env",
5050
- status: "pass",
5161
+ status: "skipped",
5051
5162
  message: "skipped (claude-only check)"
5052
5163
  };
5053
5164
  }
@@ -5083,7 +5194,7 @@ async function checkPlanningWithFiles() {
5083
5194
  if (getPluginsRegistry() === null) {
5084
5195
  return {
5085
5196
  name: "planning-with-files plugin",
5086
- status: "pass",
5197
+ status: "skipped",
5087
5198
  message: "skipped (claude-only plugin-cache probe; no plugin registry on this platform)"
5088
5199
  };
5089
5200
  }
@@ -5312,7 +5423,7 @@ async function checkMcpAvailability() {
5312
5423
  if (keyless.length > 0) {
5313
5424
  const vars = keyless.map((k) => k.envVar).join(" / ");
5314
5425
  fixes.push(
5315
- `set ${vars} in the ~/.claude/settings.json "env" block (e.g. {"env": {"${keyless[0]?.envVar}": "<your-key>"}}) or export it in your shell; a mcpServers.<name>.env entry in ~/.claude.json also works`
5426
+ detectPlatform().id === "codex" ? `export ${vars} in your shell (on codex that is the only source this check can read \u2014 its MCP config is TOML and there is no JSON settings file)` : `set ${vars} in the ~/.claude/settings.json "env" block (e.g. {"env": {"${keyless[0]?.envVar}": "<your-key>"}}) or export it in your shell; a mcpServers.<name>.env entry in ~/.claude.json also works`
5316
5427
  );
5317
5428
  }
5318
5429
  return {
@@ -5326,6 +5437,7 @@ var TARGET_SERVERS, CHECK_NAME;
5326
5437
  var init_check_mcp_availability = __esm({
5327
5438
  "src/cli/lib/check-mcp-availability.ts"() {
5328
5439
  init_readClaudeConfig();
5440
+ init_platform();
5329
5441
  init_search_mcp_keys();
5330
5442
  TARGET_SERVERS = Object.keys(SEARCH_MCP_KEY_VARS);
5331
5443
  CHECK_NAME = "MCP servers (tavily/exa)";
@@ -5956,24 +6068,24 @@ var init_check_install_channels = __esm({
5956
6068
  init_assetsRoot();
5957
6069
  }
5958
6070
  });
5959
- function isRelativeFileToken(token) {
5960
- if (!/[\\/]/.test(token)) return false;
5961
- if (ABSOLUTE_RE.test(token)) return false;
5962
- if (/[*?$`]/.test(token)) return false;
6071
+ function isRelativeFileToken(token2) {
6072
+ if (!/[\\/]/.test(token2)) return false;
6073
+ if (ABSOLUTE_RE.test(token2)) return false;
6074
+ if (/[*?$`]/.test(token2)) return false;
5963
6075
  return true;
5964
6076
  }
5965
- function stripQuotes(token) {
5966
- const m = token.match(/^"(.*)"$/);
6077
+ function stripQuotes(token2) {
6078
+ const m = token2.match(/^"(.*)"$/);
5967
6079
  if (m?.[1] !== void 0) return { bare: m[1], quoted: true };
5968
- return { bare: token, quoted: false };
6080
+ return { bare: token2, quoted: false };
5969
6081
  }
5970
6082
  function splitTokens(raw) {
5971
6083
  return raw.split(/\s+/).filter((t2) => t2.length > 0);
5972
6084
  }
5973
6085
  function hookMarkerAt(raw) {
5974
6086
  const tokens = splitTokens(raw);
5975
- for (const [i, token] of tokens.entries()) {
5976
- const { bare: bare2 } = stripQuotes(token);
6087
+ for (const [i, token2] of tokens.entries()) {
6088
+ const { bare: bare2 } = stripQuotes(token2);
5977
6089
  if (!isRelativeFileToken(bare2)) continue;
5978
6090
  const seg = bare2.split(/[\\/]/);
5979
6091
  const base = seg[seg.length - 1];
@@ -5981,8 +6093,8 @@ function hookMarkerAt(raw) {
5981
6093
  const id = COMPILED_HOOK_IDENTITIES.find((k) => base.includes(k));
5982
6094
  return { marker: id ?? base, index: i };
5983
6095
  }
5984
- for (const [i, token] of tokens.entries()) {
5985
- const { bare: bare2 } = stripQuotes(token);
6096
+ for (const [i, token2] of tokens.entries()) {
6097
+ const { bare: bare2 } = stripQuotes(token2);
5986
6098
  if (COMPILED_HOOK_IDENTITIES.includes(bare2))
5987
6099
  return { marker: bare2, index: i };
5988
6100
  }
@@ -5999,12 +6111,12 @@ function resolveHookCommand(raw, deps) {
5999
6111
  }
6000
6112
  let root = null;
6001
6113
  const tokens = splitTokens(raw);
6002
- const out = tokens.map((token) => {
6003
- const { bare: bare2 } = stripQuotes(token);
6004
- if (!isRelativeFileToken(bare2)) return token;
6114
+ const out = tokens.map((token2) => {
6115
+ const { bare: bare2 } = stripQuotes(token2);
6116
+ if (!isRelativeFileToken(bare2)) return token2;
6005
6117
  root = root ?? deps.assetsRoot();
6006
6118
  const abs = join(root, bare2);
6007
- if (!deps.exists(abs)) return token;
6119
+ if (!deps.exists(abs)) return token2;
6008
6120
  return `"${abs.replace(/\\/g, "/")}"`;
6009
6121
  });
6010
6122
  return out.join(" ");
@@ -6173,7 +6285,7 @@ function checkStaleHooks(deps) {
6173
6285
  if (settingsPath === null)
6174
6286
  return {
6175
6287
  name: NAME,
6176
- status: "pass",
6288
+ status: "skipped",
6177
6289
  message: `no settings file on ${detectPlatform().id} \u2014 skipped`
6178
6290
  };
6179
6291
  const raw = readText(settingsPath);
@@ -6371,7 +6483,7 @@ function checkInjectInvalidate(deps) {
6371
6483
  if (settingsPath === null)
6372
6484
  return {
6373
6485
  name: NAME3,
6374
- status: "pass",
6486
+ status: "skipped",
6375
6487
  message: `no settings file on ${detectPlatform().id} \u2014 skipped`
6376
6488
  };
6377
6489
  const raw = readText(settingsPath);
@@ -6502,7 +6614,7 @@ function readInstalledVersions(deps, registryPath) {
6502
6614
  function checkPluginStaleness(overrides) {
6503
6615
  const deps = { ...defaultDeps3(), ...overrides };
6504
6616
  if (deps.registryPath === null) {
6505
- return { name: NAME4, status: "pass", message: "no plugin registry on this harness" };
6617
+ return { name: NAME4, status: "skipped", message: "no plugin registry on this harness" };
6506
6618
  }
6507
6619
  const installed = readInstalledVersions(deps, deps.registryPath);
6508
6620
  if (installed === null) {
@@ -7391,7 +7503,7 @@ function chainProblem(d, pluginName, id) {
7391
7503
  async function checkCodexHooks(deps) {
7392
7504
  const d = { ...defaultDeps4(), ...deps };
7393
7505
  if (d.platformId !== "codex")
7394
- return { name: NAME6, status: "pass", message: `not codex (${d.platformId}) \u2014 skipped` };
7506
+ return { name: NAME6, status: "skipped", message: `not codex (${d.platformId}) \u2014 skipped` };
7395
7507
  const plugins = await d.pluginDirs();
7396
7508
  if (plugins.length === 0)
7397
7509
  return { name: NAME6, status: "pass", message: "no harnessed codex hook plugins installed" };
@@ -7438,75 +7550,180 @@ var init_check_codex_hooks = __esm({
7438
7550
  });
7439
7551
 
7440
7552
  // src/cli/lib/doctor-registry.ts
7441
- var CHECKS;
7553
+ function checksForHost(host) {
7554
+ return CHECKS.filter((c) => c.hosts.includes(host));
7555
+ }
7556
+ var ALL_HOSTS, BOTH, CHECKS;
7442
7557
  var init_doctor_registry = __esm({
7443
7558
  "src/cli/lib/doctor-registry.ts"() {
7444
7559
  init_check_builtin();
7560
+ ALL_HOSTS = ["claude", "codex"];
7561
+ BOTH = ALL_HOSTS;
7445
7562
  CHECKS = [
7446
- async () => checkNodeVersion(),
7447
- checkMcpScope,
7448
- async () => checkJq(),
7449
- async () => checkWinBash(),
7450
- async () => {
7451
- const { checkOrigin: checkOrigin2 } = await Promise.resolve().then(() => (init_origin_check(), origin_check_exports));
7452
- const r = checkOrigin2(process.cwd(), { allowFork: true });
7453
- return { name: "origin URL", status: r.status, message: r.detail, fix: r.fix };
7563
+ // Node runtime version — `process.versions.node`, no harness surface at all.
7564
+ { name: "node \u2265 22", hosts: BOTH, fn: async () => checkNodeVersion() },
7565
+ // claude-only: check-builtin.ts checkMcpScope early-returns unless
7566
+ // detectPlatform().id === 'claude'; it reads ~/.claude.json + project .mcp.json.
7567
+ { name: "mcp scope", hosts: ["claude"], fn: checkMcpScope },
7568
+ // PATH probe (`where`/`which jq`) — the install hint switches on OS, not host.
7569
+ { name: "jq present", hosts: BOTH, fn: async () => checkJq() },
7570
+ // resolveBash() PATH inspection. Its early return is an OS gate (non-Windows),
7571
+ // NOT a host gate — both harnesses need a usable bash on Windows.
7572
+ { name: "bash flavor (win)", hosts: BOTH, fn: async () => checkWinBash() },
7573
+ // git remote of the cwd — no harness surface.
7574
+ {
7575
+ name: "origin URL",
7576
+ hosts: BOTH,
7577
+ fn: async () => {
7578
+ const { checkOrigin: checkOrigin2 } = await Promise.resolve().then(() => (init_origin_check(), origin_check_exports));
7579
+ const r = checkOrigin2(process.cwd(), { allowFork: true });
7580
+ return { name: "origin URL", status: r.status, message: r.detail, fix: r.fix };
7581
+ }
7582
+ },
7583
+ // PATH probe + harnessSkillsDirs() (which spans BOTH harnesses' skills dirs).
7584
+ {
7585
+ name: "gstack prefix",
7586
+ hosts: BOTH,
7587
+ fn: async () => {
7588
+ const { probeGstackPrefix: probeGstackPrefix2 } = await Promise.resolve().then(() => (init_probe_gstack(), probe_gstack_exports));
7589
+ const r = probeGstackPrefix2();
7590
+ return { name: "gstack prefix", status: r.status, message: r.detail, fix: r.fix };
7591
+ }
7592
+ },
7593
+ // Reads the packaged manifests/aliases.yaml — harness-independent.
7594
+ {
7595
+ name: "deprecated manifests",
7596
+ hosts: BOTH,
7597
+ fn: async () => (await Promise.resolve().then(() => (init_check_deprecations(), check_deprecations_exports))).checkDeprecations()
7454
7598
  },
7455
- async () => {
7456
- const { probeGstackPrefix: probeGstackPrefix2 } = await Promise.resolve().then(() => (init_probe_gstack(), probe_gstack_exports));
7457
- const r = probeGstackPrefix2();
7458
- return { name: "gstack prefix", status: r.status, message: r.detail, fix: r.fix };
7599
+ // getSkillsDir() — descriptor-resolved, so it audits whichever harness is active.
7600
+ {
7601
+ name: "token budget",
7602
+ hosts: BOTH,
7603
+ fn: async () => (await Promise.resolve().then(() => (init_check_token_budget(), check_token_budget_exports))).checkTokenBudget()
7604
+ },
7605
+ // claude-only: Agent Teams is a Claude Code env key; the check early-returns
7606
+ // unless detectPlatform().id === 'claude'.
7607
+ {
7608
+ name: "Agent Teams env",
7609
+ hosts: ["claude"],
7610
+ fn: async () => (await Promise.resolve().then(() => (init_check_agent_teams_doctor(), check_agent_teams_doctor_exports))).checkAgentTeamsDoctor()
7611
+ },
7612
+ // claude-only: probes the CC plugin CACHE and early-returns when
7613
+ // getPluginsRegistry() is null (codex has no installed_plugins.json).
7614
+ {
7615
+ name: "planning-with-files plugin",
7616
+ hosts: ["claude"],
7617
+ fn: async () => (await Promise.resolve().then(() => (init_check_planning_with_files(), check_planning_with_files_exports))).checkPlanningWithFiles()
7618
+ },
7619
+ // Both: the plugin-cache probe is registry-gated but the skill probes span
7620
+ // harnessSkillsDirs(), and install_commands computes `--agent` per host.
7621
+ {
7622
+ name: "mattpocock-skills",
7623
+ hosts: BOTH,
7624
+ fn: async () => (await Promise.resolve().then(() => (init_check_mattpocock_skills(), check_mattpocock_skills_exports))).checkMattpocockSkills()
7625
+ },
7626
+ // Both: isMcpServerRegistered branches on codex → `[mcp_servers.*]` in config.toml.
7627
+ {
7628
+ name: "MCP servers (tavily/exa)",
7629
+ hosts: BOTH,
7630
+ fn: async () => (await Promise.resolve().then(() => (init_check_mcp_availability(), check_mcp_availability_exports))).checkMcpAvailability()
7459
7631
  },
7460
- async () => (await Promise.resolve().then(() => (init_check_deprecations(), check_deprecations_exports))).checkDeprecations(),
7461
- async () => (await Promise.resolve().then(() => (init_check_token_budget(), check_token_budget_exports))).checkTokenBudget(),
7462
- async () => (await Promise.resolve().then(() => (init_check_agent_teams_doctor(), check_agent_teams_doctor_exports))).checkAgentTeamsDoctor(),
7463
- async () => (await Promise.resolve().then(() => (init_check_planning_with_files(), check_planning_with_files_exports))).checkPlanningWithFiles(),
7464
- async () => (await Promise.resolve().then(() => (init_check_mattpocock_skills(), check_mattpocock_skills_exports))).checkMattpocockSkills(),
7465
- async () => (await Promise.resolve().then(() => (init_check_mcp_availability(), check_mcp_availability_exports))).checkMcpAvailability(),
7466
7632
  // Phase 18 — opt-in CodeGraph semantic-index detect (always 'pass'; absence of an
7467
- // optional tool is not a health failure).
7468
- async () => (await Promise.resolve().then(() => (init_check_codegraph(), check_codegraph_exports))).checkCodeGraph(process.cwd()),
7633
+ // optional tool is not a health failure). Project-local `.codegraph/` — no host surface.
7634
+ {
7635
+ name: "codegraph",
7636
+ hosts: BOTH,
7637
+ fn: async () => (await Promise.resolve().then(() => (init_check_codegraph(), check_codegraph_exports))).checkCodeGraph(process.cwd())
7638
+ },
7469
7639
  // v4.16.1 T3 — bun presence (warn-only): gstack's upstream setup hard-requires
7470
7640
  // bun; missing bun is THE gstack refresh-failure cause on user dogfood machines.
7471
- async () => (await Promise.resolve().then(() => (init_check_bun(), check_bun_exports))).checkBun(),
7641
+ // Pure PATH probe.
7642
+ { name: "bun present", hosts: BOTH, fn: async () => (await Promise.resolve().then(() => (init_check_bun(), check_bun_exports))).checkBun() },
7472
7643
  // 4.22.1 T4 — dual-guard conflict (warn-only): ECC GateGuard's filename policy
7473
7644
  // vs evidence-guard artifact contract names (subagents cannot fact-retry).
7474
- async () => (await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports))).checkGuardConflict(),
7645
+ // Both: only the settings.json signal degrades on codex — the ecc-plugin signal
7646
+ // goes through isPluginRegistered (which asks `codex plugin list` there) and the
7647
+ // env signal is host-free. ECC ships a codex channel, so the conflict is real there.
7648
+ {
7649
+ name: "guard conflict (GateGuard)",
7650
+ hosts: BOTH,
7651
+ fn: async () => (await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports))).checkGuardConflict()
7652
+ },
7475
7653
  // 4.23.0 (issue #3) — installed workflow-skill integrity (warn-only): flat
7476
7654
  // ~/.claude/skills packs can silently shadow shipped workflows; setup self-heals.
7477
- async () => (await Promise.resolve().then(() => (init_check_skill_integrity(), check_skill_integrity_exports))).checkSkillIntegrity(),
7655
+ // getSkillsDir() — per-host install dir, so it audits either harness.
7656
+ {
7657
+ name: "workflow skill integrity",
7658
+ hosts: BOTH,
7659
+ fn: async () => (await Promise.resolve().then(() => (init_check_skill_integrity(), check_skill_integrity_exports))).checkSkillIntegrity()
7660
+ },
7478
7661
  // Phase 20 — "update available" version check ('warn' only when behind; 'pass'
7479
7662
  // when current/ahead/npm-unreachable — fail-soft, never flips the summary).
7480
- async () => (await Promise.resolve().then(() => (init_check_update(), check_update_exports))).checkUpdate(),
7663
+ // Compares package.json against npm — no harness surface.
7664
+ {
7665
+ name: "update",
7666
+ hosts: BOTH,
7667
+ fn: async () => (await Promise.resolve().then(() => (init_check_update(), check_update_exports))).checkUpdate()
7668
+ },
7481
7669
  // 4.32.4 — dual install-channel conflict (warn-only): npm-global + standalone
7482
- // binary both present → ambiguous PATH resolution + stale-update trap.
7483
- async () => (await Promise.resolve().then(() => (init_check_install_channels(), check_install_channels_exports))).checkInstallChannels(),
7670
+ // binary both present → ambiguous PATH resolution + stale-update trap. The
7671
+ // harnessed CLI's own install, independent of which harness drives it.
7672
+ {
7673
+ name: "install channel",
7674
+ hosts: BOTH,
7675
+ fn: async () => (await Promise.resolve().then(() => (init_check_install_channels(), check_install_channels_exports))).checkInstallChannels()
7676
+ },
7484
7677
  // issue #8 — orphaned harnessed Stop/UserPromptSubmit hooks (warn-only): a hook
7485
7678
  // pointing at a deleted bin/*.mjs makes Claude Code error MODULE_NOT_FOUND every
7486
- // prompt; `harnessed uninstall` now strips them.
7487
- async () => (await Promise.resolve().then(() => (init_check_stale_hooks(), check_stale_hooks_exports))).checkStaleHooks(),
7679
+ // prompt; `harnessed uninstall` now strips them. claude-only: the whole check is
7680
+ // a settings.json read, and getSettingsPath() is null on codex.
7681
+ {
7682
+ name: "stale hooks",
7683
+ hosts: ["claude"],
7684
+ fn: async () => (await Promise.resolve().then(() => (init_check_stale_hooks(), check_stale_hooks_exports))).checkStaleHooks()
7685
+ },
7488
7686
  // 4.32.22 — ECC per-harness detect (optional; pass unless CC-side ecc overlaps
7489
7687
  // the official chrome-devtools-mcp plugin → warn). CC plugin registry + codex
7490
- // sync-clone probed independently.
7491
- async () => (await Promise.resolve().then(() => (init_check_ecc(), check_ecc_exports))).checkEcc(),
7688
+ // sync-clone probed independently — by construction a both-hosts check.
7689
+ { name: "ecc", hosts: BOTH, fn: async () => (await Promise.resolve().then(() => (init_check_ecc(), check_ecc_exports))).checkEcc() },
7492
7690
  // 4.38.0 — half-installed per-turn injection (warn-only): perturn-inject
7493
7691
  // without perturn-inject-invalidate keeps skipping <project-context> after a
7494
7692
  // compact/clear has already dropped the copy it is skipping on behalf of.
7495
- async () => (await Promise.resolve().then(() => (init_check_inject_invalidate(), check_inject_invalidate_exports))).checkInjectInvalidate(),
7693
+ // claude-only: pairs two settings.json hook registrations (null path on codex).
7694
+ {
7695
+ name: "per-turn inject pairing",
7696
+ hosts: ["claude"],
7697
+ fn: async () => (await Promise.resolve().then(() => (init_check_inject_invalidate(), check_inject_invalidate_exports))).checkInjectInvalidate()
7698
+ },
7496
7699
  // Phase 56 — silently stale marketplace plugins (warn-only): `claude plugin
7497
7700
  // install` pins a version into a versioned cache dir and never re-resolves, so
7498
7701
  // the four cc-plugin-marketplace components drift behind without any signal.
7499
7702
  // The only comparison in the codebase between a genuinely DETECTED version and
7500
7703
  // a recorded one — see the header for why the installer-state layer cannot do it.
7501
- async () => (await Promise.resolve().then(() => (init_check_plugin_staleness(), check_plugin_staleness_exports))).checkPluginStaleness(),
7704
+ // claude-only: needs the installed_plugins.json registry (null on codex).
7705
+ {
7706
+ name: "plugin install freshness",
7707
+ hosts: ["claude"],
7708
+ fn: async () => (await Promise.resolve().then(() => (init_check_plugin_staleness(), check_plugin_staleness_exports))).checkPluginStaleness()
7709
+ },
7502
7710
  // Phase 60 — HARNESSED_OFF left on (warn-only): the kill switch silences every
7503
7711
  // first-party hook, so a machine that forgot to unset it looks exactly like a
7504
- // broken install. doctor is where that gets said out loud.
7505
- async () => (await Promise.resolve().then(() => (init_check_ablation(), check_ablation_exports))).checkAblation(),
7712
+ // broken install. doctor is where that gets said out loud. Env var — and the
7713
+ // hooks it silences exist on both harnesses.
7714
+ {
7715
+ name: "ablation switch",
7716
+ hosts: BOTH,
7717
+ fn: async () => (await Promise.resolve().then(() => (init_check_ablation(), check_ablation_exports))).checkAblation()
7718
+ },
7506
7719
  // v16.0 Phase 64 (ADR 0041) — codex hook plugins (warn-only): codex silently
7507
- // skips an untrusted / modified hook, so "installed" is not "running". Skipped
7508
- // (pass) on every non-codex platform.
7509
- async () => (await Promise.resolve().then(() => (init_check_codex_hooks(), check_codex_hooks_exports))).checkCodexHooks()
7720
+ // skips an untrusted / modified hook, so "installed" is not "running". codex-only:
7721
+ // the check early-returns unless the active platform id is `codex`.
7722
+ {
7723
+ name: "codex hook plugins",
7724
+ hosts: ["codex"],
7725
+ fn: async () => (await Promise.resolve().then(() => (init_check_codex_hooks(), check_codex_hooks_exports))).checkCodexHooks()
7726
+ }
7510
7727
  ];
7511
7728
  }
7512
7729
  });
@@ -7909,8 +8126,8 @@ var init_before_spawn = __esm({
7909
8126
  _implCache = /* @__PURE__ */ new Map();
7910
8127
  }
7911
8128
  });
7912
- function isUndefinedVariableError(e) {
7913
- return e instanceof GateEvalError && /undefined variable/i.test(e.message);
8129
+ function isStaticGateConfigError(e) {
8130
+ return e instanceof GateEvalError && STATIC_CONFIG_ERROR.test(e.message);
7914
8131
  }
7915
8132
  function evalGate(expression, context) {
7916
8133
  try {
@@ -7928,7 +8145,7 @@ function evalGate(expression, context) {
7928
8145
  throw new GateEvalError(`Gate eval failed: ${err2.message}`, expression);
7929
8146
  }
7930
8147
  }
7931
- var PARSER_OPTIONS, _parserSingleton, GateEvalError;
8148
+ var PARSER_OPTIONS, _parserSingleton, GateEvalError, STATIC_CONFIG_ERROR;
7932
8149
  var init_exprBuilder = __esm({
7933
8150
  "src/workflow/exprBuilder.ts"() {
7934
8151
  PARSER_OPTIONS = {
@@ -7952,6 +8169,7 @@ var init_exprBuilder = __esm({
7952
8169
  }
7953
8170
  expression;
7954
8171
  };
8172
+ STATIC_CONFIG_ERROR = /undefined variable|cannot read propert(?:y|ies) of (?:undefined|null)|parse error/i;
7955
8173
  }
7956
8174
  });
7957
8175
  var GovernanceStatus, GovernanceV1;
@@ -8149,33 +8367,6 @@ var init_judgmentResolver = __esm({
8149
8367
  }
8150
8368
  });
8151
8369
 
8152
- // src/workflow/lib/completionSchema.ts
8153
- var COMPLETION_SCHEMA;
8154
- var init_completionSchema = __esm({
8155
- "src/workflow/lib/completionSchema.ts"() {
8156
- COMPLETION_SCHEMA = {
8157
- type: "object",
8158
- properties: {
8159
- status: { type: "string", enum: ["COMPLETE", "PARTIAL", "BLOCKED"] },
8160
- phase: { type: "string" },
8161
- summary: { type: "string" },
8162
- blockers: { type: "array", items: { type: "string" } },
8163
- // v3.5.0 Phase 2 — Option 1-Lite signal-driven Agent Teams escalation.
8164
- // spawned subagent SHOULD set this when any of parallelism-gate.yaml 5
8165
- // upgrade triggers fire. harnessed runtime propagates to stderr hint;
8166
- // user opens the team in the main Claude Code session — a spawned subagent
8167
- // cannot form one itself (originally because the SDK never exposed the create
8168
- // tool; since CC v2.1.178 there IS no create tool at all — teams form
8169
- // implicitly on the lead's first background teammate spawn, and teammates
8170
- // cannot nest teammates. See PHASE-2-SPEC.md § Why for the original rationale).
8171
- needs_teams_escalation: { type: "boolean" },
8172
- escalation_reason: { type: "string" }
8173
- },
8174
- required: ["status"]
8175
- };
8176
- }
8177
- });
8178
-
8179
8370
  // src/workflow/lib/sdkReconcile.ts
8180
8371
  function toSdkAgentDefinition(def) {
8181
8372
  return {
@@ -8228,6 +8419,342 @@ var init_spawnTimeout = __esm({
8228
8419
  DEFAULT_SPAWN_TIMEOUT_MS = 60 * 60 * 1e3;
8229
8420
  }
8230
8421
  });
8422
+ function firstMatch(text, patterns) {
8423
+ return patterns.find((p8) => p8.test(text));
8424
+ }
8425
+ function hasDanglingItem(events) {
8426
+ const started = /* @__PURE__ */ new Set();
8427
+ for (const e of events) {
8428
+ const id = e.item?.id;
8429
+ if (!id) continue;
8430
+ if (e.type === "item.started") started.add(id);
8431
+ if (e.type === "item.completed") started.delete(id);
8432
+ }
8433
+ return started.size > 0;
8434
+ }
8435
+ function classifyCodexExec(o) {
8436
+ const corpus = [o.stderr, o.lastMessage ?? "", JSON.stringify(o.events)].join("\n");
8437
+ const auth = firstMatch(corpus, AUTH_PATTERNS);
8438
+ if (auth) {
8439
+ return {
8440
+ ok: false,
8441
+ failure: "SpawnAuthFailed",
8442
+ detail: `codex exec is not authenticated (matched ${auth.source}). Run \`codex login\`.`
8443
+ };
8444
+ }
8445
+ if (o.signal) {
8446
+ return { ok: false, failure: "SpawnExitNonZero", detail: `killed by signal ${o.signal}` };
8447
+ }
8448
+ if (o.exitCode !== 0) {
8449
+ return {
8450
+ ok: false,
8451
+ failure: "SpawnExitNonZero",
8452
+ detail: `codex exec exited ${o.exitCode}: ${o.stderr.trim().slice(0, 300)}`
8453
+ };
8454
+ }
8455
+ const refusal = firstMatch(corpus, REFUSAL_PATTERNS);
8456
+ if (refusal) {
8457
+ return {
8458
+ ok: false,
8459
+ failure: "SpawnRefused",
8460
+ detail: `codex exec refused the work (matched ${refusal.source}) \u2014 exit code was still 0`
8461
+ };
8462
+ }
8463
+ if (o.events.some((e) => e.type === "turn.failed")) {
8464
+ return { ok: false, failure: "SpawnRefused", detail: "codex reported turn.failed" };
8465
+ }
8466
+ if (hasDanglingItem(o.events)) {
8467
+ return {
8468
+ ok: false,
8469
+ failure: "SpawnRefused",
8470
+ detail: "an item.started never completed \u2014 the tool call was rejected (F8)"
8471
+ };
8472
+ }
8473
+ if (!o.events.some((e) => e.type === "turn.completed")) {
8474
+ return {
8475
+ ok: false,
8476
+ failure: "SpawnOutputMalformed",
8477
+ detail: o.events.length === 0 && o.garbageLines > 0 ? `stdout was not JSONL (${o.garbageLines} unparseable lines)` : "the JSONL stream never reached turn.completed"
8478
+ };
8479
+ }
8480
+ if (o.lastMessage === null || o.lastMessage.trim() === "") {
8481
+ return {
8482
+ ok: false,
8483
+ failure: "SpawnOutputMalformed",
8484
+ detail: "the -o last-message file was never written"
8485
+ };
8486
+ }
8487
+ return { ok: true, value: o.lastMessage };
8488
+ }
8489
+ function promoteStructuredOutput(lastMessage) {
8490
+ const trimmed = lastMessage.trim();
8491
+ if (!trimmed.startsWith("{")) return void 0;
8492
+ let parsed;
8493
+ try {
8494
+ parsed = JSON.parse(trimmed);
8495
+ } catch {
8496
+ return void 0;
8497
+ }
8498
+ const status = parsed?.status;
8499
+ if (typeof status !== "string" || !COMPLETION_STATUSES.includes(status)) return void 0;
8500
+ return { status };
8501
+ }
8502
+ function buildArgs(outPath, prompt, opts) {
8503
+ return [
8504
+ "exec",
8505
+ "--ephemeral",
8506
+ "--json",
8507
+ "-o",
8508
+ outPath,
8509
+ "-s",
8510
+ opts.sandbox ?? DEFAULT_CODEX_SANDBOX,
8511
+ ...opts.model ? ["-m", opts.model] : [],
8512
+ "--skip-git-repo-check",
8513
+ prompt
8514
+ ];
8515
+ }
8516
+ function planRequest(args, opts) {
8517
+ const env = { ...process.env, ...opts.env ?? {} };
8518
+ if (process.platform === "win32") {
8519
+ const plan = planWindowsSpawn("codex", args, resolveWindowsBin("codex"));
8520
+ return {
8521
+ command: plan.command,
8522
+ args: plan.args,
8523
+ env,
8524
+ windowsVerbatimArguments: plan.verbatim,
8525
+ ...opts.cwd ? { cwd: opts.cwd } : {}
8526
+ };
8527
+ }
8528
+ return {
8529
+ command: "codex",
8530
+ args,
8531
+ env,
8532
+ windowsVerbatimArguments: false,
8533
+ ...opts.cwd ? { cwd: opts.cwd } : {}
8534
+ };
8535
+ }
8536
+ function realSpawn(req) {
8537
+ const child = spawn(req.command, req.args, {
8538
+ // `shell: false` is the default and must stay that way (F5 pitfall 1).
8539
+ windowsHide: true,
8540
+ stdio: ["ignore", "pipe", "pipe"],
8541
+ env: req.env,
8542
+ windowsVerbatimArguments: req.windowsVerbatimArguments,
8543
+ ...req.cwd ? { cwd: req.cwd } : {}
8544
+ });
8545
+ return {
8546
+ stdout: child.stdout,
8547
+ stderr: child.stderr,
8548
+ kill: () => killProcessTree(child),
8549
+ on: ((event, fn) => child.on(event, fn))
8550
+ };
8551
+ }
8552
+ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
8553
+ return new Promise((resolve23, reject) => {
8554
+ const events = [];
8555
+ let garbageLines = 0;
8556
+ let stderr = "";
8557
+ let stdoutBuf = "";
8558
+ let threadSeen = false;
8559
+ let settled = false;
8560
+ let exited;
8561
+ let openStreams = 2;
8562
+ let timer;
8563
+ let proc;
8564
+ try {
8565
+ proc = spawnFn(req);
8566
+ } catch (e) {
8567
+ reject(new SpawnFailureError("SpawnExitNonZero", `spawn error: ${e.message}`));
8568
+ return;
8569
+ }
8570
+ const finish = () => {
8571
+ if (settled || !exited || openStreams > 0) return;
8572
+ settled = true;
8573
+ clearTimeout(timer);
8574
+ resolve23({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
8575
+ };
8576
+ const fail = (err2) => {
8577
+ if (settled) return;
8578
+ settled = true;
8579
+ clearTimeout(timer);
8580
+ try {
8581
+ proc.kill();
8582
+ } catch {
8583
+ }
8584
+ reject(err2);
8585
+ };
8586
+ proc.stdout.setEncoding("utf8");
8587
+ proc.stdout.on("data", (chunk) => {
8588
+ stdoutBuf += chunk;
8589
+ for (let i = stdoutBuf.indexOf("\n"); i >= 0; i = stdoutBuf.indexOf("\n")) {
8590
+ const line = stdoutBuf.slice(0, i).trim();
8591
+ stdoutBuf = stdoutBuf.slice(i + 1);
8592
+ if (!line) continue;
8593
+ let ev;
8594
+ try {
8595
+ ev = JSON.parse(line);
8596
+ } catch {
8597
+ garbageLines += 1;
8598
+ continue;
8599
+ }
8600
+ events.push(ev);
8601
+ if (!threadSeen && ev.type === "thread.started" && typeof ev.thread_id === "string") {
8602
+ threadSeen = true;
8603
+ onThreadId?.(ev.thread_id);
8604
+ }
8605
+ }
8606
+ });
8607
+ proc.stdout.on("end", () => {
8608
+ openStreams -= 1;
8609
+ finish();
8610
+ });
8611
+ proc.stderr.setEncoding("utf8");
8612
+ proc.stderr.on("data", (chunk) => {
8613
+ stderr += chunk;
8614
+ });
8615
+ proc.stderr.on("end", () => {
8616
+ openStreams -= 1;
8617
+ finish();
8618
+ });
8619
+ proc.on(
8620
+ "error",
8621
+ (e) => fail(new SpawnFailureError("SpawnExitNonZero", `spawn error: ${e.message}`))
8622
+ );
8623
+ proc.on("exit", (code2, signal) => {
8624
+ exited = { code: code2, signal };
8625
+ finish();
8626
+ });
8627
+ if (timeoutMs > 0) {
8628
+ timer = setTimeout(
8629
+ () => fail(
8630
+ new SpawnFailureError(
8631
+ "SpawnTimeout",
8632
+ `codex exec exceeded its ${timeoutMs}ms wall-clock timeout (HARNESSED_SPAWN_TIMEOUT_MS)`
8633
+ )
8634
+ ),
8635
+ timeoutMs
8636
+ );
8637
+ }
8638
+ });
8639
+ }
8640
+ async function codexExecSpawn(def, opts, deps = {}) {
8641
+ const hostId = toHostId(detectPlatform().id);
8642
+ if (hostId !== "codex") throw new HostNotCodexError(hostId);
8643
+ const spawnFn = deps.spawn ?? realSpawn;
8644
+ const timeoutMs = opts.timeoutMs ?? envSpawnTimeoutMs();
8645
+ const prompt = injectFactoryInternalFields(def, def.prompt);
8646
+ const dir = await mkdtemp(join(tmpdir(), "harnessed-codex-exec-"));
8647
+ try {
8648
+ let last;
8649
+ for (let attempt = 1; attempt <= 2; attempt++) {
8650
+ const outPath = join(dir, `last-message-${attempt}.txt`);
8651
+ const req = planRequest(buildArgs(outPath, prompt, opts), opts);
8652
+ let failure;
8653
+ let detail;
8654
+ try {
8655
+ const run = await runOnce(req, spawnFn, timeoutMs, opts.onThreadId);
8656
+ const verdict = classifyCodexExec({
8657
+ ...run,
8658
+ lastMessage: await readIfPresent(outPath)
8659
+ });
8660
+ if (verdict.ok) return toEnvelope(verdict.value);
8661
+ failure = verdict.failure;
8662
+ detail = verdict.detail;
8663
+ } catch (e) {
8664
+ if (!(e instanceof SpawnFailureError)) throw e;
8665
+ failure = e.failure;
8666
+ detail = e.message;
8667
+ }
8668
+ last = new SpawnFailureError(failure, `${detail} [phase ${opts.expertName}]`);
8669
+ if (attempt === 2 || !isRetryableSpawnFailure(failure)) break;
8670
+ }
8671
+ throw last;
8672
+ } finally {
8673
+ await rm(dir, { recursive: true, force: true }).catch(() => {
8674
+ });
8675
+ }
8676
+ }
8677
+ async function readIfPresent(path) {
8678
+ try {
8679
+ return await readFile(path, "utf8");
8680
+ } catch {
8681
+ return null;
8682
+ }
8683
+ }
8684
+ function toEnvelope(lastMessage) {
8685
+ const structured = promoteStructuredOutput(lastMessage);
8686
+ const envelope = {
8687
+ subtype: "success",
8688
+ ...structured ? { structured_output: structured } : {},
8689
+ text: lastMessage,
8690
+ result: lastMessage
8691
+ };
8692
+ return JSON.stringify(envelope);
8693
+ }
8694
+ var DEFAULT_CODEX_SANDBOX, HostNotCodexError, AUTH_PATTERNS, REFUSAL_PATTERNS, COMPLETION_STATUSES;
8695
+ var init_codexExecSpawn = __esm({
8696
+ "src/workflow/lib/codexExecSpawn.ts"() {
8697
+ init_hostPrimitives();
8698
+ init_killTree();
8699
+ init_winSpawn();
8700
+ init_platform();
8701
+ init_sdkReconcile();
8702
+ init_spawnFailure();
8703
+ init_spawnTimeout();
8704
+ DEFAULT_CODEX_SANDBOX = "workspace-write";
8705
+ HostNotCodexError = class extends Error {
8706
+ constructor(hostId) {
8707
+ super(
8708
+ `codexExecSpawn is reachable only from a codex host (this process resolved to '${hostId}'). A claude host never launches codex on its own \u2014 that is the v16.0 outbound boundary.`
8709
+ );
8710
+ this.name = "HostNotCodexError";
8711
+ }
8712
+ };
8713
+ AUTH_PATTERNS = [
8714
+ /not logged in/i,
8715
+ /\bunauthorized\b/i,
8716
+ /\b401\b/,
8717
+ /authentication (?:failed|required)/i,
8718
+ /\bcodex login\b/i,
8719
+ /auth\.json/i,
8720
+ /no (?:valid )?credentials/i
8721
+ ];
8722
+ REFUSAL_PATTERNS = [
8723
+ /Rejected\(/,
8724
+ /exec_command failed/i,
8725
+ /unknown agent_type/i,
8726
+ /sandbox (?:denied|rejected)/i
8727
+ ];
8728
+ COMPLETION_STATUSES = ["COMPLETE", "PARTIAL", "BLOCKED"];
8729
+ }
8730
+ });
8731
+
8732
+ // src/workflow/lib/completionSchema.ts
8733
+ var COMPLETION_SCHEMA;
8734
+ var init_completionSchema = __esm({
8735
+ "src/workflow/lib/completionSchema.ts"() {
8736
+ COMPLETION_SCHEMA = {
8737
+ type: "object",
8738
+ properties: {
8739
+ status: { type: "string", enum: ["COMPLETE", "PARTIAL", "BLOCKED"] },
8740
+ phase: { type: "string" },
8741
+ summary: { type: "string" },
8742
+ blockers: { type: "array", items: { type: "string" } },
8743
+ // v3.5.0 Phase 2 — Option 1-Lite signal-driven Agent Teams escalation.
8744
+ // spawned subagent SHOULD set this when any of parallelism-gate.yaml 5
8745
+ // upgrade triggers fire. harnessed runtime propagates to stderr hint;
8746
+ // user opens the team in the main Claude Code session — a spawned subagent
8747
+ // cannot form one itself (originally because the SDK never exposed the create
8748
+ // tool; since CC v2.1.178 there IS no create tool at all — teams form
8749
+ // implicitly on the lead's first background teammate spawn, and teammates
8750
+ // cannot nest teammates. See PHASE-2-SPEC.md § Why for the original rationale).
8751
+ needs_teams_escalation: { type: "boolean" },
8752
+ escalation_reason: { type: "string" }
8753
+ },
8754
+ required: ["status"]
8755
+ };
8756
+ }
8757
+ });
8231
8758
  async function sdkSpawn(def, opts) {
8232
8759
  const sdkDef = toSdkAgentDefinition(def);
8233
8760
  const injectedPrompt = injectFactoryInternalFields(def, def.prompt);
@@ -8322,25 +8849,23 @@ var init_sdkSpawn = __esm({
8322
8849
  }
8323
8850
  });
8324
8851
 
8325
- // src/workflow/lib/spawnFailure.ts
8326
- function isSpawnFailure(v) {
8327
- return typeof v === "string" && SPAWN_FAILURES.includes(v);
8852
+ // src/workflow/lib/spawnDispatch.ts
8853
+ function resolveSpawnHost() {
8854
+ return toHostId(detectPlatform().id);
8328
8855
  }
8329
- function classifySpawnError(err2) {
8330
- if (!err2 || typeof err2 !== "object") return void 0;
8331
- const tag = err2.failure;
8332
- return isSpawnFailure(tag) ? tag : void 0;
8856
+ async function dispatchSpawn(def, opts, deps = {}) {
8857
+ const host = (deps.hostId ?? resolveSpawnHost)();
8858
+ if (host === "codex") {
8859
+ return (deps.codexExecSpawn ?? codexExecSpawn)(def, { expertName: opts.expertName });
8860
+ }
8861
+ return (deps.sdkSpawn ?? sdkSpawn)(def, opts);
8333
8862
  }
8334
- var SPAWN_FAILURES;
8335
- var init_spawnFailure = __esm({
8336
- "src/workflow/lib/spawnFailure.ts"() {
8337
- SPAWN_FAILURES = [
8338
- "SpawnTimeout",
8339
- "SpawnExitNonZero",
8340
- "SpawnOutputMalformed",
8341
- "SpawnAuthFailed",
8342
- "SpawnRefused"
8343
- ];
8863
+ var init_spawnDispatch = __esm({
8864
+ "src/workflow/lib/spawnDispatch.ts"() {
8865
+ init_hostPrimitives();
8866
+ init_platform();
8867
+ init_codexExecSpawn();
8868
+ init_sdkSpawn();
8344
8869
  }
8345
8870
  });
8346
8871
 
@@ -8842,14 +9367,14 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
8842
9367
  const veto = await resolveSkipVeto(clause.skip_gate, context, packageRoot);
8843
9368
  gateEvalled.push(veto ? { clause, passes: false, reason: veto } : { clause, passes: true });
8844
9369
  } catch (e) {
8845
- if (isUndefinedVariableError(e)) {
9370
+ if (isStaticGateConfigError(e)) {
8846
9371
  console.warn(
8847
- `\u26A0\uFE0F master ${masterName} sub ${clause.sub} gate ${clause.gate} references a variable missing from the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
9372
+ `\u26A0\uFE0F master ${masterName} sub ${clause.sub} gate ${clause.gate} cannot be evaluated against the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
8848
9373
  );
8849
9374
  gateEvalled.push({
8850
9375
  clause,
8851
9376
  passes: false,
8852
- reason: `gate ${clause.gate} misconfigured (undefined variable) \u2014 fail-closed, not fired`
9377
+ reason: `gate ${clause.gate} misconfigured (expression/context drift) \u2014 fail-closed, not fired`
8853
9378
  });
8854
9379
  } else {
8855
9380
  console.warn(
@@ -9094,9 +9619,9 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
9094
9619
  try {
9095
9620
  fires = await resolveJudgmentGate(ph.gate, gateContext, packageRoot);
9096
9621
  } catch (err2) {
9097
- if (isUndefinedVariableError(err2)) {
9622
+ if (isStaticGateConfigError(err2)) {
9098
9623
  console.warn(
9099
- `\u26A0\uFE0F phase ${ph.id} gate ${ph.gate} references a variable missing from the gate context (${err2.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
9624
+ `\u26A0\uFE0F phase ${ph.id} gate ${ph.gate} cannot be evaluated against the gate context (${err2.message}) \u2014 a missing variable, \`in\` against a missing/null member, or an unparseable expression. Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the fact via --context / gateContext defaults.`
9100
9625
  );
9101
9626
  fires = false;
9102
9627
  } else {
@@ -9126,6 +9651,18 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
9126
9651
  ...typeof gateContext.modelTierOverride === "string" ? { modelTierOverride: gateContext.modelTierOverride } : {}
9127
9652
  });
9128
9653
  if (r.status !== "ok") {
9654
+ if (r.failure) {
9655
+ try {
9656
+ const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
9657
+ const { annotateSpawnFailure: annotateSpawnFailure2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
9658
+ const failure = r.failure;
9659
+ await mutateSubProgress2((entries) => annotateSpawnFailure2(entries, workflowName, failure));
9660
+ } catch (err2) {
9661
+ console.warn(
9662
+ `\u26A0\uFE0F could not record spawn failure '${r.failure}' for ${workflowName} on the ledger (${err2.message}); the terminal checkpoint below is unaffected.`
9663
+ );
9664
+ }
9665
+ }
9129
9666
  await completePhase({
9130
9667
  phaseId: ph.id,
9131
9668
  lastTask: `FAILED: phase ${ph.id}: ${r.output}`,
@@ -9166,7 +9703,7 @@ var init_run = __esm({
9166
9703
  init_governance2();
9167
9704
  init_judgmentResolver();
9168
9705
  init_ralphLoop();
9169
- init_sdkSpawn();
9706
+ init_spawnDispatch();
9170
9707
  init_spawnFailure();
9171
9708
  init_loadPhases();
9172
9709
  init_masterOrchestrator();
@@ -9215,7 +9752,7 @@ This applies to: strategic-layer review skip / phase-layer clarification skip /
9215
9752
  const optIn = isRalphLoopOptIn(phase);
9216
9753
  const spawnOnce = async (resumeSessionId, onSessionId) => {
9217
9754
  const injectsRules = phase && typeof phase === "object" && "injects_rules" in phase && Array.isArray(phase.injects_rules) ? phase.injects_rules : void 0;
9218
- return sdkSpawn(
9755
+ return dispatchSpawn(
9219
9756
  buildAgentDef(
9220
9757
  skillName,
9221
9758
  opts?.rolePrompts,
@@ -9337,7 +9874,9 @@ function resolveCapabilityCmd(capability, installedPlugins, installedUserSkills,
9337
9874
  anyDetected = true;
9338
9875
  break;
9339
9876
  }
9340
- missingHints.push(`plugin '${plugin_id}' (\`claude plugin install ${plugin_id}\`)`);
9877
+ missingHints.push(
9878
+ host === "codex" ? `plugin '${plugin_id}' is distributed as a Claude Code plugin and this host has no plugin registry \u2014 unavailable here, no install can change that; treat steps that call it as skipped (record the skip) rather than substituting an equivalent` : `plugin '${plugin_id}' (\`claude plugin install ${plugin_id}\`)`
9879
+ );
9341
9880
  } else {
9342
9881
  if (!skill_dir) {
9343
9882
  missingHints.push(
@@ -9390,6 +9929,34 @@ var init_capabilityResolver = __esm({
9390
9929
  CAPABILITY_CMD_TEMPLATE = /\{\{\s*capabilities\.([a-zA-Z0-9_-]+)\.cmd\s*\}\}/g;
9391
9930
  }
9392
9931
  });
9932
+ function userLangPinPath() {
9933
+ return join(detectPlatform().stateRoot, USER_LANG_PIN);
9934
+ }
9935
+ async function writeUserLangPin(code2) {
9936
+ const path = userLangPinPath();
9937
+ await mkdir(detectPlatform().stateRoot, { recursive: true });
9938
+ await writeFile(path, `${code2}
9939
+ `, "utf8");
9940
+ return path;
9941
+ }
9942
+ function readUserLangPin() {
9943
+ let raw;
9944
+ try {
9945
+ raw = readFileSync(userLangPinPath(), "utf8");
9946
+ } catch {
9947
+ return void 0;
9948
+ }
9949
+ const value = raw.trim();
9950
+ return SUPPORTED2.includes(value) ? value : void 0;
9951
+ }
9952
+ var SUPPORTED2, USER_LANG_PIN;
9953
+ var init_userLangPin = __esm({
9954
+ "src/cli/lib/userLangPin.ts"() {
9955
+ init_platform();
9956
+ SUPPORTED2 = ["en", "zh-Hans"];
9957
+ USER_LANG_PIN = "user-lang";
9958
+ }
9959
+ });
9393
9960
 
9394
9961
  // src/cli/prompt.ts
9395
9962
  var prompt_exports = {};
@@ -9510,7 +10077,7 @@ async function renderPreserveCategories(categories, packageRoot, host) {
9510
10077
  }
9511
10078
  }
9512
10079
  async function buildLanguageSection(packageRoot, host = toHostId(detectPlatform().id)) {
9513
- const code2 = process.env.HARNESSED_USER_LANG;
10080
+ const code2 = process.env.HARNESSED_USER_LANG || readUserLangPin();
9514
10081
  if (!code2) return "";
9515
10082
  const name = LANG_NAMES[code2] ?? code2;
9516
10083
  const categories = await renderPreserveCategories(
@@ -9620,6 +10187,7 @@ var init_prompt = __esm({
9620
10187
  init_capabilityResolver();
9621
10188
  init_hostPrimitives();
9622
10189
  init_rolePromptHostRender();
10190
+ init_userLangPin();
9623
10191
  DEFAULT_MAX_ITERATIONS = 20;
9624
10192
  DEFAULT_MODEL = "sonnet";
9625
10193
  DEFAULT_SPECIALIST = "Implementation Engineer";
@@ -9905,13 +10473,13 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
9905
10473
  if (veto) skip.push({ sub: clause.sub, reason: veto });
9906
10474
  else fire.push(fireEntry(clause, master));
9907
10475
  } catch (e) {
9908
- if (isUndefinedVariableError(e)) {
10476
+ if (isStaticGateConfigError(e)) {
9909
10477
  deps.warn(
9910
- `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} references a variable missing from the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
10478
+ `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} cannot be evaluated against the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
9911
10479
  );
9912
10480
  skip.push({
9913
10481
  sub: clause.sub,
9914
- reason: `gate ${clause.gate} misconfigured (undefined variable) \u2014 fail-closed, not fired`
10482
+ reason: `gate ${clause.gate} misconfigured (expression/context drift) \u2014 fail-closed, not fired`
9915
10483
  });
9916
10484
  } else {
9917
10485
  deps.warn(
@@ -11318,6 +11886,7 @@ var init_mcpHttpAdd2 = __esm({
11318
11886
  init_security();
11319
11887
  init_platform();
11320
11888
  init_backup();
11889
+ init_codexMcpServers();
11321
11890
  init_confirm();
11322
11891
  init_diff();
11323
11892
  init_err();
@@ -11449,7 +12018,7 @@ ${newEntry}
11449
12018
  return { aborted: true, reason };
11450
12019
  }
11451
12020
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
11452
- const bk = await backup(plan, ctx);
12021
+ const bk = await backup(bin === "codex" ? { files: [] } : plan, ctx);
11453
12022
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
11454
12023
  const spawnCwd = install.cwd ?? getMcpSpawnCwd();
11455
12024
  const r = await runHarnessArgs(bin, addArgs, spawnCwd);
@@ -11472,9 +12041,11 @@ ${newEntry}
11472
12041
  )
11473
12042
  };
11474
12043
  }
12044
+ if (bin === "codex") invalidateCodexMcpCache();
11475
12045
  const registered = await isMcpServerRegistered(name);
11476
12046
  if (!registered) {
11477
- const cfgLabel = bin === "codex" ? "[mcp_servers] table of ~/.codex/config.toml" : "mcpServers map of ~/.claude.json";
12047
+ const cfgLabel = bin === "codex" ? "the `codex mcp list --json` listing" : "mcpServers map of ~/.claude.json";
12048
+ const cfgHint = bin === "codex" ? "the add reported success but the listing does not show it \u2014 `codex mcp add` may have written under a different CODEX_HOME, or the listing could not be parsed" : `file may have been overwritten, or ${bin} mcp add wrote to a non-default location`;
11478
12049
  return {
11479
12050
  ok: false,
11480
12051
  phase: "verify",
@@ -11482,7 +12053,7 @@ ${newEntry}
11482
12053
  error: err(
11483
12054
  ctx,
11484
12055
  "/spec/verify/cmd",
11485
- `verify: '${name}' not found in ${cfgLabel} after install spawn exit 0 (file may have been overwritten, or ${bin} mcp add wrote to a non-default location)`,
12056
+ `verify: '${name}' not found in ${cfgLabel} after install spawn exit 0 (${cfgHint})`,
11486
12057
  "verify-failed"
11487
12058
  )
11488
12059
  };
@@ -11500,6 +12071,7 @@ var init_mcpStdioAdd2 = __esm({
11500
12071
  init_security();
11501
12072
  init_platform();
11502
12073
  init_backup();
12074
+ init_codexMcpServers();
11503
12075
  init_confirm();
11504
12076
  init_diff();
11505
12077
  init_err();
@@ -11597,7 +12169,7 @@ ${newEntry}
11597
12169
  return { aborted: true, reason };
11598
12170
  }
11599
12171
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
11600
- const bk = await backup(plan, ctx);
12172
+ const bk = await backup(bin === "codex" ? { files: [] } : plan, ctx);
11601
12173
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
11602
12174
  const spawnCwd = install.cwd ?? getMcpSpawnCwd();
11603
12175
  const r = await runHarnessArgs(bin, addArgs, spawnCwd);
@@ -11620,9 +12192,11 @@ ${newEntry}
11620
12192
  )
11621
12193
  };
11622
12194
  }
12195
+ if (bin === "codex") invalidateCodexMcpCache();
11623
12196
  const registered = await isMcpServerRegistered(name);
11624
12197
  if (!registered) {
11625
- const cfgLabel = bin === "codex" ? "[mcp_servers] table of ~/.codex/config.toml" : "mcpServers map of ~/.claude.json";
12198
+ const cfgLabel = bin === "codex" ? "the `codex mcp list --json` listing" : "mcpServers map of ~/.claude.json";
12199
+ const cfgHint = bin === "codex" ? "the add reported success but the listing does not show it \u2014 `codex mcp add` may have written under a different CODEX_HOME, or the listing could not be parsed" : `file may have been overwritten, or ${bin} mcp add wrote to a non-default location`;
11626
12200
  return {
11627
12201
  ok: false,
11628
12202
  phase: "verify",
@@ -11630,7 +12204,7 @@ ${newEntry}
11630
12204
  error: err(
11631
12205
  ctx,
11632
12206
  "/spec/verify/cmd",
11633
- `verify: '${name}' not found in ${cfgLabel} after install spawn exit 0 (file may have been overwritten, or ${bin} mcp add wrote to a non-default location)`,
12207
+ `verify: '${name}' not found in ${cfgLabel} after install spawn exit 0 (${cfgHint})`,
11634
12208
  "verify-failed"
11635
12209
  )
11636
12210
  };
@@ -12981,7 +13555,7 @@ async function runAutoInstall(opts) {
12981
13555
  if (!opts.autoInstall) {
12982
13556
  return out;
12983
13557
  }
12984
- const results = await Promise.all(CHECKS.map((c) => c()));
13558
+ const results = await Promise.all(CHECKS.map((c) => c.fn()));
12985
13559
  const installables = results.filter(
12986
13560
  (r) => r.status === "warn" && Array.isArray(r.install_commands) && r.install_commands.length > 0
12987
13561
  );
@@ -14058,41 +14632,161 @@ function registerCompact(program2) {
14058
14632
 
14059
14633
  // src/cli/doctor.ts
14060
14634
  init_i18n();
14635
+
14636
+ // src/cli/lib/doctor-matrix.ts
14637
+ var NOT_APPLICABLE = "n/a";
14638
+ var SUMMARY_ROW = "summary";
14639
+ var CHECK_COL = "check";
14640
+ var GUTTER = " ";
14641
+ function summarise(results) {
14642
+ if (results.some((r) => r.status === "fail")) return "fail";
14643
+ if (results.some((r) => r.status === "warn")) return "warn";
14644
+ return "pass";
14645
+ }
14646
+ function token(cell2) {
14647
+ return cell2 === null ? NOT_APPLICABLE : cell2.status;
14648
+ }
14649
+ function pad(text, width) {
14650
+ return text + " ".repeat(Math.max(0, width - text.length));
14651
+ }
14652
+ function renderMatrix(m, legend) {
14653
+ const nameW = Math.max(
14654
+ CHECK_COL.length,
14655
+ SUMMARY_ROW.length,
14656
+ ...m.checks.map((c) => c.name.length)
14657
+ );
14658
+ const colW = m.hosts.map(
14659
+ (h) => Math.max(h.length, m.summary[h].length, ...m.checks.map((c) => token(c.cells[h]).length))
14660
+ );
14661
+ const line = (first, cells) => [pad(first, nameW), ...cells.map((c, i) => pad(c, colW[i] ?? c.length))].join(GUTTER).trimEnd();
14662
+ const rule = line(
14663
+ "-".repeat(nameW),
14664
+ colW.map((w) => "-".repeat(w))
14665
+ );
14666
+ return [
14667
+ line(
14668
+ CHECK_COL,
14669
+ m.hosts.map((h) => h)
14670
+ ),
14671
+ rule,
14672
+ ...m.checks.map(
14673
+ (c) => line(
14674
+ c.name,
14675
+ m.hosts.map((h) => token(c.cells[h]))
14676
+ )
14677
+ ),
14678
+ rule,
14679
+ line(
14680
+ SUMMARY_ROW,
14681
+ m.hosts.map((h) => m.summary[h])
14682
+ ),
14683
+ legend
14684
+ ].join("\n");
14685
+ }
14686
+
14687
+ // src/cli/doctor.ts
14061
14688
  init_doctor_registry();
14689
+ var MARKS = { pass: "\u2713", warn: "\u26A0", fail: "\u2717", skipped: "-" };
14690
+ async function runChecks(checks) {
14691
+ const settled = await Promise.allSettled(checks.map((c) => c.fn()));
14692
+ return settled.map(
14693
+ (s, i) => s.status === "fulfilled" ? s.value : {
14694
+ name: checks[i]?.name ?? `check #${i + 1}`,
14695
+ status: "warn",
14696
+ message: `check crashed: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`,
14697
+ fix: "this check was skipped; the other checks above are unaffected"
14698
+ }
14699
+ );
14700
+ }
14701
+ async function runAsHost(host, checks) {
14702
+ const prev = process.env.HARNESSED_PLATFORM;
14703
+ process.env.HARNESSED_PLATFORM = host;
14704
+ try {
14705
+ return await runChecks(checks);
14706
+ } finally {
14707
+ if (prev === void 0) delete process.env.HARNESSED_PLATFORM;
14708
+ else process.env.HARNESSED_PLATFORM = prev;
14709
+ }
14710
+ }
14711
+ async function buildMatrix() {
14712
+ const perHost = /* @__PURE__ */ new Map();
14713
+ const summary = {};
14714
+ for (const host of ALL_HOSTS) {
14715
+ const applicable = checksForHost(host);
14716
+ const results = await runAsHost(host, applicable);
14717
+ perHost.set(
14718
+ host,
14719
+ new Map(
14720
+ results.map((r, i) => [
14721
+ applicable[i]?.name ?? r.name,
14722
+ { status: r.status, message: r.message, ...r.fix ? { fix: r.fix } : {} }
14723
+ ])
14724
+ )
14725
+ );
14726
+ summary[host] = summarise(results);
14727
+ }
14728
+ return {
14729
+ hosts: ALL_HOSTS,
14730
+ checks: CHECKS.map((c) => ({
14731
+ name: c.name,
14732
+ hosts: c.hosts,
14733
+ cells: Object.fromEntries(
14734
+ ALL_HOSTS.map((h) => [h, perHost.get(h)?.get(c.name) ?? null])
14735
+ )
14736
+ })),
14737
+ summary
14738
+ };
14739
+ }
14740
+ function printList(results) {
14741
+ for (const r of results) {
14742
+ console.log(`${MARKS[r.status]} ${r.name} \u2014 ${r.message}`);
14743
+ if (r.status !== "pass" && r.status !== "skipped" && r.fix) console.log(` fix: ${r.fix}`);
14744
+ }
14745
+ }
14062
14746
  function registerDoctor(program2) {
14063
14747
  program2.command("doctor").description(
14064
- "Preflight checks (Node / MCP scope / jq / Win bash / origin URL / gstack prefix / deprecations / token budget / Agent Teams / planning-with-files / mattpocock-skills / MCP availability / ECC / plugin freshness)"
14065
- ).option("--json", "output JSON instead of human-readable").action(async (opts) => {
14066
- const settled = await Promise.allSettled(CHECKS.map((c) => c()));
14067
- const results = settled.map(
14068
- (s, i) => s.status === "fulfilled" ? s.value : {
14069
- name: `check #${i + 1}`,
14070
- status: "warn",
14071
- message: `check crashed: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`,
14072
- fix: "this check was skipped; the other checks above are unaffected"
14748
+ "Preflight checks (Node / MCP scope / jq / Win bash / origin URL / gstack prefix / deprecations / token budget / Agent Teams / planning-with-files / mattpocock-skills / MCP availability / ECC / plugin freshness / codex hooks)"
14749
+ ).option("--json", "output JSON instead of human-readable").option(
14750
+ "--host <id>",
14751
+ `run only the checks that apply to one harness (${ALL_HOSTS.join(" | ")}), resolved as that harness`
14752
+ ).option("--matrix", "report every check against every harness (check \xD7 host table)").action(async (opts) => {
14753
+ if (opts.matrix && opts.host !== void 0) {
14754
+ console.error("--matrix and --host are mutually exclusive (--matrix covers every host)");
14755
+ process.exit(2);
14756
+ }
14757
+ if (opts.matrix) {
14758
+ const matrix2 = await buildMatrix();
14759
+ if (opts.json) console.log(JSON.stringify({ matrix: matrix2 }, null, 2));
14760
+ else console.log(renderMatrix(matrix2, t("doctor.matrix.legend")));
14761
+ process.exit(ALL_HOSTS.some((h) => matrix2.summary[h] === "fail") ? 1 : 0);
14762
+ }
14763
+ let host = null;
14764
+ if (opts.host !== void 0) {
14765
+ if (!ALL_HOSTS.includes(opts.host)) {
14766
+ console.error(
14767
+ `--host: unknown id '${opts.host}' (expected one of: ${ALL_HOSTS.join(" | ")})`
14768
+ );
14769
+ process.exit(2);
14073
14770
  }
14074
- );
14075
- const hasFail = results.some((r) => r.status === "fail");
14076
- const hasWarn = results.some((r) => r.status === "warn");
14771
+ host = opts.host;
14772
+ }
14773
+ const checks = host === null ? CHECKS : checksForHost(host);
14774
+ const results = host === null ? await runChecks(checks) : await runAsHost(host, checks);
14775
+ const summary = summarise(results);
14077
14776
  if (opts.json) {
14078
- console.log(
14079
- JSON.stringify(
14080
- { checks: results, summary: hasFail ? "fail" : hasWarn ? "warn" : "pass" },
14081
- null,
14082
- 2
14083
- )
14084
- );
14777
+ console.log(JSON.stringify({ host, checks: results, summary }, null, 2));
14085
14778
  } else {
14086
- for (const r of results) {
14087
- const mark = r.status === "pass" ? "\u2713" : r.status === "warn" ? "\u26A0" : "\u2717";
14088
- console.log(`${mark} ${r.name} \u2014 ${r.message}`);
14089
- if (r.status !== "pass" && r.fix) console.log(` fix: ${r.fix}`);
14779
+ if (host !== null) {
14780
+ console.log(
14781
+ t("doctor.host_scope", { host, applied: checks.length, total: CHECKS.length })
14782
+ );
14090
14783
  }
14784
+ printList(results);
14091
14785
  console.log(
14092
- hasFail ? t("doctor.summary.fail") : hasWarn ? t("doctor.summary.warn") : t("doctor.summary.pass")
14786
+ summary === "fail" ? t("doctor.summary.fail") : summary === "warn" ? t("doctor.summary.warn") : t("doctor.summary.pass")
14093
14787
  );
14094
14788
  }
14095
- process.exit(hasFail ? 1 : 0);
14789
+ process.exit(summary === "fail" ? 1 : 0);
14096
14790
  });
14097
14791
  }
14098
14792
 
@@ -16099,6 +16793,7 @@ async function enableAgentTeamsInSettings() {
16099
16793
  // src/cli/lib/enableUserLangInSettings.ts
16100
16794
  init_platform();
16101
16795
  init_settingsWriter();
16796
+ init_userLangPin();
16102
16797
  var ENV_KEY2 = "HARNESSED_USER_LANG";
16103
16798
  function detectUserLang(override) {
16104
16799
  if (override) {
@@ -16118,13 +16813,17 @@ function safeIntlLocale2() {
16118
16813
  }
16119
16814
  async function enableUserLangInSettings(override) {
16120
16815
  const platform = detectPlatform();
16816
+ const detected = detectUserLang(override);
16121
16817
  if (!platform.supportsEnvKeyWrite) {
16122
- return {
16123
- status: "warn",
16124
- message: `platform '${platform.id}' does not support env-key settings writes (capability-absent) \u2014 ${ENV_KEY2} skipped`
16125
- };
16818
+ try {
16819
+ return { status: "pinned", path: await writeUserLangPin(detected), detected };
16820
+ } catch (e) {
16821
+ return {
16822
+ status: "warn",
16823
+ message: `platform '${platform.id}' has no env-key store and the ${ENV_KEY2} pin could not be written (${e.message})`
16824
+ };
16825
+ }
16126
16826
  }
16127
- const detected = detectUserLang(override);
16128
16827
  const r = await mergeSettingsEnvKey(ENV_KEY2, detected, {
16129
16828
  skipIfPresent: () => override === void 0
16130
16829
  });
@@ -16383,7 +17082,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
16383
17082
  function shouldOverwriteFile(content) {
16384
17083
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
16385
17084
  }
16386
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync25 = (p8) => readFileSync(p8, "utf8"), hostRender) {
17085
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync26 = (p8) => readFileSync(p8, "utf8"), hostRender) {
16387
17086
  const results = [];
16388
17087
  const aggregatedWarnings = /* @__PURE__ */ new Set();
16389
17088
  for (const name of slashNames) {
@@ -16402,7 +17101,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
16402
17101
  if (fileExists2(path)) {
16403
17102
  let existing = "";
16404
17103
  try {
16405
- existing = readFileSync25(path);
17104
+ existing = readFileSync26(path);
16406
17105
  } catch {
16407
17106
  existing = "";
16408
17107
  }
@@ -16524,6 +17223,7 @@ async function renderSkillFile(skillName, skillsBase, capabilities, installedPlu
16524
17223
  const needsWrite = localeBodySelected || finalBody !== body;
16525
17224
  if (!needsWrite) {
16526
17225
  result.warnings = rendered.warnings;
17226
+ await stripLocaleSiblings(dir);
16527
17227
  return result;
16528
17228
  }
16529
17229
  try {
@@ -16534,17 +17234,18 @@ async function renderSkillFile(skillName, skillsBase, capabilities, installedPlu
16534
17234
  result.error = `write failed: ${e.message}`;
16535
17235
  return result;
16536
17236
  }
16537
- if (localeBodySelected) {
16538
- for (const loc of LOCALE_SIBLINGS) {
16539
- const sibling = skillBodyFilename(loc);
16540
- if (sibling === "SKILL.md") continue;
16541
- try {
16542
- await rm(join(dir, sibling), { force: true });
16543
- } catch {
16544
- }
17237
+ await stripLocaleSiblings(dir);
17238
+ return result;
17239
+ }
17240
+ async function stripLocaleSiblings(dir) {
17241
+ for (const loc of LOCALE_SIBLINGS) {
17242
+ const sibling = skillBodyFilename(loc);
17243
+ if (sibling === "SKILL.md") continue;
17244
+ try {
17245
+ await rm(join(dir, sibling), { force: true });
17246
+ } catch {
16545
17247
  }
16546
17248
  }
16547
- return result;
16548
17249
  }
16549
17250
  async function renderAllSkills(skillNames, skillsBase, workflowsDir, homedirOverride, locale, host) {
16550
17251
  const resolvedLocale = locale ?? getLocale();