@memnexus-ai/mx-agent-cli 0.1.303 → 0.1.304

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 (159) hide show
  1. package/dist/agent-config/.mx-config-generation.json +2 -2
  2. package/dist/agent-config/AGENTS.md.template +1 -1
  3. package/dist/agent-config/agents/bar-raiser.md +41 -1
  4. package/dist/agent-config/agents/git-expert.md +58 -54
  5. package/dist/agent-config/claude-md/CLAUDE.core.md +1 -1
  6. package/dist/agent-config/hooks/session-idle-gate.sh +14 -1
  7. package/dist/agent-config/hooks/subagent-write-guard.sh +198 -12
  8. package/dist/agent-config/hooks/worktree-guard.sh +8 -6
  9. package/dist/agent-config/skills/mx-post-merge-sync/SKILL.md +57 -51
  10. package/dist/commands/codex-agent-gate.d.ts +1 -2
  11. package/dist/commands/codex-agent-gate.d.ts.map +1 -1
  12. package/dist/commands/codex-agent-gate.js +1 -2
  13. package/dist/commands/codex-agent-gate.js.map +1 -1
  14. package/dist/commands/codex-deploy-config.d.ts +6 -0
  15. package/dist/commands/codex-deploy-config.d.ts.map +1 -1
  16. package/dist/commands/codex-deploy-config.js +28 -8
  17. package/dist/commands/codex-deploy-config.js.map +1 -1
  18. package/dist/commands/codex-prove-guards.d.ts +2 -0
  19. package/dist/commands/codex-prove-guards.d.ts.map +1 -1
  20. package/dist/commands/codex-prove-guards.js +31 -3
  21. package/dist/commands/codex-prove-guards.js.map +1 -1
  22. package/dist/commands/codex-trust-keys.d.ts +2 -0
  23. package/dist/commands/codex-trust-keys.d.ts.map +1 -1
  24. package/dist/commands/codex-trust-keys.js +27 -7
  25. package/dist/commands/codex-trust-keys.js.map +1 -1
  26. package/dist/commands/coordination.d.ts +16 -0
  27. package/dist/commands/coordination.d.ts.map +1 -1
  28. package/dist/commands/coordination.js +24 -2
  29. package/dist/commands/coordination.js.map +1 -1
  30. package/dist/commands/create.d.ts +164 -7
  31. package/dist/commands/create.d.ts.map +1 -1
  32. package/dist/commands/create.js +293 -91
  33. package/dist/commands/create.js.map +1 -1
  34. package/dist/commands/doctor.d.ts +17 -0
  35. package/dist/commands/doctor.d.ts.map +1 -1
  36. package/dist/commands/doctor.js +33 -0
  37. package/dist/commands/doctor.js.map +1 -1
  38. package/dist/commands/gh.d.ts +3 -2
  39. package/dist/commands/gh.d.ts.map +1 -1
  40. package/dist/commands/gh.js +3 -2
  41. package/dist/commands/gh.js.map +1 -1
  42. package/dist/commands/new.d.ts +132 -17
  43. package/dist/commands/new.d.ts.map +1 -1
  44. package/dist/commands/new.js +426 -74
  45. package/dist/commands/new.js.map +1 -1
  46. package/dist/commands/start.d.ts +6 -0
  47. package/dist/commands/start.d.ts.map +1 -1
  48. package/dist/commands/start.js +105 -17
  49. package/dist/commands/start.js.map +1 -1
  50. package/dist/commands/status.d.ts +7 -0
  51. package/dist/commands/status.d.ts.map +1 -1
  52. package/dist/commands/status.js +21 -1
  53. package/dist/commands/status.js.map +1 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +28 -4
  56. package/dist/index.js.map +1 -1
  57. package/dist/lib/agent-session.d.ts +11 -0
  58. package/dist/lib/agent-session.d.ts.map +1 -1
  59. package/dist/lib/agent-session.js +26 -7
  60. package/dist/lib/agent-session.js.map +1 -1
  61. package/dist/lib/behavioral-injection.d.ts.map +1 -1
  62. package/dist/lib/behavioral-injection.js +25 -7
  63. package/dist/lib/behavioral-injection.js.map +1 -1
  64. package/dist/lib/catalog-commit.d.ts.map +1 -1
  65. package/dist/lib/catalog-commit.js +17 -14
  66. package/dist/lib/catalog-commit.js.map +1 -1
  67. package/dist/lib/catalog.d.ts +93 -2
  68. package/dist/lib/catalog.d.ts.map +1 -1
  69. package/dist/lib/catalog.js +116 -9
  70. package/dist/lib/catalog.js.map +1 -1
  71. package/dist/lib/claude.d.ts.map +1 -1
  72. package/dist/lib/claude.js +28 -4
  73. package/dist/lib/claude.js.map +1 -1
  74. package/dist/lib/fleet-data.d.ts +98 -9
  75. package/dist/lib/fleet-data.d.ts.map +1 -1
  76. package/dist/lib/fleet-data.js +353 -34
  77. package/dist/lib/fleet-data.js.map +1 -1
  78. package/dist/lib/fleet-render.d.ts +8 -1
  79. package/dist/lib/fleet-render.d.ts.map +1 -1
  80. package/dist/lib/fleet-render.js +10 -3
  81. package/dist/lib/fleet-render.js.map +1 -1
  82. package/dist/lib/gh-remote.d.ts +15 -1
  83. package/dist/lib/gh-remote.d.ts.map +1 -1
  84. package/dist/lib/gh-remote.js +27 -2
  85. package/dist/lib/gh-remote.js.map +1 -1
  86. package/dist/lib/gh-token-run.d.ts +140 -14
  87. package/dist/lib/gh-token-run.d.ts.map +1 -1
  88. package/dist/lib/gh-token-run.js +187 -15
  89. package/dist/lib/gh-token-run.js.map +1 -1
  90. package/dist/lib/git-identity.d.ts +6 -2
  91. package/dist/lib/git-identity.d.ts.map +1 -1
  92. package/dist/lib/git-identity.js +17 -8
  93. package/dist/lib/git-identity.js.map +1 -1
  94. package/dist/lib/guarded-read.d.ts +15 -0
  95. package/dist/lib/guarded-read.d.ts.map +1 -0
  96. package/dist/lib/guarded-read.js +73 -0
  97. package/dist/lib/guarded-read.js.map +1 -0
  98. package/dist/lib/machine-setup.d.ts +165 -0
  99. package/dist/lib/machine-setup.d.ts.map +1 -0
  100. package/dist/lib/machine-setup.js +441 -0
  101. package/dist/lib/machine-setup.js.map +1 -0
  102. package/dist/lib/native-realpath.d.ts +70 -0
  103. package/dist/lib/native-realpath.d.ts.map +1 -0
  104. package/dist/lib/native-realpath.js +95 -0
  105. package/dist/lib/native-realpath.js.map +1 -0
  106. package/dist/lib/project-config.d.ts +2 -6
  107. package/dist/lib/project-config.d.ts.map +1 -1
  108. package/dist/lib/project-config.js.map +1 -1
  109. package/dist/lib/project-name.d.ts +15 -0
  110. package/dist/lib/project-name.d.ts.map +1 -0
  111. package/dist/lib/project-name.js +22 -0
  112. package/dist/lib/project-name.js.map +1 -0
  113. package/dist/lib/push-to.d.ts +113 -0
  114. package/dist/lib/push-to.d.ts.map +1 -0
  115. package/dist/lib/push-to.js +240 -0
  116. package/dist/lib/push-to.js.map +1 -0
  117. package/dist/lib/runtime/claude-gateway-routing.d.ts +161 -0
  118. package/dist/lib/runtime/claude-gateway-routing.d.ts.map +1 -0
  119. package/dist/lib/runtime/claude-gateway-routing.js +466 -0
  120. package/dist/lib/runtime/claude-gateway-routing.js.map +1 -0
  121. package/dist/lib/runtime/codex-adapter.d.ts +91 -5
  122. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  123. package/dist/lib/runtime/codex-adapter.js +204 -44
  124. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  125. package/dist/lib/runtime/codex-config.d.ts +6 -12
  126. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  127. package/dist/lib/runtime/codex-config.js +17 -24
  128. package/dist/lib/runtime/codex-config.js.map +1 -1
  129. package/dist/lib/runtime/codex-guard-proof.d.ts +4 -7
  130. package/dist/lib/runtime/codex-guard-proof.d.ts.map +1 -1
  131. package/dist/lib/runtime/codex-guard-proof.js +16 -14
  132. package/dist/lib/runtime/codex-guard-proof.js.map +1 -1
  133. package/dist/lib/runtime/codex-hooks-list.d.ts +20 -0
  134. package/dist/lib/runtime/codex-hooks-list.d.ts.map +1 -1
  135. package/dist/lib/runtime/codex-hooks-list.js +20 -8
  136. package/dist/lib/runtime/codex-hooks-list.js.map +1 -1
  137. package/dist/lib/runtime/types.d.ts +1 -1
  138. package/dist/lib/runtime/types.d.ts.map +1 -1
  139. package/dist/lib/standards.d.ts +3 -0
  140. package/dist/lib/standards.d.ts.map +1 -1
  141. package/dist/lib/standards.js +1 -0
  142. package/dist/lib/standards.js.map +1 -1
  143. package/dist/lib/team-identity.d.ts.map +1 -1
  144. package/dist/lib/team-identity.js +18 -53
  145. package/dist/lib/team-identity.js.map +1 -1
  146. package/dist/lib/team-restore.d.ts +281 -0
  147. package/dist/lib/team-restore.d.ts.map +1 -0
  148. package/dist/lib/team-restore.js +533 -0
  149. package/dist/lib/team-restore.js.map +1 -0
  150. package/dist/lib/window-view.d.ts +5 -0
  151. package/dist/lib/window-view.d.ts.map +1 -1
  152. package/dist/lib/window-view.js +67 -6
  153. package/dist/lib/window-view.js.map +1 -1
  154. package/dist/lib/worktree-sync.d.ts +139 -11
  155. package/dist/lib/worktree-sync.d.ts.map +1 -1
  156. package/dist/lib/worktree-sync.js +327 -46
  157. package/dist/lib/worktree-sync.js.map +1 -1
  158. package/dist/standards/merge-gates.md +26 -0
  159. package/package.json +2 -2
@@ -4,12 +4,15 @@
4
4
  * Creates a new agent team worktree, initialises team memories, and
5
5
  * creates a catalog entry.
6
6
  */
7
- import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, statSync, unlinkSync, writeSync, } from 'fs';
7
+ import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, unlinkSync, writeSync, } from 'fs';
8
8
  import { join, basename, dirname, relative, isAbsolute, sep } from 'path';
9
9
  import chalk from 'chalk';
10
10
  import { findProjectRoot, findTeamWorktree, assignSlot, getCurrentBranch, fetchOrigin, createGitWorktree, addToGitSafeDirectory, createHuskySymlink, generateBranchName, generateWorktreeDirName, listRemotes, } from '../lib/worktree.js';
11
11
  import { syncClaudeConfig, deployClaudeMd, writeClaudeLocal, readBehavioralPointer, logSuccess, logWarning, logDim } from '../lib/claude.js';
12
- import { writeTeamCatalog, writeNewProjectTeamBuilderCatalog, slugToDisplayName, getTeamCatalogPath, catalogEntryOnOriginMain, catalogEntryOnRef, roleguideOnOriginMain, isReadableRepoPath, listTeams, getTeam, serializeTeamEntry, serializeNewProjectTeamBuilderEntry } from '../lib/catalog.js';
12
+ import { writeTeamCatalog, writeNewProjectTeamBuilderCatalog, slugToDisplayName, getTeamCatalogPath, catalogEntryOnOriginMain, catalogEntryOnRef, roleguideOnOriginMain, isReadableRepoPath, listTeams, getTeam, getTeamWithStatus, serializeTeamEntry, serializeNewProjectTeamBuilderEntry, MAX_TEAM_FILE_BYTES } from '../lib/catalog.js';
13
+ import { readRegularFileGuarded } from '../lib/guarded-read.js';
14
+ import { sanitizeField } from '../lib/coordination-render.js';
15
+ import { stripAnsi, redactUrlCredentials } from '../lib/startup-report.js';
13
16
  import { rosterEntryOnRef, rosterSourceHasSlug, rosterRefFor } from '../lib/roster.js';
14
17
  import { commitCatalogEntry } from '../lib/catalog-commit.js';
15
18
  // The build boundary (#123). Its own module for the reason `lib/roster.ts` and
@@ -34,7 +37,7 @@ export const SELF_SERVICE_REFUSED_DETAIL = 'the coordination service refused thi
34
37
  'only the project\'s owner creates teams, and any other identity needs an operator grant on an existing team. ' +
35
38
  'Run this from the owner\'s MemNexus login (mx auth login), or ask an operator to add the team with ' +
36
39
  'POST /admin/provision and grant you with POST /admin/grant';
37
- import { isMxAvailable, bootstrapTeamMemories, logMemoryResult, teamMemorySpecs, logManualMemoryCommands, namedMemoryExists, namedMemoryResolvesById, readNamedMemoryJson, shellSingleQuote, PROVISIONED_MEMORY_SERVICE, EXTRA_ANCHOR_SUFFIX_RE } from '../lib/memory.js';
40
+ import { isMxAvailable, bootstrapTeamMemories, logMemoryResult, teamMemorySpecs, logManualMemoryCommands, namedMemoryExists, namedMemoryResolvesById, readNamedMemoryJson, shellSingleQuote, redactSecrets, PROVISIONED_MEMORY_SERVICE, EXTRA_ANCHOR_SUFFIX_RE } from '../lib/memory.js';
38
41
  // The reader `mx-agent window` uses, imported rather than reimplemented: rows 3
39
42
  // to 5 assert that the fleet view can read the seed, and a local copy of the
40
43
  // parser's rules could pass while the parser itself returns `unknown` (#6).
@@ -1014,20 +1017,20 @@ function placeholderRow(i) {
1014
1017
  required: true,
1015
1018
  };
1016
1019
  }
1017
- let text;
1018
- try {
1019
- text = readFileSync(i.roleguideInWorktree, 'utf-8');
1020
- }
1021
- catch (err) {
1022
- const code = err?.code ?? 'unknown error';
1020
+ // The guarded read (#909): a bare `readFileSync` blocks forever on a FIFO at
1021
+ // this path. A refused file is this row's could-not-run, as a failed read was.
1022
+ const read = readRegularFileGuarded(i.roleguideInWorktree, MAX_ROLEGUIDE_BYTES);
1023
+ if (read.kind !== 'ok') {
1023
1024
  return {
1024
1025
  n: 13,
1025
1026
  label,
1026
1027
  asserted: false,
1027
- detail: `could not run: ${i.roleguideInWorktree} could not be read (${code})`,
1028
+ detail: `could not run: ${i.roleguideInWorktree} could not be read `
1029
+ + `(${read.kind === 'absent' ? 'ENOENT' : read.reason})`,
1028
1030
  required: true,
1029
1031
  };
1030
1032
  }
1033
+ const text = read.bytes.toString('utf-8');
1031
1034
  // Before the placeholder count, so a draft that also has unfilled tokens
1032
1035
  // reports the marker: removing the DRAFT line is the first thing to do, and a
1033
1036
  // row prints one detail. The exemption above returns first, so the bundled
@@ -1562,30 +1565,22 @@ function anchorStage(i) {
1562
1565
  if (i.roleguideInWorktree === null) {
1563
1566
  return { kind: 'could-not-run', detail: 'no roleguide was copied into the worktree (row 1)' };
1564
1567
  }
1565
- let text;
1566
- try {
1567
- // SIZE FIRST. `MAX_ROLEGUIDE_BYTES` is 1 MiB and the contract read enforces
1568
- // it upstream (`lib/behavioral-injection.ts:153`), so the worktree copy
1569
- // inherits the bound; this asks again at the one place that reads the copy
1570
- // directly, and asks before the read rather than after (security pre-ruling
1571
- // I4).
1572
- const size = statSync(i.roleguideInWorktree).size;
1573
- if (size > MAX_ROLEGUIDE_BYTES) {
1574
- return {
1575
- kind: 'could-not-run',
1576
- detail: `${i.roleguideInWorktree} is ${size} bytes, over the ${MAX_ROLEGUIDE_BYTES}-byte `
1577
- + 'roleguide bound',
1578
- };
1579
- }
1580
- text = readFileSync(i.roleguideInWorktree, 'utf-8');
1581
- }
1582
- catch (err) {
1583
- const code = err?.code ?? 'unknown error';
1568
+ // SIZE FIRST. `MAX_ROLEGUIDE_BYTES` is 1 MiB and the contract read enforces
1569
+ // it upstream (`lib/behavioral-injection.ts:153`), so the worktree copy
1570
+ // inherits the bound; this asks again at the one place that reads the copy
1571
+ // directly, and asks before the read rather than after (security pre-ruling
1572
+ // I4). The guarded read (#909) checks the size on the descriptor it reads,
1573
+ // where the earlier `statSync` followed a link and checked a different file
1574
+ // from the one read, and it does not block on a FIFO as `readFileSync` did.
1575
+ const read = readRegularFileGuarded(i.roleguideInWorktree, MAX_ROLEGUIDE_BYTES);
1576
+ if (read.kind !== 'ok') {
1584
1577
  return {
1585
1578
  kind: 'could-not-run',
1586
- detail: `${i.roleguideInWorktree} could not be read (${code})`,
1579
+ detail: `${i.roleguideInWorktree} could not be read `
1580
+ + `(${read.kind === 'absent' ? 'ENOENT' : read.reason})`,
1587
1581
  };
1588
1582
  }
1583
+ const text = read.bytes.toString('utf-8');
1589
1584
  const parsed = parseAnchorTable(text);
1590
1585
  if (!parsed.ok)
1591
1586
  return { kind: 'refused', detail: parsed.detail };
@@ -2905,13 +2900,15 @@ function checkCompletionRows(i) {
2905
2900
  * Making it required changes whether `provision` exits non-zero, which is a
2906
2901
  * separate decision with its own reach. When this row was written,
2907
2902
  * `extensions.worktreeConfig` was off on `/workspace/.git`, so a required row
2908
- * would have refused EVERY provision until a change this command must not make
2909
- * had been made by hand. It is on there now (`git -C /workspace config --get
2910
- * extensions.worktreeConfig` read `true` on 2026-11-01), and `mx-agent new
2911
- * project` enables it on the repository it creates (#448, plan #857). A
2912
- * repository adopted by `mx-agent init` or created before that can still have it
2913
- * off, so the row stays `required: false`; making it required for new-project
2914
- * runs is a separate follow-up.
2903
+ * would have refused EVERY provision until the extension had been enabled by
2904
+ * hand. `provision` itself never enables it. It is on there now (`git -C
2905
+ * /workspace config --get extensions.worktreeConfig` read `true` on
2906
+ * 2026-11-01). `mx-agent new project` enables it on the repository it creates
2907
+ * (#448, plan #857), and `mx-agent start` enables it on a clone with no other
2908
+ * worktrees (#1155 slice 2, `lib/machine-setup.ts`). A repository adopted by
2909
+ * `mx-agent init`, or a clone that already had other worktrees, can still have
2910
+ * it off, so the row stays `required: false`; making it required for
2911
+ * new-project runs is a separate follow-up.
2915
2912
  */
2916
2913
  function gitIdentityRow(worktreePath, slug) {
2917
2914
  const expectedEmail = teamGitEmail(slug);
@@ -3053,6 +3050,70 @@ function buildRow(build, slug) {
3053
3050
  required: true,
3054
3051
  };
3055
3052
  }
3053
+ function completionRowState(row) {
3054
+ if (row.asserted)
3055
+ return row.stale === true ? 'asserted-stale' : 'asserted';
3056
+ if (row.notApplicable === true)
3057
+ return 'not-applicable';
3058
+ if (row.couldNotRun === true)
3059
+ return 'could-not-run';
3060
+ if (row.partlyAsserted === true)
3061
+ return 'partly-asserted';
3062
+ return 'not-asserted';
3063
+ }
3064
+ /**
3065
+ * The rows a creation or a re-check asserts and that did not hold. A non-empty
3066
+ * list is what makes `runRecheck` throw `CompletionCheckError`, and what makes
3067
+ * the JSON `result` read `fail`: one expression, so the two agree.
3068
+ */
3069
+ function failedCompletionRows(rows) {
3070
+ return rows.filter((r) => r.required && !r.asserted);
3071
+ }
3072
+ /**
3073
+ * The document, as a value. Called from the re-check site only today; built as a
3074
+ * function that returns rather than prints so #1089 can reuse it.
3075
+ *
3076
+ * With `error` the run produced no rows: `result` is `could-not-run` and `rows`
3077
+ * is empty whatever was passed.
3078
+ *
3079
+ * THE MESSAGE IS REDACTED FOR EVERY CODE (security review of #1093, Should Fix,
3080
+ * CWE-532). The four named codes build their message from a slug, a path or an
3081
+ * identity verdict, but `internal` is any exception nobody enumerated, and its
3082
+ * text can hold a credentialed URL or a token. A desktop consumer may log or
3083
+ * store stdout, so the message is stripped of control sequences, then URL
3084
+ * userinfo, then the token shapes `redactSecrets` knows. Redaction is
3085
+ * pattern-based: a secret in a shape neither helper knows is not caught.
3086
+ */
3087
+ function completionRowsDocument(i) {
3088
+ const environment = { platform: i.platform ?? process.platform };
3089
+ if (i.error) {
3090
+ return {
3091
+ schema_version: 1,
3092
+ team: i.team,
3093
+ result: 'could-not-run',
3094
+ environment,
3095
+ error: { code: i.error.code, message: redactErrorText(stripAnsi(i.error.message)) },
3096
+ rows: [],
3097
+ };
3098
+ }
3099
+ return {
3100
+ schema_version: 1,
3101
+ team: i.team,
3102
+ result: failedCompletionRows(i.rows).length > 0 ? 'fail' : 'pass',
3103
+ environment,
3104
+ error: null,
3105
+ rows: i.rows.map((row, index) => ({
3106
+ index,
3107
+ id: completionRowNumber(row),
3108
+ n: row.n,
3109
+ label: row.label,
3110
+ state: completionRowState(row),
3111
+ required: row.required,
3112
+ detail: row.detail,
3113
+ shape_only: row.asserted && row.shapeAsserted === true,
3114
+ })),
3115
+ };
3116
+ }
3056
3117
  /**
3057
3118
  * One line per row, each `row N: asserted` or `row N: not asserted`.
3058
3119
  *
@@ -3089,31 +3150,24 @@ function printCompletionRows(rows) {
3089
3150
  console.log(chalk.bold(` ${row.sectionHeading}:`));
3090
3151
  // Padded to one width so the verdict column stays a column: `asserted (shape)`
3091
3152
  // is the longest of the three, and rows 3 to 5 are the only ones that print it.
3092
- // A not-asserted row with `partlyAsserted` had one of its parts checked (row
3093
- // 9, #77), and the verdict column says so. It still counts as not asserted.
3094
- const partlyAsserted = !row.asserted && row.partlyAsserted === true;
3095
- // Could-not-run is its own word, before `partly asserted`: a row that could
3096
- // not look has not had a part hold, so the two are not the same state and the
3097
- // yellow they share does not make them one (#290 Should Fix 4).
3098
- const couldNotRun = !row.asserted && row.couldNotRun === true;
3099
- // Not applicable is its own word too (#613 item 2): a row whose claim this
3100
- // project cannot make is not a step the command handed the operator.
3101
- const notApplicable = !row.asserted && row.notApplicable === true;
3102
- const verdict = row.asserted
3103
- ? row.stale === true
3104
- // Asserted, and not this run's content. Yellow, because the reader has
3105
- // something to look at even though nothing failed.
3106
- ? chalk.yellow('asserted, stale ')
3107
- : chalk.green(row.shapeAsserted ? 'asserted (shape)' : 'asserted ')
3108
- : notApplicable
3109
- ? chalk.dim('not applicable ')
3110
- : couldNotRun
3111
- ? chalk.yellow('could not run ')
3112
- : partlyAsserted
3113
- ? chalk.yellow('partly asserted ')
3114
- : row.required
3115
- ? chalk.red('not asserted ')
3116
- : chalk.yellow('not asserted ');
3153
+ // The state comes from `completionRowState`, the one function the JSON output
3154
+ // reads too (#1088 part 1b), so the table and the JSON cannot disagree.
3155
+ const state = completionRowState(row);
3156
+ const verdict = state === 'asserted-stale'
3157
+ // Asserted, and not this run's content. Yellow, because the reader has
3158
+ // something to look at even though nothing failed.
3159
+ ? chalk.yellow('asserted, stale ')
3160
+ : state === 'asserted'
3161
+ ? chalk.green(row.shapeAsserted ? 'asserted (shape)' : 'asserted ')
3162
+ : state === 'not-applicable'
3163
+ ? chalk.dim('not applicable ')
3164
+ : state === 'could-not-run'
3165
+ ? chalk.yellow('could not run ')
3166
+ : state === 'partly-asserted'
3167
+ ? chalk.yellow('partly asserted ')
3168
+ : row.required
3169
+ ? chalk.red('not asserted ')
3170
+ : chalk.yellow('not asserted ');
3117
3171
  const detail = row.detail;
3118
3172
  // Printed for asserted rows too: when a row is green on the probe rather than
3119
3173
  // on the id read, the reader is told which evidence held.
@@ -3796,16 +3850,25 @@ function catalogEntryExpectedForms(entry) {
3796
3850
  * builds it. Nothing is stripped before comparing (#828 M5).
3797
3851
  */
3798
3852
  function catalogEntryState(i) {
3799
- let onDisk;
3800
3853
  try {
3801
3854
  if (!lstatSync(i.path).isFile()) {
3802
3855
  return { kind: 'absent', detail: `catalog entry is not a regular file: ${i.path}` };
3803
3856
  }
3804
- onDisk = readFileSync(i.path, 'utf-8');
3805
3857
  }
3806
3858
  catch {
3807
3859
  return { kind: 'absent', detail: `catalog entry missing: ${i.path}` };
3808
3860
  }
3861
+ // The guarded read (#910 SF-2). The `lstat` above already refuses a FIFO; this
3862
+ // closes the window between it and the read, where a swap to a FIFO would
3863
+ // block a bare `readFileSync` forever. A file refused here is `absent`, as a
3864
+ // non-regular file is above.
3865
+ const read = readRegularFileGuarded(i.path, MAX_TEAM_FILE_BYTES);
3866
+ if (read.kind === 'absent')
3867
+ return { kind: 'absent', detail: `catalog entry missing: ${i.path}` };
3868
+ if (read.kind === 'refused') {
3869
+ return { kind: 'absent', detail: `catalog entry was not read (${read.reason}): ${i.path}` };
3870
+ }
3871
+ const onDisk = read.bytes.toString('utf-8');
3809
3872
  if (i.expected.includes(onDisk)) {
3810
3873
  return { kind: 'present', detail: `catalog entry in the scaffolded project (no origin yet): ${i.path}` };
3811
3874
  }
@@ -3814,20 +3877,127 @@ function catalogEntryState(i) {
3814
3877
  detail: `present, stale: ${i.path} differs from what this run would write; not overwritten`,
3815
3878
  };
3816
3879
  }
3880
+ /** A refusal that, in `--recheck --json` mode, is reported as a could-not-run document (#1088 amendment 2, F2). */
3881
+ class RecheckJsonRefusal extends Error {
3882
+ code;
3883
+ constructor(code, message) {
3884
+ super(message);
3885
+ this.code = code;
3886
+ this.name = 'RecheckJsonRefusal';
3887
+ }
3888
+ }
3889
+ /** The no-worktree refusal of `--recheck`. Still a `CompletionCheckError`, so every non-JSON caller reads it as before. */
3890
+ class RecheckNoWorktreeError extends CompletionCheckError {
3891
+ }
3817
3892
  export async function runCreate(options) {
3893
+ if (options.json === true) {
3894
+ if (options.recheck !== true) {
3895
+ // Before every read and every write. Provision without `--recheck` writes
3896
+ // state, and its output is not a stable contract yet (#1088 part 1b).
3897
+ console.error(chalk.red('Error: --json is accepted only with --recheck.'));
3898
+ console.error(chalk.dim(' provision without --recheck writes state, and its output is not a stable contract yet.'));
3899
+ console.error(chalk.dim(' Nothing was written.'));
3900
+ process.exit(1);
3901
+ }
3902
+ await runRecheckJson(options);
3903
+ return;
3904
+ }
3905
+ await provisionOrRecheck(options, null);
3906
+ }
3907
+ /**
3908
+ * `mx-agent provision --recheck --json` (#1088 part 1b, amendments 1 and 2).
3909
+ *
3910
+ * STDOUT HOLDS ONE DOCUMENT, written by ONE `process.stdout.write` at the end.
3911
+ * For the whole run `console.log` and `console.info` are pointed at
3912
+ * `console.error`, so every human line goes to stderr: the TEST TEAM banner, the
3913
+ * config-generation line (`checkConfigGeneration` logs through `console.log`
3914
+ * when given no logger), the re-check banners, `logDim` (which prints through
3915
+ * `console.log`), and any line a helper adds later. Both are restored before
3916
+ * the document is written.
3917
+ *
3918
+ * EVERY EXIT WRITES A DOCUMENT. With rows: `pass` or `fail`. Without rows,
3919
+ * because a refusal or a throw came first: `could-not-run`, `rows: []`, and
3920
+ * `error` naming why. The message the non-JSON run would print still goes to
3921
+ * stderr, redacted as the document's message is.
3922
+ *
3923
+ * EXIT CODES: 0 pass, 1 fail, 2 could-not-run, set through `process.exitCode`
3924
+ * rather than `process.exit`, so the write is not cut short on a platform where
3925
+ * stdout to a pipe is asynchronous. The caller in `index.ts` then sees no throw.
3926
+ */
3927
+ /** URL userinfo, then the token shapes `redactSecrets` knows (security review of #1093). */
3928
+ export function redactErrorText(text) {
3929
+ return redactSecrets(redactUrlCredentials(text));
3930
+ }
3931
+ async function runRecheckJson(options) {
3932
+ const team = options.name ?? (options.roleguide ? inferSlugFromRoleguide(options.roleguide) : '');
3933
+ const sink = { document: null };
3934
+ const savedLog = console.log;
3935
+ const savedInfo = console.info;
3936
+ // Looked up at call time, so a test's spy on `console.error` sees these lines.
3937
+ console.log = (...a) => console.error(...a);
3938
+ console.info = (...a) => console.error(...a);
3939
+ let failure = null;
3940
+ try {
3941
+ await provisionOrRecheck(options, sink);
3942
+ }
3943
+ catch (err) {
3944
+ failure = err;
3945
+ }
3946
+ finally {
3947
+ console.log = savedLog;
3948
+ console.info = savedInfo;
3949
+ }
3950
+ const message = failure === null ? '' : failure instanceof Error ? failure.message : String(failure);
3951
+ const doc = sink.document ?? completionRowsDocument({
3952
+ team,
3953
+ rows: [],
3954
+ error: {
3955
+ code: failure instanceof RecheckJsonRefusal
3956
+ ? failure.code
3957
+ : failure instanceof RecheckNoWorktreeError
3958
+ ? 'no-worktree'
3959
+ : failure instanceof ResumeIdentityError
3960
+ ? 'identity-mismatch'
3961
+ : 'internal',
3962
+ message: failure === null ? 'the re-check returned without producing rows' : message,
3963
+ },
3964
+ });
3965
+ process.stdout.write(JSON.stringify(doc, null, 2) + '\n');
3966
+ // Redacted on stderr too in JSON mode: the desktop app reads both streams.
3967
+ if (failure !== null)
3968
+ console.error(redactErrorText(message));
3969
+ process.exitCode = doc.result === 'pass' ? 0 : doc.result === 'fail' ? 1 : 2;
3970
+ }
3971
+ /**
3972
+ * The body of `mx-agent provision`. `json` is set only by `runRecheckJson`; with
3973
+ * it, the four refusals before the re-check branch throw a `RecheckJsonRefusal`
3974
+ * instead of calling `process.exit(1)`, and the re-check stores its document in
3975
+ * the sink instead of printing the table. With `json` null every line is what it
3976
+ * was before #1088.
3977
+ */
3978
+ async function provisionOrRecheck(options, json) {
3818
3979
  const roleguide = options.roleguide ?? '';
3980
+ // In JSON mode a refusal is a could-not-run document; otherwise the lines and
3981
+ // the exit are exactly the ones this function printed before #1088.
3982
+ const refuse = (code, lines) => {
3983
+ if (json !== null)
3984
+ throw new RecheckJsonRefusal(code, lines.join('\n'));
3985
+ for (const line of lines)
3986
+ console.error(line);
3987
+ process.exit(1);
3988
+ };
3819
3989
  // Resolve team slug
3820
3990
  const slug = options.name ?? (roleguide ? inferSlugFromRoleguide(roleguide) : '');
3821
3991
  if (!slug) {
3822
- console.error(chalk.red('Error: Could not determine team slug. Use --name to specify it explicitly.'));
3823
- process.exit(1);
3992
+ refuse('invalid-slug', [chalk.red('Error: Could not determine team slug. Use --name to specify it explicitly.')]);
3824
3993
  }
3825
3994
  // Defense-in-depth: validate slug before use in any shell command or file path
3826
3995
  const SLUG_RE = /^[a-z][a-z0-9-]{0,48}[a-z0-9]$/;
3827
3996
  if (!SLUG_RE.test(slug)) {
3828
- console.error(chalk.red(`Error: Invalid team slug "${slug}".`));
3829
- console.error(chalk.dim(' Slug must match ^[a-z][a-z0-9-]{0,48}[a-z0-9]$ (lowercase, digits, hyphens; 2–50 chars).'));
3830
- process.exit(1);
3997
+ refuse('invalid-slug', [
3998
+ chalk.red(`Error: Invalid team slug "${slug}".`),
3999
+ chalk.dim(' Slug must match ^[a-z][a-z0-9-]{0,48}[a-z0-9]$ (lowercase, digits, hyphens; 2–50 chars).'),
4000
+ ]);
3831
4001
  }
3832
4002
  const displayName = slugToDisplayName(slug);
3833
4003
  let projectRoot;
@@ -3839,8 +4009,8 @@ export async function runCreate(options) {
3839
4009
  projectRoot = findProjectRoot();
3840
4010
  }
3841
4011
  catch (err) {
3842
- console.error(chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
3843
- process.exit(1);
4012
+ // `return`, so the compiler sees that `projectRoot` is assigned past here.
4013
+ return refuse('no-project-root', [chalk.red(`Error: ${err instanceof Error ? err.message : String(err)}`)]);
3844
4014
  }
3845
4015
  }
3846
4016
  const configured = resolveProjectConfig(loadProjectConfig(projectRoot));
@@ -3874,9 +4044,12 @@ export async function runCreate(options) {
3874
4044
  // prefix", and every project without an `mx-agent.config.json` has one, so
3875
4045
  // validating it would refuse provisioning everywhere.
3876
4046
  if (cfg.projectSlug !== '' && !isValidProjectSlug(cfg.projectSlug)) {
3877
- console.error(chalk.red(`Error: mx-agent.config.json: ${invalidProjectSlugMessage(cfg.projectSlug)}`));
3878
- console.error(chalk.dim(' Nothing was created. Fix "projectSlug" in mx-agent.config.json and re-run.'));
3879
- process.exit(1);
4047
+ // `invalid-slug` in JSON mode: amendment 2 lists this refusal under F2 and
4048
+ // names no code of its own for it. The message says it is the project slug.
4049
+ refuse('invalid-slug', [
4050
+ chalk.red(`Error: mx-agent.config.json: ${invalidProjectSlugMessage(cfg.projectSlug)}`),
4051
+ chalk.dim(' Nothing was created. Fix "projectSlug" in mx-agent.config.json and re-run.'),
4052
+ ]);
3880
4053
  }
3881
4054
  // Non-blocking agent-config generation drift check (#4017). At most one line.
3882
4055
  checkConfigGeneration(projectRoot, cfg.configSource, cfg.baseBranch);
@@ -3886,7 +4059,7 @@ export async function runCreate(options) {
3886
4059
  // every other write this command makes. A re-check that generated a roleguide
3887
4060
  // would not be a re-check.
3888
4061
  if (options.recheck === true) {
3889
- await runRecheck({ slug, displayName, projectRoot, cfg, roleguide: roleguide || null });
4062
+ await runRecheck({ slug, displayName, projectRoot, cfg, roleguide: roleguide || null, json });
3890
4063
  return;
3891
4064
  }
3892
4065
  if (!roleguide) {
@@ -3895,6 +4068,18 @@ export async function runCreate(options) {
3895
4068
  console.error(chalk.dim(` mx-agent provision --recheck --name ${slug}`));
3896
4069
  process.exit(1);
3897
4070
  }
4071
+ // A catalog entry that is there and was refused (#902): a FIFO, a symlink, a
4072
+ // directory or an oversize file at `<slug>.md`. Read as absent, provisioning
4073
+ // would treat the slug as free, and step 8's `writeTeamCatalog` would then
4074
+ // block on the FIFO or write through the symlink. Before every write, so a
4075
+ // refusal leaves nothing behind.
4076
+ const ownEntry = getTeamWithStatus(projectRoot, slug, cfg.teamsDir);
4077
+ if (ownEntry.kind === 'refused') {
4078
+ const entryPath = getTeamCatalogPath(projectRoot, slug, cfg.teamsDir);
4079
+ console.error(chalk.red(`Error: the catalog entry ${sanitizeField(entryPath)} is there and was not read: ${sanitizeField(ownEntry.reason)}.`));
4080
+ console.error(chalk.dim(' Nothing was created. Replace it with a regular file, or remove it, and re-run.'));
4081
+ process.exit(1);
4082
+ }
3898
4083
  // Before every write, and after the `--recheck` return above, which writes nothing
3899
4084
  // and contacts no service (#76). A resume is checked too: rows 3, 4, 5 and 10 need
3900
4085
  // the key there as well (#818).
@@ -4340,7 +4525,7 @@ async function runRecheck(i) {
4340
4525
  console.log();
4341
4526
  const worktreePath = findTeamWorktree(projectRoot, slug, cfg.worktreeDir);
4342
4527
  if (worktreePath === null) {
4343
- throw new CompletionCheckError([
4528
+ throw new RecheckNoWorktreeError([
4344
4529
  '',
4345
4530
  chalk.red.bold(`Re-check COULD NOT RUN — no worktree for ${slug} under ${cfg.worktreeDir}.`),
4346
4531
  '',
@@ -4515,8 +4700,13 @@ async function runRecheck(i) {
4515
4700
  // 2), so row 12 is not probed here and is not required.
4516
4701
  row12: { mode: 'recheck' },
4517
4702
  });
4518
- printCompletionRows(rows);
4519
- const failedRows = rows.filter((r) => r.required && !r.asserted);
4703
+ // The one site that prints the document (#1088 part 1b). The provision site and
4704
+ // the failure path still call `printCompletionRows` alone.
4705
+ if (i.json !== null)
4706
+ i.json.document = completionRowsDocument({ team: slug, rows });
4707
+ else
4708
+ printCompletionRows(rows);
4709
+ const failedRows = failedCompletionRows(rows);
4520
4710
  const requiredCount = rows.filter((r) => r.required).length;
4521
4711
  if (failedRows.length > 0) {
4522
4712
  const held = rows.filter((r) => r.asserted).map(completionRowNumber).join(', ');
@@ -4680,10 +4870,20 @@ function catalogEntryStep(i) {
4680
4870
  logWarning(`Could not copy the catalog entry into the new worktree: ${anchoredCatalog.detail}`);
4681
4871
  }
4682
4872
  else if (!existsSync(anchoredCatalog.dest)) {
4683
- const bytes = readFileSync(catalogInSource, 'utf-8');
4684
- const written = writeContained(anchoredCatalog.dest, realpathSync(worktreePath), bytes);
4685
- if (!written.ok) {
4686
- logWarning(`Could not copy the catalog entry into the new worktree: ${written.detail}`);
4873
+ // The guarded read (#909): `existsSync` is true for a FIFO, and a bare
4874
+ // `readFileSync` on one blocks forever. A refused entry is not copied;
4875
+ // creation goes on, as it does when the copy's write fails.
4876
+ const read = readRegularFileGuarded(catalogInSource, MAX_TEAM_FILE_BYTES);
4877
+ if (read.kind !== 'ok') {
4878
+ logWarning('Could not copy the catalog entry into the new worktree: '
4879
+ + `${sanitizeForMessage(catalogInSource)} was not read `
4880
+ + `(${read.kind === 'absent' ? 'it is not there' : read.reason})`);
4881
+ }
4882
+ else {
4883
+ const written = writeContained(anchoredCatalog.dest, realpathSync(worktreePath), read.bytes.toString('utf-8'));
4884
+ if (!written.ok) {
4885
+ logWarning(`Could not copy the catalog entry into the new worktree: ${written.detail}`);
4886
+ }
4687
4887
  }
4688
4888
  }
4689
4889
  }
@@ -4965,14 +5165,16 @@ async function runProvisionSteps(ctx) {
4965
5165
  // behavioral block. A missing identity degrades attribution; it does not
4966
5166
  // endanger the worktree, the memories or the catalog entry, and refusing here
4967
5167
  // would abort a creation that has already made all three. It refuses on any
4968
- // repository where `extensions.worktreeConfig` is off, because enabling it is
4969
- // a shared-repository change that is not a provisioning run's to make. When
4970
- // this was written that was every provision against `/workspace/.git`; the
4971
- // extension is on there now, and `mx-agent new project` enables it on the
4972
- // repository it creates (#448, plan #857). A repository adopted by
4973
- // `mx-agent init` can still have it off. Row 15 reports the result either
4974
- // way, so a degraded creation is visible in the table rather than only in a
4975
- // scrollback.
5168
+ // repository where `extensions.worktreeConfig` is off, because `provision`
5169
+ // never enables it: the one writer is `setWorktreeConfigExtension`
5170
+ // (`lib/machine-setup.ts`), which `mx-agent new project` calls on the
5171
+ // repository it creates (#448, plan #857) and `mx-agent start` calls on a
5172
+ // clone with no other worktrees (#1155 slice 2). When this was written that
5173
+ // refusal was every provision against `/workspace/.git`; the extension is on
5174
+ // there now. A repository adopted by `mx-agent init`, or a clone that already
5175
+ // had other worktrees, can still have it off. Row 15 reports the result
5176
+ // either way, so a degraded creation is visible in the table rather than only
5177
+ // in a scrollback.
4976
5178
  const gitIdentity = writeTeamGitIdentity({ worktreePath, slug });
4977
5179
  if (gitIdentity.kind === 'written') {
4978
5180
  logSuccess(`Git identity for this worktree: ${gitIdentity.name} <${gitIdentity.email}>`);
@@ -5815,7 +6017,7 @@ async function runProvisionSteps(ctx) {
5815
6017
  * filesystem (was a byte written outside the destination root?) rather than
5816
6018
  * inferred from a refusal message. Not part of the command API.
5817
6019
  */
5818
- export const __testing = { catalogEntryState, catalogEntryExpectedForms, catalogRemedyLines, reanchorContained, writeContained, allowedRoleguideRoots, checkRoleguideIdentity, checkCompletionRows, printCompletionRows, isPlaceholderRoleguide, assessSeedShape, generateRoleguide, remainingPlaceholders, placeholderRowDetail, SKELETON_PLACEHOLDERS, PROSE_METAVARIABLES, unrecognizedBracketTokens, DRAFT_MARKER_RE, DRAFT_MARKER_DETAIL,
6020
+ export const __testing = { placeholderRow, catalogEntryState, catalogEntryExpectedForms, catalogRemedyLines, reanchorContained, writeContained, allowedRoleguideRoots, checkRoleguideIdentity, checkCompletionRows, printCompletionRows, completionRowState, completionRowsDocument, failedCompletionRows, isPlaceholderRoleguide, assessSeedShape, generateRoleguide, remainingPlaceholders, placeholderRowDetail, SKELETON_PLACEHOLDERS, PROSE_METAVARIABLES, unrecognizedBracketTokens, DRAFT_MARKER_RE, DRAFT_MARKER_DETAIL,
5819
6021
  // #190. `MEMORY_KEY_RE` and `TEAM_MEMORY_SUFFIXES` are exported so a test can
5820
6022
  // pin that neither changed: the security pre-ruling's S1 leaves the regex at
5821
6023
  // `checkRoleguideIdentity` static, and S2's false-refusal direction depends on