@memnexus-ai/mx-agent-cli 0.1.294 → 0.1.296-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (649) hide show
  1. package/dist/__tests__/agents-md-canonicalization.test.js +31 -1
  2. package/dist/__tests__/agents-md-canonicalization.test.js.map +1 -1
  3. package/dist/__tests__/behavioral-extraction.test.js +50 -0
  4. package/dist/__tests__/behavioral-extraction.test.js.map +1 -1
  5. package/dist/__tests__/bootstrap-behavioral-contract.test.js +6 -3
  6. package/dist/__tests__/bootstrap-behavioral-contract.test.js.map +1 -1
  7. package/dist/__tests__/bundle-config.test.js +28 -2
  8. package/dist/__tests__/bundle-config.test.js.map +1 -1
  9. package/dist/__tests__/catalog-interaction.test.d.ts +25 -0
  10. package/dist/__tests__/catalog-interaction.test.d.ts.map +1 -0
  11. package/dist/__tests__/catalog-interaction.test.js +269 -0
  12. package/dist/__tests__/catalog-interaction.test.js.map +1 -0
  13. package/dist/__tests__/catalog-named-memories.test.d.ts +2 -0
  14. package/dist/__tests__/catalog-named-memories.test.d.ts.map +1 -0
  15. package/dist/__tests__/catalog-named-memories.test.js +204 -0
  16. package/dist/__tests__/catalog-named-memories.test.js.map +1 -0
  17. package/dist/__tests__/catalog-origin-main.test.d.ts +15 -0
  18. package/dist/__tests__/catalog-origin-main.test.d.ts.map +1 -0
  19. package/dist/__tests__/catalog-origin-main.test.js +296 -0
  20. package/dist/__tests__/catalog-origin-main.test.js.map +1 -0
  21. package/dist/__tests__/catalog.test.d.ts +2 -0
  22. package/dist/__tests__/catalog.test.d.ts.map +1 -0
  23. package/dist/__tests__/catalog.test.js +131 -0
  24. package/dist/__tests__/catalog.test.js.map +1 -0
  25. package/dist/__tests__/claude-local-sanitizer.test.d.ts +24 -0
  26. package/dist/__tests__/claude-local-sanitizer.test.d.ts.map +1 -0
  27. package/dist/__tests__/claude-local-sanitizer.test.js +906 -0
  28. package/dist/__tests__/claude-local-sanitizer.test.js.map +1 -0
  29. package/dist/__tests__/cli-build-integration.test.d.ts +2 -0
  30. package/dist/__tests__/cli-build-integration.test.d.ts.map +1 -0
  31. package/dist/__tests__/cli-build-integration.test.js +64 -0
  32. package/dist/__tests__/cli-build-integration.test.js.map +1 -0
  33. package/dist/__tests__/cli-build.test.d.ts +2 -0
  34. package/dist/__tests__/cli-build.test.d.ts.map +1 -0
  35. package/dist/__tests__/cli-build.test.js +640 -0
  36. package/dist/__tests__/cli-build.test.js.map +1 -0
  37. package/dist/__tests__/codex-deploy-config.test.js +60 -0
  38. package/dist/__tests__/codex-deploy-config.test.js.map +1 -1
  39. package/dist/__tests__/completion-rows-discriminate.test.d.ts +20 -0
  40. package/dist/__tests__/completion-rows-discriminate.test.d.ts.map +1 -0
  41. package/dist/__tests__/completion-rows-discriminate.test.js +481 -0
  42. package/dist/__tests__/completion-rows-discriminate.test.js.map +1 -0
  43. package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts +2 -0
  44. package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts.map +1 -0
  45. package/dist/__tests__/config-fidelity-archived-symlinks.test.js +127 -0
  46. package/dist/__tests__/config-fidelity-archived-symlinks.test.js.map +1 -0
  47. package/dist/__tests__/config-fidelity-display.test.d.ts +2 -0
  48. package/dist/__tests__/config-fidelity-display.test.d.ts.map +1 -0
  49. package/dist/__tests__/config-fidelity-display.test.js +77 -0
  50. package/dist/__tests__/config-fidelity-display.test.js.map +1 -0
  51. package/dist/__tests__/config-fidelity.test.js +166 -33
  52. package/dist/__tests__/config-fidelity.test.js.map +1 -1
  53. package/dist/__tests__/config-generation-gate.test.js +78 -0
  54. package/dist/__tests__/config-generation-gate.test.js.map +1 -1
  55. package/dist/__tests__/config-sync.test.js +89 -1
  56. package/dist/__tests__/config-sync.test.js.map +1 -1
  57. package/dist/__tests__/coordination-401-production-wiring.test.js +12 -7
  58. package/dist/__tests__/coordination-401-production-wiring.test.js.map +1 -1
  59. package/dist/__tests__/coordination-401-recovery.test.js +39 -32
  60. package/dist/__tests__/coordination-401-recovery.test.js.map +1 -1
  61. package/dist/__tests__/coordination-brief-pin.test.js +21 -8
  62. package/dist/__tests__/coordination-brief-pin.test.js.map +1 -1
  63. package/dist/__tests__/coordination-client.test.js +316 -3
  64. package/dist/__tests__/coordination-client.test.js.map +1 -1
  65. package/dist/__tests__/coordination-credential-endpoint.test.d.ts +24 -0
  66. package/dist/__tests__/coordination-credential-endpoint.test.d.ts.map +1 -0
  67. package/dist/__tests__/coordination-credential-endpoint.test.js +1290 -0
  68. package/dist/__tests__/coordination-credential-endpoint.test.js.map +1 -0
  69. package/dist/__tests__/coordination-memory.test.js +20 -4
  70. package/dist/__tests__/coordination-memory.test.js.map +1 -1
  71. package/dist/__tests__/coordination-provision.test.js +22 -14
  72. package/dist/__tests__/coordination-provision.test.js.map +1 -1
  73. package/dist/__tests__/coordination-status-registration.test.d.ts +16 -0
  74. package/dist/__tests__/coordination-status-registration.test.d.ts.map +1 -0
  75. package/dist/__tests__/coordination-status-registration.test.js +480 -0
  76. package/dist/__tests__/coordination-status-registration.test.js.map +1 -0
  77. package/dist/__tests__/coordination-token-multitenant.test.js +24 -24
  78. package/dist/__tests__/coordination-token-multitenant.test.js.map +1 -1
  79. package/dist/__tests__/coordination-token.test.js +35 -28
  80. package/dist/__tests__/coordination-token.test.js.map +1 -1
  81. package/dist/__tests__/creation-pr-class-check.test.d.ts +17 -0
  82. package/dist/__tests__/creation-pr-class-check.test.d.ts.map +1 -0
  83. package/dist/__tests__/creation-pr-class-check.test.js +346 -0
  84. package/dist/__tests__/creation-pr-class-check.test.js.map +1 -0
  85. package/dist/__tests__/decision-check.test.d.ts +2 -0
  86. package/dist/__tests__/decision-check.test.d.ts.map +1 -0
  87. package/dist/__tests__/decision-check.test.js +105 -0
  88. package/dist/__tests__/decision-check.test.js.map +1 -0
  89. package/dist/__tests__/digest-team-omission.test.d.ts +15 -0
  90. package/dist/__tests__/digest-team-omission.test.d.ts.map +1 -0
  91. package/dist/__tests__/digest-team-omission.test.js +247 -0
  92. package/dist/__tests__/digest-team-omission.test.js.map +1 -0
  93. package/dist/__tests__/doctor-worktree-path.test.d.ts +17 -0
  94. package/dist/__tests__/doctor-worktree-path.test.d.ts.map +1 -0
  95. package/dist/__tests__/doctor-worktree-path.test.js +158 -0
  96. package/dist/__tests__/doctor-worktree-path.test.js.map +1 -0
  97. package/dist/__tests__/fleet-data.test.js +40 -7
  98. package/dist/__tests__/fleet-data.test.js.map +1 -1
  99. package/dist/__tests__/fleet-tmux.test.js +2 -2
  100. package/dist/__tests__/fleet-tmux.test.js.map +1 -1
  101. package/dist/__tests__/generate-claude.test.js +137 -3
  102. package/dist/__tests__/generate-claude.test.js.map +1 -1
  103. package/dist/__tests__/git-env.test.d.ts +14 -0
  104. package/dist/__tests__/git-env.test.d.ts.map +1 -0
  105. package/dist/__tests__/git-env.test.js +131 -0
  106. package/dist/__tests__/git-env.test.js.map +1 -0
  107. package/dist/__tests__/git-identity-isolation.test.d.ts +33 -0
  108. package/dist/__tests__/git-identity-isolation.test.d.ts.map +1 -0
  109. package/dist/__tests__/git-identity-isolation.test.js +626 -0
  110. package/dist/__tests__/git-identity-isolation.test.js.map +1 -0
  111. package/dist/__tests__/harness-extract.test.d.ts +19 -0
  112. package/dist/__tests__/harness-extract.test.d.ts.map +1 -0
  113. package/dist/__tests__/harness-extract.test.js +566 -0
  114. package/dist/__tests__/harness-extract.test.js.map +1 -0
  115. package/dist/__tests__/harness-wiring.test.d.ts +16 -0
  116. package/dist/__tests__/harness-wiring.test.d.ts.map +1 -0
  117. package/dist/__tests__/harness-wiring.test.js +469 -0
  118. package/dist/__tests__/harness-wiring.test.js.map +1 -0
  119. package/dist/__tests__/hook-heal.test.js +17 -0
  120. package/dist/__tests__/hook-heal.test.js.map +1 -1
  121. package/dist/__tests__/init-coordination-url.test.d.ts +11 -0
  122. package/dist/__tests__/init-coordination-url.test.d.ts.map +1 -0
  123. package/dist/__tests__/init-coordination-url.test.js +114 -0
  124. package/dist/__tests__/init-coordination-url.test.js.map +1 -0
  125. package/dist/__tests__/memory-autocreate.test.js +574 -8
  126. package/dist/__tests__/memory-autocreate.test.js.map +1 -1
  127. package/dist/__tests__/memory-log-result.test.d.ts +13 -0
  128. package/dist/__tests__/memory-log-result.test.d.ts.map +1 -0
  129. package/dist/__tests__/memory-log-result.test.js +113 -0
  130. package/dist/__tests__/memory-log-result.test.js.map +1 -0
  131. package/dist/__tests__/memory-named-exists.test.d.ts +16 -0
  132. package/dist/__tests__/memory-named-exists.test.d.ts.map +1 -0
  133. package/dist/__tests__/memory-named-exists.test.js +288 -0
  134. package/dist/__tests__/memory-named-exists.test.js.map +1 -0
  135. package/dist/__tests__/mx-agent-cli-pin-validation.test.js +23 -47
  136. package/dist/__tests__/mx-agent-cli-pin-validation.test.js.map +1 -1
  137. package/dist/__tests__/mx-agent-cli-version-pin.test.js +34 -88
  138. package/dist/__tests__/mx-agent-cli-version-pin.test.js.map +1 -1
  139. package/dist/__tests__/new-project-first-team.test.d.ts +15 -0
  140. package/dist/__tests__/new-project-first-team.test.d.ts.map +1 -0
  141. package/dist/__tests__/new-project-first-team.test.js +263 -0
  142. package/dist/__tests__/new-project-first-team.test.js.map +1 -0
  143. package/dist/__tests__/otel-env.test.d.ts +2 -0
  144. package/dist/__tests__/otel-env.test.d.ts.map +1 -0
  145. package/dist/__tests__/otel-env.test.js +127 -0
  146. package/dist/__tests__/otel-env.test.js.map +1 -0
  147. package/dist/__tests__/project-config.test.js +283 -1
  148. package/dist/__tests__/project-config.test.js.map +1 -1
  149. package/dist/__tests__/provision-behavioral-contract.test.js +96 -4
  150. package/dist/__tests__/provision-behavioral-contract.test.js.map +1 -1
  151. package/dist/__tests__/provision-catalog-precondition.test.d.ts +26 -0
  152. package/dist/__tests__/provision-catalog-precondition.test.d.ts.map +1 -0
  153. package/dist/__tests__/provision-catalog-precondition.test.js +620 -0
  154. package/dist/__tests__/provision-catalog-precondition.test.js.map +1 -0
  155. package/dist/__tests__/provision-completion-rows.test.d.ts +17 -0
  156. package/dist/__tests__/provision-completion-rows.test.d.ts.map +1 -0
  157. package/dist/__tests__/provision-completion-rows.test.js +3187 -0
  158. package/dist/__tests__/provision-completion-rows.test.js.map +1 -0
  159. package/dist/__tests__/provision-identity-gate.test.d.ts +20 -0
  160. package/dist/__tests__/provision-identity-gate.test.d.ts.map +1 -0
  161. package/dist/__tests__/provision-identity-gate.test.js +600 -0
  162. package/dist/__tests__/provision-identity-gate.test.js.map +1 -0
  163. package/dist/__tests__/provision-resume.test.d.ts +26 -0
  164. package/dist/__tests__/provision-resume.test.d.ts.map +1 -0
  165. package/dist/__tests__/provision-resume.test.js +1164 -0
  166. package/dist/__tests__/provision-resume.test.js.map +1 -0
  167. package/dist/__tests__/provision-roleguide-anchors.test.d.ts +27 -0
  168. package/dist/__tests__/provision-roleguide-anchors.test.d.ts.map +1 -0
  169. package/dist/__tests__/provision-roleguide-anchors.test.js +747 -0
  170. package/dist/__tests__/provision-roleguide-anchors.test.js.map +1 -0
  171. package/dist/__tests__/provision-skeleton-fill.test.d.ts +16 -0
  172. package/dist/__tests__/provision-skeleton-fill.test.d.ts.map +1 -0
  173. package/dist/__tests__/provision-skeleton-fill.test.js +488 -0
  174. package/dist/__tests__/provision-skeleton-fill.test.js.map +1 -0
  175. package/dist/__tests__/provision-teambuilder-flow.test.js +93 -7
  176. package/dist/__tests__/provision-teambuilder-flow.test.js.map +1 -1
  177. package/dist/__tests__/repo-guard-wiring.test.d.ts +21 -0
  178. package/dist/__tests__/repo-guard-wiring.test.d.ts.map +1 -0
  179. package/dist/__tests__/repo-guard-wiring.test.js +638 -0
  180. package/dist/__tests__/repo-guard-wiring.test.js.map +1 -0
  181. package/dist/__tests__/report-format.test.d.ts +2 -0
  182. package/dist/__tests__/report-format.test.d.ts.map +1 -0
  183. package/dist/__tests__/report-format.test.js +219 -0
  184. package/dist/__tests__/report-format.test.js.map +1 -0
  185. package/dist/__tests__/row15-detail-sanitizer.test.d.ts +20 -0
  186. package/dist/__tests__/row15-detail-sanitizer.test.d.ts.map +1 -0
  187. package/dist/__tests__/row15-detail-sanitizer.test.js +61 -0
  188. package/dist/__tests__/row15-detail-sanitizer.test.js.map +1 -0
  189. package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts +2 -0
  190. package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts.map +1 -0
  191. package/dist/__tests__/runtime-codex-gateway-pilot.test.js +309 -0
  192. package/dist/__tests__/runtime-codex-gateway-pilot.test.js.map +1 -0
  193. package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts +2 -0
  194. package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts.map +1 -0
  195. package/dist/__tests__/runtime-codex-gateway-provider.test.js +163 -0
  196. package/dist/__tests__/runtime-codex-gateway-provider.test.js.map +1 -0
  197. package/dist/__tests__/runtime-identity.test.d.ts +2 -0
  198. package/dist/__tests__/runtime-identity.test.d.ts.map +1 -0
  199. package/dist/__tests__/runtime-identity.test.js +117 -0
  200. package/dist/__tests__/runtime-identity.test.js.map +1 -0
  201. package/dist/__tests__/session-pause-provisioning.test.js +6 -1
  202. package/dist/__tests__/session-pause-provisioning.test.js.map +1 -1
  203. package/dist/__tests__/session-record-disclosure.test.d.ts +24 -0
  204. package/dist/__tests__/session-record-disclosure.test.d.ts.map +1 -0
  205. package/dist/__tests__/session-record-disclosure.test.js +494 -0
  206. package/dist/__tests__/session-record-disclosure.test.js.map +1 -0
  207. package/dist/__tests__/session.test.js +35 -0
  208. package/dist/__tests__/session.test.js.map +1 -1
  209. package/dist/__tests__/slug-validation.test.js +27 -21
  210. package/dist/__tests__/slug-validation.test.js.map +1 -1
  211. package/dist/__tests__/standards-injection.test.d.ts +2 -0
  212. package/dist/__tests__/standards-injection.test.d.ts.map +1 -0
  213. package/dist/__tests__/standards-injection.test.js +179 -0
  214. package/dist/__tests__/standards-injection.test.js.map +1 -0
  215. package/dist/__tests__/start-interactive-role.test.d.ts +22 -0
  216. package/dist/__tests__/start-interactive-role.test.d.ts.map +1 -0
  217. package/dist/__tests__/start-interactive-role.test.js +204 -0
  218. package/dist/__tests__/start-interactive-role.test.js.map +1 -0
  219. package/dist/__tests__/start-team-identity.test.d.ts +25 -0
  220. package/dist/__tests__/start-team-identity.test.d.ts.map +1 -0
  221. package/dist/__tests__/start-team-identity.test.js +307 -0
  222. package/dist/__tests__/start-team-identity.test.js.map +1 -0
  223. package/dist/__tests__/team-memory-commands.test.js +142 -19
  224. package/dist/__tests__/team-memory-commands.test.js.map +1 -1
  225. package/dist/__tests__/template-sync.test.d.ts +19 -0
  226. package/dist/__tests__/template-sync.test.d.ts.map +1 -0
  227. package/dist/__tests__/template-sync.test.js +270 -0
  228. package/dist/__tests__/template-sync.test.js.map +1 -0
  229. package/dist/__tests__/test-project.test.d.ts +18 -0
  230. package/dist/__tests__/test-project.test.d.ts.map +1 -0
  231. package/dist/__tests__/test-project.test.js +465 -0
  232. package/dist/__tests__/test-project.test.js.map +1 -0
  233. package/dist/__tests__/usage-per-call-grouping.test.d.ts +25 -0
  234. package/dist/__tests__/usage-per-call-grouping.test.d.ts.map +1 -0
  235. package/dist/__tests__/usage-per-call-grouping.test.js +952 -0
  236. package/dist/__tests__/usage-per-call-grouping.test.js.map +1 -0
  237. package/dist/__tests__/verify-hooks-check-all.test.d.ts +32 -0
  238. package/dist/__tests__/verify-hooks-check-all.test.d.ts.map +1 -0
  239. package/dist/__tests__/verify-hooks-check-all.test.js +553 -0
  240. package/dist/__tests__/verify-hooks-check-all.test.js.map +1 -0
  241. package/dist/__tests__/worktree-sync-fixture.test.d.ts +17 -0
  242. package/dist/__tests__/worktree-sync-fixture.test.d.ts.map +1 -0
  243. package/dist/__tests__/worktree-sync-fixture.test.js +519 -0
  244. package/dist/__tests__/worktree-sync-fixture.test.js.map +1 -0
  245. package/dist/__tests__/worktree-sync-hardening.test.d.ts +13 -0
  246. package/dist/__tests__/worktree-sync-hardening.test.d.ts.map +1 -0
  247. package/dist/__tests__/worktree-sync-hardening.test.js +919 -0
  248. package/dist/__tests__/worktree-sync-hardening.test.js.map +1 -0
  249. package/dist/__tests__/worktree-sync-shell-free.test.d.ts +25 -0
  250. package/dist/__tests__/worktree-sync-shell-free.test.d.ts.map +1 -0
  251. package/dist/__tests__/worktree-sync-shell-free.test.js +185 -0
  252. package/dist/__tests__/worktree-sync-shell-free.test.js.map +1 -0
  253. package/dist/__tests__/worktree.test.js +75 -1
  254. package/dist/__tests__/worktree.test.js.map +1 -1
  255. package/dist/agent-config/.mx-config-generation.json +2 -2
  256. package/dist/agent-config/AGENTS.md.template +2 -2
  257. package/dist/agent-config/agents/bar-raiser.md +34 -1
  258. package/dist/agent-config/agents/red-team.md +34 -1
  259. package/dist/agent-config/agents/security-reviewer.md +22 -1
  260. package/dist/agent-config/claude-md/CLAUDE.core.md +6 -1
  261. package/dist/agent-config/claude-md/CLAUDE.overlay.memnexus.md +1 -3
  262. package/dist/agent-config/coordination-rosters.generated.json +10 -0
  263. package/dist/agent-config/hooks/HOOK-TIMEOUTS.md +27 -1
  264. package/dist/agent-config/hooks/OR-TRUE-AUDIT.md +8 -8
  265. package/dist/agent-config/hooks/auto-capture-precompact.sh +180 -83
  266. package/dist/agent-config/hooks/auto-capture-session-end.sh +216 -87
  267. package/dist/agent-config/hooks/auto-checkpoint.sh +75 -5
  268. package/dist/agent-config/hooks/coordination-brief.sh +290 -245
  269. package/dist/agent-config/hooks/deploy-verification-reminder.sh +359 -22
  270. package/dist/agent-config/hooks/git-mutation-guard.sh +85 -13
  271. package/dist/agent-config/hooks/observability-sync.sh +46 -9
  272. package/dist/agent-config/hooks/session-idle-gate.sh +177 -12
  273. package/dist/agent-config/hooks/subagent-write-guard.sh +670 -0
  274. package/dist/agent-config/hooks/worktree-guard.sh +36 -7
  275. package/dist/agent-config/settings.json +15 -2
  276. package/dist/agent-config/shared/creation-pr-review-checklist.md +317 -0
  277. package/dist/commands/bootstrap.d.ts.map +1 -1
  278. package/dist/commands/bootstrap.js +22 -10
  279. package/dist/commands/bootstrap.js.map +1 -1
  280. package/dist/commands/config-sync.d.ts +37 -0
  281. package/dist/commands/config-sync.d.ts.map +1 -1
  282. package/dist/commands/config-sync.js +36 -18
  283. package/dist/commands/config-sync.js.map +1 -1
  284. package/dist/commands/config.d.ts.map +1 -1
  285. package/dist/commands/config.js +28 -1
  286. package/dist/commands/config.js.map +1 -1
  287. package/dist/commands/coordination.d.ts +150 -8
  288. package/dist/commands/coordination.d.ts.map +1 -1
  289. package/dist/commands/coordination.js +524 -25
  290. package/dist/commands/coordination.js.map +1 -1
  291. package/dist/commands/create.d.ts +922 -1
  292. package/dist/commands/create.d.ts.map +1 -1
  293. package/dist/commands/create.js +4934 -345
  294. package/dist/commands/create.js.map +1 -1
  295. package/dist/commands/dashboard.d.ts.map +1 -1
  296. package/dist/commands/dashboard.js +10 -2
  297. package/dist/commands/dashboard.js.map +1 -1
  298. package/dist/commands/decision.d.ts +20 -0
  299. package/dist/commands/decision.d.ts.map +1 -0
  300. package/dist/commands/decision.js +54 -0
  301. package/dist/commands/decision.js.map +1 -0
  302. package/dist/commands/digest.d.ts.map +1 -1
  303. package/dist/commands/digest.js +91 -7
  304. package/dist/commands/digest.js.map +1 -1
  305. package/dist/commands/fleet-tmux.js +1 -1
  306. package/dist/commands/fleet-tmux.js.map +1 -1
  307. package/dist/commands/init.d.ts +8 -0
  308. package/dist/commands/init.d.ts.map +1 -1
  309. package/dist/commands/init.js +26 -1
  310. package/dist/commands/init.js.map +1 -1
  311. package/dist/commands/list.d.ts +32 -1
  312. package/dist/commands/list.d.ts.map +1 -1
  313. package/dist/commands/list.js +98 -5
  314. package/dist/commands/list.js.map +1 -1
  315. package/dist/commands/monitor.d.ts.map +1 -1
  316. package/dist/commands/monitor.js +8 -2
  317. package/dist/commands/monitor.js.map +1 -1
  318. package/dist/commands/new.d.ts +2 -0
  319. package/dist/commands/new.d.ts.map +1 -1
  320. package/dist/commands/new.js +114 -21
  321. package/dist/commands/new.js.map +1 -1
  322. package/dist/commands/report.d.ts +33 -0
  323. package/dist/commands/report.d.ts.map +1 -0
  324. package/dist/commands/report.js +73 -0
  325. package/dist/commands/report.js.map +1 -0
  326. package/dist/commands/session.js +1 -1
  327. package/dist/commands/session.js.map +1 -1
  328. package/dist/commands/start.d.ts +42 -0
  329. package/dist/commands/start.d.ts.map +1 -1
  330. package/dist/commands/start.js +183 -8
  331. package/dist/commands/start.js.map +1 -1
  332. package/dist/commands/sync.d.ts +57 -0
  333. package/dist/commands/sync.d.ts.map +1 -1
  334. package/dist/commands/sync.js +117 -3
  335. package/dist/commands/sync.js.map +1 -1
  336. package/dist/commands/update.d.ts +13 -1
  337. package/dist/commands/update.d.ts.map +1 -1
  338. package/dist/commands/update.js +50 -1
  339. package/dist/commands/update.js.map +1 -1
  340. package/dist/commands/usage.d.ts +64 -0
  341. package/dist/commands/usage.d.ts.map +1 -1
  342. package/dist/commands/usage.js +96 -3
  343. package/dist/commands/usage.js.map +1 -1
  344. package/dist/commands/verify-hooks.d.ts +37 -1
  345. package/dist/commands/verify-hooks.d.ts.map +1 -1
  346. package/dist/commands/verify-hooks.js +114 -2
  347. package/dist/commands/verify-hooks.js.map +1 -1
  348. package/dist/commands/window.d.ts +10 -0
  349. package/dist/commands/window.d.ts.map +1 -0
  350. package/dist/commands/window.js +265 -0
  351. package/dist/commands/window.js.map +1 -0
  352. package/dist/commands/worktree-sync.d.ts +54 -0
  353. package/dist/commands/worktree-sync.d.ts.map +1 -0
  354. package/dist/commands/worktree-sync.js +135 -0
  355. package/dist/commands/worktree-sync.js.map +1 -0
  356. package/dist/index.d.ts.map +1 -1
  357. package/dist/index.js +189 -14
  358. package/dist/index.js.map +1 -1
  359. package/dist/lib/agent-session.d.ts +12 -0
  360. package/dist/lib/agent-session.d.ts.map +1 -1
  361. package/dist/lib/agent-session.js +189 -42
  362. package/dist/lib/agent-session.js.map +1 -1
  363. package/dist/lib/behavioral-injection.d.ts +9 -0
  364. package/dist/lib/behavioral-injection.d.ts.map +1 -1
  365. package/dist/lib/behavioral-injection.js +10 -1
  366. package/dist/lib/behavioral-injection.js.map +1 -1
  367. package/dist/lib/catalog.d.ts +321 -2
  368. package/dist/lib/catalog.d.ts.map +1 -1
  369. package/dist/lib/catalog.js +490 -11
  370. package/dist/lib/catalog.js.map +1 -1
  371. package/dist/lib/claude.d.ts +113 -23
  372. package/dist/lib/claude.d.ts.map +1 -1
  373. package/dist/lib/claude.js +498 -32
  374. package/dist/lib/claude.js.map +1 -1
  375. package/dist/lib/cli-build.d.ts +172 -0
  376. package/dist/lib/cli-build.d.ts.map +1 -0
  377. package/dist/lib/cli-build.js +654 -0
  378. package/dist/lib/cli-build.js.map +1 -0
  379. package/dist/lib/code-context-file.d.ts +109 -0
  380. package/dist/lib/code-context-file.d.ts.map +1 -0
  381. package/dist/lib/code-context-file.js +219 -0
  382. package/dist/lib/code-context-file.js.map +1 -0
  383. package/dist/lib/code-context-file.test.d.ts +19 -0
  384. package/dist/lib/code-context-file.test.d.ts.map +1 -0
  385. package/dist/lib/code-context-file.test.js +202 -0
  386. package/dist/lib/code-context-file.test.js.map +1 -0
  387. package/dist/lib/config-fidelity.d.ts +40 -20
  388. package/dist/lib/config-fidelity.d.ts.map +1 -1
  389. package/dist/lib/config-fidelity.js +144 -56
  390. package/dist/lib/config-fidelity.js.map +1 -1
  391. package/dist/lib/coordination-client.d.ts +101 -0
  392. package/dist/lib/coordination-client.d.ts.map +1 -1
  393. package/dist/lib/coordination-client.js +232 -8
  394. package/dist/lib/coordination-client.js.map +1 -1
  395. package/dist/lib/coordination-token.d.ts +333 -6
  396. package/dist/lib/coordination-token.d.ts.map +1 -1
  397. package/dist/lib/coordination-token.js +875 -52
  398. package/dist/lib/coordination-token.js.map +1 -1
  399. package/dist/lib/decision-check.d.ts +48 -0
  400. package/dist/lib/decision-check.d.ts.map +1 -0
  401. package/dist/lib/decision-check.js +149 -0
  402. package/dist/lib/decision-check.js.map +1 -0
  403. package/dist/lib/fleet-data.d.ts +34 -0
  404. package/dist/lib/fleet-data.d.ts.map +1 -1
  405. package/dist/lib/fleet-data.js +37 -9
  406. package/dist/lib/fleet-data.js.map +1 -1
  407. package/dist/lib/fleet-render.js +1 -1
  408. package/dist/lib/fleet-render.js.map +1 -1
  409. package/dist/lib/git-identity.d.ts +302 -0
  410. package/dist/lib/git-identity.d.ts.map +1 -0
  411. package/dist/lib/git-identity.js +546 -0
  412. package/dist/lib/git-identity.js.map +1 -0
  413. package/dist/lib/harness/console/announce.d.ts +45 -0
  414. package/dist/lib/harness/console/announce.d.ts.map +1 -0
  415. package/dist/lib/harness/console/announce.js +48 -0
  416. package/dist/lib/harness/console/announce.js.map +1 -0
  417. package/dist/lib/harness/console/announce.test.d.ts +2 -0
  418. package/dist/lib/harness/console/announce.test.d.ts.map +1 -0
  419. package/dist/lib/harness/console/announce.test.js +104 -0
  420. package/dist/lib/harness/console/announce.test.js.map +1 -0
  421. package/dist/lib/harness/console/by-session.d.ts +50 -0
  422. package/dist/lib/harness/console/by-session.d.ts.map +1 -0
  423. package/dist/lib/harness/console/by-session.js +83 -0
  424. package/dist/lib/harness/console/by-session.js.map +1 -0
  425. package/dist/lib/harness/console/by-session.test.d.ts +2 -0
  426. package/dist/lib/harness/console/by-session.test.d.ts.map +1 -0
  427. package/dist/lib/harness/console/by-session.test.js +86 -0
  428. package/dist/lib/harness/console/by-session.test.js.map +1 -0
  429. package/dist/lib/harness/console/console.d.ts +67 -0
  430. package/dist/lib/harness/console/console.d.ts.map +1 -0
  431. package/dist/lib/harness/console/console.js +373 -0
  432. package/dist/lib/harness/console/console.js.map +1 -0
  433. package/dist/lib/harness/console/console.test.d.ts +2 -0
  434. package/dist/lib/harness/console/console.test.d.ts.map +1 -0
  435. package/dist/lib/harness/console/console.test.js +269 -0
  436. package/dist/lib/harness/console/console.test.js.map +1 -0
  437. package/dist/lib/harness/console/decision-request.d.ts +32 -0
  438. package/dist/lib/harness/console/decision-request.d.ts.map +1 -0
  439. package/dist/lib/harness/console/decision-request.js +112 -0
  440. package/dist/lib/harness/console/decision-request.js.map +1 -0
  441. package/dist/lib/harness/console/decision-request.test.d.ts +2 -0
  442. package/dist/lib/harness/console/decision-request.test.d.ts.map +1 -0
  443. package/dist/lib/harness/console/decision-request.test.js +75 -0
  444. package/dist/lib/harness/console/decision-request.test.js.map +1 -0
  445. package/dist/lib/harness/console/fixtures.d.ts +16 -0
  446. package/dist/lib/harness/console/fixtures.d.ts.map +1 -0
  447. package/dist/lib/harness/console/fixtures.js +49 -0
  448. package/dist/lib/harness/console/fixtures.js.map +1 -0
  449. package/dist/lib/harness/console/index.d.ts +15 -0
  450. package/dist/lib/harness/console/index.d.ts.map +1 -0
  451. package/dist/lib/harness/console/index.js +14 -0
  452. package/dist/lib/harness/console/index.js.map +1 -0
  453. package/dist/lib/harness/console/rank.d.ts +73 -0
  454. package/dist/lib/harness/console/rank.d.ts.map +1 -0
  455. package/dist/lib/harness/console/rank.js +113 -0
  456. package/dist/lib/harness/console/rank.js.map +1 -0
  457. package/dist/lib/harness/console/rank.test.d.ts +2 -0
  458. package/dist/lib/harness/console/rank.test.d.ts.map +1 -0
  459. package/dist/lib/harness/console/rank.test.js +124 -0
  460. package/dist/lib/harness/console/rank.test.js.map +1 -0
  461. package/dist/lib/harness/console/render.d.ts +22 -0
  462. package/dist/lib/harness/console/render.d.ts.map +1 -0
  463. package/dist/lib/harness/console/render.js +65 -0
  464. package/dist/lib/harness/console/render.js.map +1 -0
  465. package/dist/lib/harness/console/render.test.d.ts +2 -0
  466. package/dist/lib/harness/console/render.test.d.ts.map +1 -0
  467. package/dist/lib/harness/console/render.test.js +96 -0
  468. package/dist/lib/harness/console/render.test.js.map +1 -0
  469. package/dist/lib/harness/console/replay-cli.test.d.ts +2 -0
  470. package/dist/lib/harness/console/replay-cli.test.d.ts.map +1 -0
  471. package/dist/lib/harness/console/replay-cli.test.js +96 -0
  472. package/dist/lib/harness/console/replay-cli.test.js.map +1 -0
  473. package/dist/lib/harness/console/replay.d.ts +36 -0
  474. package/dist/lib/harness/console/replay.d.ts.map +1 -0
  475. package/dist/lib/harness/console/replay.js +59 -0
  476. package/dist/lib/harness/console/replay.js.map +1 -0
  477. package/dist/lib/harness/console/replay.test.d.ts +2 -0
  478. package/dist/lib/harness/console/replay.test.d.ts.map +1 -0
  479. package/dist/lib/harness/console/replay.test.js +81 -0
  480. package/dist/lib/harness/console/replay.test.js.map +1 -0
  481. package/dist/lib/harness/console/turn-reader.d.ts +50 -0
  482. package/dist/lib/harness/console/turn-reader.d.ts.map +1 -0
  483. package/dist/lib/harness/console/turn-reader.js +184 -0
  484. package/dist/lib/harness/console/turn-reader.js.map +1 -0
  485. package/dist/lib/harness/console/turn-reader.test.d.ts +2 -0
  486. package/dist/lib/harness/console/turn-reader.test.d.ts.map +1 -0
  487. package/dist/lib/harness/console/turn-reader.test.js +108 -0
  488. package/dist/lib/harness/console/turn-reader.test.js.map +1 -0
  489. package/dist/lib/harness/console/types.d.ts +109 -0
  490. package/dist/lib/harness/console/types.d.ts.map +1 -0
  491. package/dist/lib/harness/console/types.js +2 -0
  492. package/dist/lib/harness/console/types.js.map +1 -0
  493. package/dist/lib/harness/contract.d.ts +229 -0
  494. package/dist/lib/harness/contract.d.ts.map +1 -0
  495. package/dist/lib/harness/contract.js +22 -0
  496. package/dist/lib/harness/contract.js.map +1 -0
  497. package/dist/lib/harness/credential.d.ts +23 -0
  498. package/dist/lib/harness/credential.d.ts.map +1 -0
  499. package/dist/lib/harness/credential.js +81 -0
  500. package/dist/lib/harness/credential.js.map +1 -0
  501. package/dist/lib/harness/credential.test.d.ts +2 -0
  502. package/dist/lib/harness/credential.test.d.ts.map +1 -0
  503. package/dist/lib/harness/credential.test.js +74 -0
  504. package/dist/lib/harness/credential.test.js.map +1 -0
  505. package/dist/lib/harness/evaluate.d.ts +390 -0
  506. package/dist/lib/harness/evaluate.d.ts.map +1 -0
  507. package/dist/lib/harness/evaluate.js +988 -0
  508. package/dist/lib/harness/evaluate.js.map +1 -0
  509. package/dist/lib/harness/evaluate.test.d.ts +2 -0
  510. package/dist/lib/harness/evaluate.test.d.ts.map +1 -0
  511. package/dist/lib/harness/evaluate.test.js +621 -0
  512. package/dist/lib/harness/evaluate.test.js.map +1 -0
  513. package/dist/lib/harness/extract.d.ts +152 -0
  514. package/dist/lib/harness/extract.d.ts.map +1 -0
  515. package/dist/lib/harness/extract.js +1601 -0
  516. package/dist/lib/harness/extract.js.map +1 -0
  517. package/dist/lib/harness/gate.d.ts +48 -0
  518. package/dist/lib/harness/gate.d.ts.map +1 -0
  519. package/dist/lib/harness/gate.js +60 -0
  520. package/dist/lib/harness/gate.js.map +1 -0
  521. package/dist/lib/harness/gate.test.d.ts +2 -0
  522. package/dist/lib/harness/gate.test.d.ts.map +1 -0
  523. package/dist/lib/harness/gate.test.js +111 -0
  524. package/dist/lib/harness/gate.test.js.map +1 -0
  525. package/dist/lib/harness/self-check.d.ts +59 -0
  526. package/dist/lib/harness/self-check.d.ts.map +1 -0
  527. package/dist/lib/harness/self-check.js +56 -0
  528. package/dist/lib/harness/self-check.js.map +1 -0
  529. package/dist/lib/harness/self-check.test.d.ts +2 -0
  530. package/dist/lib/harness/self-check.test.d.ts.map +1 -0
  531. package/dist/lib/harness/self-check.test.js +43 -0
  532. package/dist/lib/harness/self-check.test.js.map +1 -0
  533. package/dist/lib/harness/transcript.d.ts +65 -0
  534. package/dist/lib/harness/transcript.d.ts.map +1 -0
  535. package/dist/lib/harness/transcript.js +144 -0
  536. package/dist/lib/harness/transcript.js.map +1 -0
  537. package/dist/lib/harness/transcript.test.d.ts +2 -0
  538. package/dist/lib/harness/transcript.test.d.ts.map +1 -0
  539. package/dist/lib/harness/transcript.test.js +118 -0
  540. package/dist/lib/harness/transcript.test.js.map +1 -0
  541. package/dist/lib/harness-wiring.d.ts +145 -0
  542. package/dist/lib/harness-wiring.d.ts.map +1 -0
  543. package/dist/lib/harness-wiring.js +280 -0
  544. package/dist/lib/harness-wiring.js.map +1 -0
  545. package/dist/lib/hook-staleness.d.ts +95 -0
  546. package/dist/lib/hook-staleness.d.ts.map +1 -0
  547. package/dist/lib/hook-staleness.js +304 -0
  548. package/dist/lib/hook-staleness.js.map +1 -0
  549. package/dist/lib/jsonl.d.ts +270 -2
  550. package/dist/lib/jsonl.d.ts.map +1 -1
  551. package/dist/lib/jsonl.js +472 -76
  552. package/dist/lib/jsonl.js.map +1 -1
  553. package/dist/lib/memory.d.ts +350 -23
  554. package/dist/lib/memory.d.ts.map +1 -1
  555. package/dist/lib/memory.js +751 -38
  556. package/dist/lib/memory.js.map +1 -1
  557. package/dist/lib/otel-env.d.ts +90 -0
  558. package/dist/lib/otel-env.d.ts.map +1 -0
  559. package/dist/lib/otel-env.js +98 -0
  560. package/dist/lib/otel-env.js.map +1 -0
  561. package/dist/lib/project-config.d.ts +167 -0
  562. package/dist/lib/project-config.d.ts.map +1 -1
  563. package/dist/lib/project-config.js +321 -5
  564. package/dist/lib/project-config.js.map +1 -1
  565. package/dist/lib/projects-registry.d.ts +82 -0
  566. package/dist/lib/projects-registry.d.ts.map +1 -0
  567. package/dist/lib/projects-registry.js +145 -0
  568. package/dist/lib/projects-registry.js.map +1 -0
  569. package/dist/lib/projects-registry.test.d.ts +2 -0
  570. package/dist/lib/projects-registry.test.d.ts.map +1 -0
  571. package/dist/lib/projects-registry.test.js +176 -0
  572. package/dist/lib/projects-registry.test.js.map +1 -0
  573. package/dist/lib/repo-guard-scope.d.ts +126 -0
  574. package/dist/lib/repo-guard-scope.d.ts.map +1 -0
  575. package/dist/lib/repo-guard-scope.js +249 -0
  576. package/dist/lib/repo-guard-scope.js.map +1 -0
  577. package/dist/lib/report-format.d.ts +132 -0
  578. package/dist/lib/report-format.d.ts.map +1 -0
  579. package/dist/lib/report-format.js +317 -0
  580. package/dist/lib/report-format.js.map +1 -0
  581. package/dist/lib/roster.d.ts +99 -0
  582. package/dist/lib/roster.d.ts.map +1 -0
  583. package/dist/lib/roster.js +336 -0
  584. package/dist/lib/roster.js.map +1 -0
  585. package/dist/lib/roster.test.d.ts +15 -0
  586. package/dist/lib/roster.test.d.ts.map +1 -0
  587. package/dist/lib/roster.test.js +299 -0
  588. package/dist/lib/roster.test.js.map +1 -0
  589. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  590. package/dist/lib/runtime/codex-adapter.js +5 -0
  591. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  592. package/dist/lib/runtime/codex-config.d.ts +129 -0
  593. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  594. package/dist/lib/runtime/codex-config.js +225 -0
  595. package/dist/lib/runtime/codex-config.js.map +1 -1
  596. package/dist/lib/runtime/identity.d.ts +72 -0
  597. package/dist/lib/runtime/identity.d.ts.map +1 -0
  598. package/dist/lib/runtime/identity.js +128 -0
  599. package/dist/lib/runtime/identity.js.map +1 -0
  600. package/dist/lib/standards.d.ts +99 -0
  601. package/dist/lib/standards.d.ts.map +1 -0
  602. package/dist/lib/standards.js +201 -0
  603. package/dist/lib/standards.js.map +1 -0
  604. package/dist/lib/team-identity.d.ts +134 -0
  605. package/dist/lib/team-identity.d.ts.map +1 -0
  606. package/dist/lib/team-identity.js +193 -0
  607. package/dist/lib/team-identity.js.map +1 -0
  608. package/dist/lib/templates.d.ts +29 -2
  609. package/dist/lib/templates.d.ts.map +1 -1
  610. package/dist/lib/templates.js +1042 -82
  611. package/dist/lib/templates.js.map +1 -1
  612. package/dist/lib/terminal-ui.d.ts.map +1 -1
  613. package/dist/lib/terminal-ui.js +12 -1
  614. package/dist/lib/terminal-ui.js.map +1 -1
  615. package/dist/lib/test-project.d.ts +95 -0
  616. package/dist/lib/test-project.d.ts.map +1 -0
  617. package/dist/lib/test-project.js +103 -0
  618. package/dist/lib/test-project.js.map +1 -0
  619. package/dist/lib/vault.d.ts +60 -0
  620. package/dist/lib/vault.d.ts.map +1 -0
  621. package/dist/lib/vault.js +102 -0
  622. package/dist/lib/vault.js.map +1 -0
  623. package/dist/lib/vault.test.d.ts +17 -0
  624. package/dist/lib/vault.test.d.ts.map +1 -0
  625. package/dist/lib/vault.test.js +169 -0
  626. package/dist/lib/vault.test.js.map +1 -0
  627. package/dist/lib/window-view.d.ts +63 -0
  628. package/dist/lib/window-view.d.ts.map +1 -0
  629. package/dist/lib/window-view.js +217 -0
  630. package/dist/lib/window-view.js.map +1 -0
  631. package/dist/lib/window-view.test.d.ts +2 -0
  632. package/dist/lib/window-view.test.d.ts.map +1 -0
  633. package/dist/lib/window-view.test.js +168 -0
  634. package/dist/lib/window-view.test.js.map +1 -0
  635. package/dist/lib/worktree-sync.d.ts +439 -0
  636. package/dist/lib/worktree-sync.d.ts.map +1 -0
  637. package/dist/lib/worktree-sync.js +1167 -0
  638. package/dist/lib/worktree-sync.js.map +1 -0
  639. package/dist/lib/worktree.d.ts +58 -1
  640. package/dist/lib/worktree.d.ts.map +1 -1
  641. package/dist/lib/worktree.js +91 -4
  642. package/dist/lib/worktree.js.map +1 -1
  643. package/dist/standards/decision-request.md +98 -0
  644. package/dist/standards/fail-loud-standard.md +495 -0
  645. package/dist/standards/po-communication-standard.md +126 -0
  646. package/dist/standards/report-format.md +128 -0
  647. package/dist/standards/writing-standard.md +382 -0
  648. package/package.json +3 -2
  649. package/scripts/generate-claude.mjs +119 -46
@@ -0,0 +1,1164 @@
1
+ /**
2
+ * Resumable creation (#5, #76, #295; plan #316).
3
+ *
4
+ * A provision that failed after the worktree was created could not be retried:
5
+ * the second run met `Worktree already exists at ...` and exited before it
6
+ * checked anything (`create.ts:3620-3624` at `7d336e0`, reproduced live by the
7
+ * v25 probe at `99d01b1`). The catalog entry and the three named memories were
8
+ * never written, and the only way through was deleting the worktree by hand.
9
+ *
10
+ * These tests pin what replaces it:
11
+ * 1. A second run RESUMES: it performs the missing steps and reaches a full
12
+ * row table (acceptance rows 2 and 3).
13
+ * 2. It resumes only a worktree it can show belongs to this team, and a
14
+ * mismatch refuses naming both (change A, red-team Critical 3).
15
+ * 3. Two runs for one team cannot overlap (change A, red-team Major 4).
16
+ * 4. Two resumes fetch exactly one credential (change B, red-team Critical 1).
17
+ * 5. A standing memory this team owns asserts its row, and one whose seed
18
+ * differs reads `present, stale` (change B, finding 7).
19
+ * 6. A catalog entry is byte-identical after a resume (change B, finding 8).
20
+ * 7. `--recheck` writes nothing and states row 10's limitation (change D,
21
+ * finding 6).
22
+ * 8. Nothing between `createGitWorktree` and the pre-check calls
23
+ * `process.exit` (change C, red-team Critical 2).
24
+ */
25
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
26
+ import { existsSync, lstatSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync, } from 'fs';
27
+ import { join, dirname, relative, sep, isAbsolute } from 'path';
28
+ import { tmpdir } from 'os';
29
+ // ── Test-controlled state, declared before the factories that close over it ──
30
+ /** Which step, if any, the run under test is cut at. */
31
+ let failAfter = null;
32
+ /** Names that already resolve, with the content and codeContext they hold. */
33
+ const standingMemories = new Map();
34
+ /**
35
+ * Names that are held but cannot be read back (#478): `readNamedMemoryJson`
36
+ * answers `unknown`, and the create path's probe finds the name taken but
37
+ * returns no content. Both classify `could-not-run`.
38
+ */
39
+ const unreadableMemories = new Set();
40
+ /** How many times the stubbed credential service issued a token. */
41
+ let credentialFetches = 0;
42
+ /** The `serviceUrl` each call handed the credential path, in call order. */
43
+ let credentialServiceUrls = [];
44
+ /**
45
+ * What `resolveCoordinationUrl` answers, BY ROOT.
46
+ *
47
+ * Two answers, because the defect they pin is two resolvers disagreeing:
48
+ * `runCreate` resolves with `{ projectRoot }` and `obtainCredential` resolves
49
+ * with nothing, which derives a root from the current directory
50
+ * (`lib/coordination-client.ts:346-352`).
51
+ */
52
+ let urlFromProjectRoot = 'http://127.0.0.1:9';
53
+ const URL_FROM_CWD = 'https://coordination.example.invalid';
54
+ let credentialProjects = new Set(['mx-agent']);
55
+ let configuredProjectSlug = 'mx-agent';
56
+ let hasOrigin = false;
57
+ let mxAvailable = true;
58
+ vi.mock('../lib/config.js', () => ({
59
+ getConfigValue: () => undefined,
60
+ setConfigValue: () => undefined,
61
+ getConfigPath: () => '/nonexistent/config.json',
62
+ }));
63
+ /**
64
+ * The worktree the real command makes, including the `.git` file that tells a
65
+ * linked worktree from a directory. `findTeamWorktree` reads exactly that, so a
66
+ * mock without it would never produce a resume and every test here would pass
67
+ * against the old behaviour.
68
+ */
69
+ const createGitWorktree = vi.fn((worktreePath) => {
70
+ mkdirSync(worktreePath, { recursive: true });
71
+ writeFileSync(join(worktreePath, '.git'), 'gitdir: /nowhere\n');
72
+ });
73
+ vi.mock('../lib/worktree.js', async (importOriginal) => ({
74
+ // `findTeamWorktree` decides whether a run is a resume (#316). The REAL one:
75
+ // it reads `.git` off the candidate, and a stub that answered null would make
76
+ // every test here take the fresh-creation path whatever is on disk.
77
+ findTeamWorktree: (await importOriginal()).findTeamWorktree,
78
+ findProjectRoot: vi.fn(() => '/unused'),
79
+ assignSlot: vi.fn(() => 4),
80
+ getCurrentBranch: vi.fn(() => 'worktree/newteam-20260101'),
81
+ fetchOrigin: vi.fn(() => true),
82
+ createGitWorktree: (worktreePath, ..._rest) => createGitWorktree(worktreePath),
83
+ addToGitSafeDirectory: vi.fn(),
84
+ createHuskySymlink: vi.fn(),
85
+ generateBranchName: vi.fn((s) => `worktree/${s}-20260101`),
86
+ generateWorktreeDirName: vi.fn((s) => `${s}-20260101`),
87
+ listRemotes: vi.fn(() => (hasOrigin ? ['origin'] : [])),
88
+ findWorktreePath: vi.fn(() => null),
89
+ }));
90
+ /** Step 5, which is where #5's incident died. The fault point is right after it. */
91
+ const syncClaudeConfig = vi.fn();
92
+ vi.mock('../lib/claude.js', async (importOriginal) => {
93
+ const real = await importOriginal();
94
+ return {
95
+ ...real,
96
+ syncClaudeConfig: (...a) => syncClaudeConfig(...a),
97
+ deployClaudeMd: vi.fn(),
98
+ // The pointer line comes from the REAL builder, and the identity check reads
99
+ // it with the REAL reader (red-team round 2, finding 1). A hand-written copy
100
+ // here would pass while the shipped pair drifted apart.
101
+ writeClaudeLocal: vi.fn((opts) => {
102
+ const pointer = opts.behavioralOverride?.roleguideRelPath;
103
+ writeFileSync(join(opts.worktreePath, 'CLAUDE.local.md'), pointer
104
+ ? `# Team — Behavioral Checks (every-turn reinforcement)\n\n${real.behavioralPointerLine(pointer)}\n`
105
+ : '# no behavioral block\n');
106
+ return { written: true, path: join(opts.worktreePath, 'CLAUDE.local.md') };
107
+ }),
108
+ logSuccess: vi.fn(),
109
+ logWarning: vi.fn(),
110
+ logDim: vi.fn(),
111
+ };
112
+ });
113
+ vi.mock('../lib/catalog.js', async (importOriginal) => {
114
+ const real = await importOriginal();
115
+ return {
116
+ ...real,
117
+ catalogEntryOnOriginMain: vi.fn(() => 'present'),
118
+ // The REAL row-7 reader, wrapped so its arguments are recorded (#407 review
119
+ // round 1, red-team finding 2). Row 7's outcome is unchanged by the wrapper:
120
+ // these fixtures have no reachable remote, so the real function answers
121
+ // `unresolvable` here exactly as it did before. What the wrapper adds is the
122
+ // only evidence available about the path the CALL SITES compute, which no
123
+ // test asserted: the row tests supply that path by hand.
124
+ roleguideOnOriginMain: vi.fn(real.roleguideOnOriginMain),
125
+ listTeams: vi.fn(() => []),
126
+ };
127
+ });
128
+ vi.mock('../lib/roster.js', () => ({
129
+ rosterEntryOnRef: vi.fn(() => 'present'),
130
+ rosterSourceHasSlug: vi.fn(() => 'absent'),
131
+ }));
132
+ vi.mock('../lib/vault.js', () => ({
133
+ vaultTokenPresent: vi.fn(() => 'present'),
134
+ VAULT_NAME: 'mx-dev-eastus2-kv-001',
135
+ }));
136
+ /**
137
+ * The REAL credential path with a stubbed service.
138
+ *
139
+ * Only the HTTP fetch is faked. The cache read, the born-0600 write and the
140
+ * pre-mint check are the shipped code, which is what makes "two resumes, one
141
+ * fetch" a statement about the product rather than about this file.
142
+ */
143
+ vi.mock('../lib/coordination-token.js', async (importOriginal) => {
144
+ const real = await importOriginal();
145
+ return {
146
+ ...real,
147
+ usesCredentialEndpoint: (project) => credentialProjects.has(project),
148
+ provisionCredentialForWorktree: vi.fn((i) => {
149
+ // WHAT THE COMMAND PASSED, recorded before the stub overrides it so the
150
+ // fetcher below is reachable. The assertion is about the argument, not
151
+ // about where this fixture then sends the request.
152
+ credentialServiceUrls.push(i.serviceUrl);
153
+ return real.provisionCredentialForWorktree({
154
+ ...i,
155
+ serviceUrl: 'http://127.0.0.1:9',
156
+ readUserKey: () => 'fake-user-key-for-tests-only',
157
+ fetchCredential: async () => {
158
+ credentialFetches += 1;
159
+ return { status: 'issued', token: `stub-token-${credentialFetches}` };
160
+ },
161
+ });
162
+ }),
163
+ };
164
+ });
165
+ vi.mock('../lib/coordination-client.js', async (importOriginal) => ({
166
+ ...(await importOriginal()),
167
+ // ROOT-AWARE, the way the real resolver is. A caller that passes a root gets
168
+ // that project's URL; a caller that passes none gets whatever the current
169
+ // directory implies, which is a different repository's answer.
170
+ resolveCoordinationUrl: vi.fn((opts) => (opts?.projectRoot
171
+ ? { url: urlFromProjectRoot, source: 'project' }
172
+ : { url: URL_FROM_CWD, source: 'project' })),
173
+ projectUrlValidationError: vi.fn(() => undefined),
174
+ }));
175
+ /** What `mx-agent-system/cli` looks like to the build stage: absent, so row 14 is not required. */
176
+ vi.mock('../lib/cli-build.js', () => ({
177
+ buildCliInWorktree: vi.fn(() => ({
178
+ kind: 'not-applicable',
179
+ detail: 'no mx-agent-system/cli/package.json in this worktree (this project installs the published CLI)',
180
+ })),
181
+ probeBuiltCli: vi.fn(() => ({
182
+ kind: 'not-applicable',
183
+ detail: 'no mx-agent-system/cli/package.json in this worktree (this project installs the published CLI)',
184
+ })),
185
+ REBUILD_REMEDY: 'npm ci && npm run build',
186
+ }));
187
+ /**
188
+ * The memory boundary, modelling the two rules the real module states: a create
189
+ * over a taken name is refused (`lib/memory.ts:948-996`), and the probe reports
190
+ * whose the standing memory is from its own codeContext (`:960-967`).
191
+ */
192
+ vi.mock('../lib/memory.js', async (importOriginal) => {
193
+ const real = await importOriginal();
194
+ return {
195
+ ...real,
196
+ isMxAvailable: vi.fn(() => mxAvailable),
197
+ namedMemoryResolvesById: vi.fn(() => ({ ok: true, detail: '' })),
198
+ namedMemoryExists: vi.fn((name) => standingMemories.has(name) ? { ok: true, detail: '' } : { ok: false, detail: 'mx returned no such memory' }),
199
+ readNamedMemoryJson: vi.fn((name) => {
200
+ if (unreadableMemories.has(name)) {
201
+ return { status: 'unknown', content: '', reason: 'mx timed out', exitCode: null };
202
+ }
203
+ const held = standingMemories.get(name);
204
+ return held
205
+ ? { status: 'present', content: held.content, body: { name, codeContext: held.codeContext }, exitCode: 0 }
206
+ : { status: 'absent', content: '', exitCode: 1 };
207
+ }),
208
+ logMemoryResult: vi.fn(),
209
+ logManualMemoryCommands: vi.fn(),
210
+ bootstrapTeamMemories: vi.fn((slug, displayName, rg, projectSlug, opts) => {
211
+ const specs = real.teamMemorySpecs(slug, displayName, rg, projectSlug, opts);
212
+ const seed = (idx) => {
213
+ const spec = specs[idx];
214
+ const held = standingMemories.get(spec.name);
215
+ if (held) {
216
+ const ctx = held.codeContext;
217
+ const ownership = !ctx || typeof ctx.team !== 'string'
218
+ ? 'unconfirmed'
219
+ : projectSlug !== '' && typeof ctx.product !== 'string'
220
+ ? 'unconfirmed'
221
+ : ctx.team === slug && (projectSlug === '' || ctx.product === projectSlug)
222
+ ? 'this-team'
223
+ : 'not-this-team';
224
+ return {
225
+ ok: false,
226
+ output: 'name already taken',
227
+ id: null,
228
+ conversationId: null,
229
+ preExisting: true,
230
+ preExistingOwnership: ownership,
231
+ probeConclusive: true,
232
+ preExistingRead: unreadableMemories.has(spec.name)
233
+ ? undefined
234
+ : { content: held.content, codeContext: held.codeContext },
235
+ };
236
+ }
237
+ standingMemories.set(spec.name, { content: spec.content, codeContext: spec.codeContext });
238
+ return {
239
+ ok: true,
240
+ output: '',
241
+ id: `id-of-${spec.name}`,
242
+ conversationId: 'conv_testfixture',
243
+ preExisting: false,
244
+ probeConclusive: true,
245
+ };
246
+ };
247
+ const leaderState = seed(0);
248
+ const iterationLog = seed(1);
249
+ const knownIssues = seed(2);
250
+ return {
251
+ leaderState,
252
+ iterationLog,
253
+ knownIssues,
254
+ extras: [],
255
+ conversationThreaded: true,
256
+ conversationId: 'conv_testfixture',
257
+ conversationOutcome: 'threaded-by-this-run',
258
+ };
259
+ }),
260
+ };
261
+ });
262
+ vi.mock('../lib/project-config.js', async (importOriginal) => ({
263
+ ...(await importOriginal()),
264
+ loadProjectConfig: vi.fn((root) => ({ __root: root })),
265
+ resolveProjectConfig: vi.fn(() => ({
266
+ worktreeDir: '.worktrees',
267
+ baseBranch: 'main',
268
+ configSource: 'mx-agent-system/agent-config',
269
+ teamsDir: 'mx-agent-system/teams',
270
+ roleguidesDir: 'mx-agent-system/roleguides',
271
+ projectSlug: configuredProjectSlug,
272
+ coordinationServiceUrl: '',
273
+ })),
274
+ }));
275
+ vi.mock('../lib/config-generation.js', () => ({ checkConfigGeneration: vi.fn() }));
276
+ import { runCreate, CompletionCheckError, ResumeIdentityError, memoryStateHolds, __testing } from '../commands/create.js';
277
+ import { roleguideOnOriginMain } from '../lib/catalog.js';
278
+ import { BEHAVIORAL_START_MARKER, BEHAVIORAL_END_MARKER } from '../lib/behavioral-injection.js';
279
+ const { checkResumeIdentity, memoryPresenceState, claimProvisionLock, provisionLockPath } = __testing;
280
+ const RG = 'mx-agent-system/roleguides/newteam-leader.md';
281
+ const WORKTREE_REL = '.worktrees/newteam-20260101';
282
+ const MEMORY_NAMES = [
283
+ 'mx-agent-newteam-leader-state',
284
+ 'mx-agent-newteam-iteration-log',
285
+ 'mx-agent-newteam-known-issues',
286
+ ];
287
+ function roleguideText(slug, projectSlug) {
288
+ const prefix = projectSlug ? `${projectSlug}-${slug}` : slug;
289
+ return [
290
+ `# ${slug} Leader Roleguide`,
291
+ '',
292
+ BEHAVIORAL_START_MARKER,
293
+ '## Decision Authority',
294
+ '',
295
+ '- Ship without asking when the data is clear.',
296
+ BEHAVIORAL_END_MARKER,
297
+ '',
298
+ '## Named Memory Anchors',
299
+ '',
300
+ '| Name | Content | Updated when |',
301
+ '|---|---|---|',
302
+ `| \`${prefix}-leader-state\` | State | Every change |`,
303
+ `| \`${prefix}-iteration-log\` | Log | At iteration close |`,
304
+ `| \`${prefix}-known-issues\` | Issues | When found |`,
305
+ ].join('\n');
306
+ }
307
+ let root;
308
+ let stdout;
309
+ let stderr;
310
+ class ExitCalled extends Error {
311
+ code;
312
+ constructor(code) {
313
+ super(`process.exit(${code})`);
314
+ this.code = code;
315
+ }
316
+ }
317
+ beforeEach(() => {
318
+ root = mkdtempSync(join(tmpdir(), 'mx-provision-resume-'));
319
+ failAfter = null;
320
+ standingMemories.clear();
321
+ unreadableMemories.clear();
322
+ credentialFetches = 0;
323
+ credentialServiceUrls = [];
324
+ urlFromProjectRoot = 'http://127.0.0.1:9';
325
+ credentialProjects = new Set(['mx-agent']);
326
+ configuredProjectSlug = 'mx-agent';
327
+ hasOrigin = false;
328
+ mxAvailable = true;
329
+ stdout = [];
330
+ stderr = [];
331
+ delete process.env.MX_PROVISION_FAIL_AFTER;
332
+ delete process.env.MX_PROVISION_FAULT_INJECTION;
333
+ vi.clearAllMocks();
334
+ vi.spyOn(console, 'log').mockImplementation((...a) => { stdout.push(a.map(String).join(' ')); });
335
+ vi.spyOn(console, 'error').mockImplementation((...a) => { stderr.push(a.map(String).join(' ')); });
336
+ vi.spyOn(process, 'exit').mockImplementation(((code) => {
337
+ throw new ExitCalled(code ?? 0);
338
+ }));
339
+ });
340
+ afterEach(() => {
341
+ rmSync(root, { recursive: true, force: true });
342
+ delete process.env.MX_PROVISION_FAIL_AFTER;
343
+ delete process.env.MX_PROVISION_FAULT_INJECTION;
344
+ vi.restoreAllMocks();
345
+ });
346
+ /** Write the roleguide this project's team is provisioned from. */
347
+ function writeRoleguide(name = RG, slug = 'newteam') {
348
+ const abs = join(root, name);
349
+ mkdirSync(dirname(abs), { recursive: true });
350
+ writeFileSync(abs, roleguideText(slug, configuredProjectSlug));
351
+ }
352
+ /**
353
+ * Run `mx-agent provision`, cut at `failAfter` when one is set.
354
+ *
355
+ * The fault is injected through the shipped mechanism — the environment
356
+ * variable, honoured because vitest sets `VITEST` — rather than by patching the
357
+ * module, so the recipe in the pull-request body is the one under test here.
358
+ */
359
+ async function provision(opts = {}) {
360
+ if (failAfter) {
361
+ process.env.MX_PROVISION_FAIL_AFTER = failAfter;
362
+ // The second switch (red-team round 2, finding 5). A test build alone no
363
+ // longer injects, so the fixture arms both exactly as the recipe does.
364
+ process.env.MX_PROVISION_FAULT_INJECTION = '1';
365
+ }
366
+ else {
367
+ delete process.env.MX_PROVISION_FAIL_AFTER;
368
+ delete process.env.MX_PROVISION_FAULT_INJECTION;
369
+ }
370
+ try {
371
+ await runCreate({
372
+ roleguide: opts.roleguide ?? (opts.recheck ? undefined : RG),
373
+ name: opts.name ?? 'newteam',
374
+ projectRoot: root,
375
+ recheck: opts.recheck,
376
+ });
377
+ return { failure: null };
378
+ }
379
+ catch (err) {
380
+ if (err instanceof ExitCalled)
381
+ throw new Error(`unexpected process.exit(${err.code})`);
382
+ return { failure: err };
383
+ }
384
+ }
385
+ /** Every printed `row N:` line, in order. */
386
+ function rowLines() {
387
+ return stdout.filter((l) => /^\s*row [\d]/.test(l));
388
+ }
389
+ /** Every file under `dir`, with its bytes, as one comparable snapshot. */
390
+ function snapshot(dir) {
391
+ const out = new Map();
392
+ const walk = (d) => {
393
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
394
+ const p = join(d, entry.name);
395
+ if (entry.isDirectory())
396
+ walk(p);
397
+ else
398
+ out.set(relative(dir, p), readFileSync(p, 'utf-8'));
399
+ }
400
+ };
401
+ walk(dir);
402
+ return out;
403
+ }
404
+ // ── The reproduction, and what a second run now does ─────────────────────────
405
+ describe('a run interrupted after the worktree resumes to a full row table (#5)', () => {
406
+ it('run 1 leaves a worktree and no memories; run 2 finishes it', async () => {
407
+ writeRoleguide();
408
+ failAfter = 'worktree';
409
+ const first = await provision();
410
+ // The #5 state: a worktree, and nothing after it.
411
+ expect(first.failure).toBeInstanceOf(CompletionCheckError);
412
+ expect(existsSync(join(root, WORKTREE_REL))).toBe(true);
413
+ expect(standingMemories.size).toBe(0);
414
+ expect(existsSync(join(root, 'mx-agent-system/teams/newteam.md'))).toBe(false);
415
+ // What the old code did NOT print: the row table.
416
+ expect(rowLines()).toHaveLength(16);
417
+ expect(first.failure.message).toContain('worktree');
418
+ expect(first.failure.message).toContain('--recheck');
419
+ stdout = [];
420
+ failAfter = null;
421
+ const second = await provision();
422
+ expect(second.failure).toBeNull();
423
+ expect(rowLines()).toHaveLength(16);
424
+ for (const n of [0, 1, 2, 3, 4, 5]) {
425
+ expect(rowLines()[n]).toMatch(/row \d+: asserted/);
426
+ }
427
+ expect(standingMemories.size).toBe(3);
428
+ expect(existsSync(join(root, 'mx-agent-system/teams/newteam.md'))).toBe(true);
429
+ expect(stdout.join('\n')).toContain('Team Created!');
430
+ });
431
+ it('says it is resuming, and does not create a second worktree', async () => {
432
+ writeRoleguide();
433
+ failAfter = 'claude-config';
434
+ await provision();
435
+ const before = readdirSync(join(root, '.worktrees')).filter((e) => !e.endsWith('.lock'));
436
+ stdout = [];
437
+ failAfter = null;
438
+ const second = await provision();
439
+ expect(second.failure).toBeNull();
440
+ expect(stdout.join('\n')).toContain('Resuming the provisioning of newteam');
441
+ expect(readdirSync(join(root, '.worktrees')).filter((e) => !e.endsWith('.lock'))).toEqual(before);
442
+ expect(createGitWorktree).toHaveBeenCalledTimes(1);
443
+ });
444
+ it('leaves no provision lock behind on a failed run', async () => {
445
+ writeRoleguide();
446
+ failAfter = 'memories';
447
+ await provision();
448
+ expect(existsSync(provisionLockPath(join(root, WORKTREE_REL)))).toBe(false);
449
+ });
450
+ });
451
+ // ── Change A: the identity check ─────────────────────────────────────────────
452
+ describe('the resume identity check refuses a worktree this run does not own', () => {
453
+ it('refuses when the worktree names another team, and prints both names', async () => {
454
+ writeRoleguide();
455
+ failAfter = 'claude-config';
456
+ await provision();
457
+ // Another team's scope file at the same path: the state a slug collision or a
458
+ // recycled directory produces.
459
+ writeFileSync(join(root, WORKTREE_REL, '.mx-code-context.json'), JSON.stringify({ product: 'mx-agent', service: 'team-provisioning', team: 'otherteam', role: 'team-lead' }));
460
+ stdout = [];
461
+ failAfter = null;
462
+ const second = await provision();
463
+ expect(second.failure).toBeInstanceOf(ResumeIdentityError);
464
+ expect(second.failure.message).toContain('otherteam');
465
+ expect(second.failure.message).toContain('newteam');
466
+ // NO WRITE on a mismatch.
467
+ expect(standingMemories.size).toBe(0);
468
+ expect(existsSync(join(root, 'mx-agent-system/teams/newteam.md'))).toBe(false);
469
+ expect(existsSync(provisionLockPath(join(root, WORKTREE_REL)))).toBe(false);
470
+ });
471
+ it('refuses the same --name provisioned from a different roleguide, naming both', async () => {
472
+ writeRoleguide();
473
+ // Cut AFTER step 6: `CLAUDE.local.md` is what records which roleguide the
474
+ // worktree was provisioned from, and a run cut before it leaves a worktree
475
+ // that names nothing, which is `unestablished` rather than a mismatch.
476
+ failAfter = 'memories';
477
+ await provision();
478
+ const other = 'mx-agent-system/roleguides/newteam-rewrite.md';
479
+ mkdirSync(dirname(join(root, other)), { recursive: true });
480
+ writeFileSync(join(root, other), roleguideText('newteam', configuredProjectSlug));
481
+ stdout = [];
482
+ failAfter = null;
483
+ const seededByRunOne = new Map(standingMemories);
484
+ const second = await provision({ roleguide: other });
485
+ expect(second.failure).toBeInstanceOf(ResumeIdentityError);
486
+ expect(second.failure.message).toContain('newteam-leader.md');
487
+ expect(second.failure.message).toContain('newteam-rewrite.md');
488
+ // NO WRITE on a mismatch: what run 1 left is exactly what is there.
489
+ expect(standingMemories).toEqual(seededByRunOne);
490
+ expect(existsSync(join(root, 'mx-agent-system/teams/newteam.md'))).toBe(false);
491
+ });
492
+ it('resumes a worktree whose scope file names this team', async () => {
493
+ writeRoleguide();
494
+ failAfter = 'memories';
495
+ await provision();
496
+ expect(JSON.parse(readFileSync(join(root, WORKTREE_REL, '.mx-code-context.json'), 'utf-8')).team).toBe('newteam');
497
+ stdout = [];
498
+ failAfter = null;
499
+ const second = await provision();
500
+ expect(second.failure).toBeNull();
501
+ expect(stdout.join('\n')).toContain('names team "newteam"');
502
+ });
503
+ // The verdict function itself, so each branch is pinned without a fixture.
504
+ it('reads three verdicts, not two', () => {
505
+ expect(checkResumeIdentity({
506
+ worktree: { team: null, product: null, roleguide: null },
507
+ runTeam: 'a', runProduct: 'p', runRoleguide: 'x.md',
508
+ }).kind).toBe('unestablished');
509
+ expect(checkResumeIdentity({
510
+ worktree: { team: 'a', product: 'p', roleguide: 'dir/x.md' },
511
+ runTeam: 'a', runProduct: 'p', runRoleguide: './dir/x.md',
512
+ }).kind).toBe('match');
513
+ expect(checkResumeIdentity({
514
+ worktree: { team: 'a', product: 'other', roleguide: null },
515
+ runTeam: 'a', runProduct: 'p', runRoleguide: null,
516
+ }).kind).toBe('mismatch');
517
+ // A project that configures no slug has no identity to compare against.
518
+ expect(checkResumeIdentity({
519
+ worktree: { team: 'a', product: 'anything', roleguide: null },
520
+ runTeam: 'a', runProduct: '', runRoleguide: null,
521
+ }).kind).toBe('match');
522
+ });
523
+ });
524
+ // ── Change A: the provision lock ─────────────────────────────────────────────
525
+ describe('the provision lock refuses a concurrent run', () => {
526
+ it('refuses while another live run holds it, and writes nothing', async () => {
527
+ writeRoleguide();
528
+ mkdirSync(join(root, WORKTREE_REL), { recursive: true });
529
+ writeFileSync(join(root, WORKTREE_REL, '.git'), 'gitdir: /nowhere\n');
530
+ // A lock recorded by a process that IS live: this one. It names this run's
531
+ // team AND worktree, which is what makes it a run to wait for.
532
+ writeFileSync(provisionLockPath(join(root, WORKTREE_REL)), JSON.stringify({
533
+ team: 'newteam',
534
+ worktreePath: join(root, WORKTREE_REL),
535
+ pid: process.pid,
536
+ startedAt: new Date().toISOString(),
537
+ }));
538
+ const { failure } = await provision();
539
+ expect(failure).toBeTruthy();
540
+ expect(failure.message).toContain('another provisioning run holds');
541
+ expect(failure.message).toContain(String(process.pid));
542
+ expect(standingMemories.size).toBe(0);
543
+ });
544
+ it('clears a lock whose owner is gone, rather than refusing for ever', () => {
545
+ const worktree = join(root, WORKTREE_REL);
546
+ mkdirSync(worktree, { recursive: true });
547
+ // 2^22 is above every Linux pid_max default, so no process holds it.
548
+ writeFileSync(provisionLockPath(worktree), JSON.stringify({
549
+ team: 'newteam',
550
+ worktreePath: worktree,
551
+ pid: 4194304,
552
+ startedAt: new Date().toISOString(),
553
+ }));
554
+ const claim = claimProvisionLock(worktree, 'newteam');
555
+ expect(claim.ok).toBe(true);
556
+ if (claim.ok)
557
+ claim.release();
558
+ expect(existsSync(provisionLockPath(worktree))).toBe(false);
559
+ });
560
+ it('is exclusive: the second claim of one path fails while the first is held', () => {
561
+ const worktree = join(root, WORKTREE_REL);
562
+ mkdirSync(worktree, { recursive: true });
563
+ const first = claimProvisionLock(worktree, 'newteam');
564
+ const second = claimProvisionLock(worktree, 'newteam');
565
+ expect(first.ok).toBe(true);
566
+ expect(second.ok).toBe(false);
567
+ if (first.ok)
568
+ first.release();
569
+ });
570
+ it('ages out a live pid rather than honouring it for ever', () => {
571
+ // Security review round 2, Should Fix 4. pid 1 always exists and answers
572
+ // EPERM, so it reads as live; the previous order returned on that before any
573
+ // age was computed, and aging ran only when the pid was UNREADABLE. A record
574
+ // naming pid 1 therefore refused every later run for this team for ever.
575
+ const worktree = join(root, WORKTREE_REL);
576
+ mkdirSync(worktree, { recursive: true });
577
+ const lock = provisionLockPath(worktree);
578
+ writeFileSync(lock, JSON.stringify({
579
+ team: 'newteam',
580
+ worktreePath: worktree,
581
+ pid: 1,
582
+ startedAt: new Date(Date.now() - 7 * 60 * 60 * 1000).toISOString(),
583
+ }));
584
+ // Older than the six-hour limit, set on the file itself: the age is read
585
+ // from the filesystem, never from the record's own claim about its start.
586
+ const old = new Date(Date.now() - 7 * 60 * 60 * 1000);
587
+ utimesSync(lock, old, old);
588
+ const claim = claimProvisionLock(worktree, 'newteam');
589
+ expect(claim.ok).toBe(true);
590
+ if (claim.ok)
591
+ claim.release();
592
+ });
593
+ it('honours a fresh lock naming pid 1, so aging is the only thing that clears it', () => {
594
+ const worktree = join(root, WORKTREE_REL);
595
+ mkdirSync(worktree, { recursive: true });
596
+ writeFileSync(provisionLockPath(worktree), JSON.stringify({
597
+ team: 'newteam',
598
+ worktreePath: worktree,
599
+ pid: 1,
600
+ startedAt: new Date().toISOString(),
601
+ }));
602
+ const claim = claimProvisionLock(worktree, 'newteam');
603
+ expect(claim.ok).toBe(false);
604
+ if (!claim.ok)
605
+ expect(claim.detail).toContain('pid 1');
606
+ });
607
+ it('clears a lock that records another team, rather than waiting for it', () => {
608
+ const worktree = join(root, WORKTREE_REL);
609
+ mkdirSync(worktree, { recursive: true });
610
+ writeFileSync(provisionLockPath(worktree), JSON.stringify({
611
+ team: 'someone-else',
612
+ worktreePath: '/somewhere/else',
613
+ pid: process.pid,
614
+ startedAt: new Date().toISOString(),
615
+ }));
616
+ const claim = claimProvisionLock(worktree, 'newteam');
617
+ expect(claim.ok).toBe(true);
618
+ if (claim.ok)
619
+ claim.release();
620
+ });
621
+ it('does not read a symlink planted at the lock path', () => {
622
+ // Red-team round 2, finding 2. The create and the release were already safe;
623
+ // the READ was not, so a link would have supplied the record and the mtime
624
+ // this decision rests on.
625
+ const worktree = join(root, WORKTREE_REL);
626
+ mkdirSync(worktree, { recursive: true });
627
+ const target = join(root, 'planted-lock-target');
628
+ writeFileSync(target, JSON.stringify({
629
+ team: 'newteam',
630
+ worktreePath: worktree,
631
+ pid: process.pid,
632
+ startedAt: new Date().toISOString(),
633
+ }));
634
+ symlinkSync(target, provisionLockPath(worktree));
635
+ const claim = claimProvisionLock(worktree, 'newteam');
636
+ // Taken, not refused: a link records no run to wait for.
637
+ expect(claim.ok).toBe(true);
638
+ expect(lstatSync(provisionLockPath(worktree)).isSymbolicLink()).toBe(false);
639
+ // The file the link pointed at is untouched.
640
+ expect(JSON.parse(readFileSync(target, 'utf-8')).team).toBe('newteam');
641
+ if (claim.ok)
642
+ claim.release();
643
+ });
644
+ it('releases the lock on a clean run', async () => {
645
+ writeRoleguide();
646
+ const { failure } = await provision();
647
+ expect(failure).toBeNull();
648
+ expect(existsSync(provisionLockPath(join(root, WORKTREE_REL)))).toBe(false);
649
+ });
650
+ });
651
+ // ── Change B: one credential across two resumes ──────────────────────────────
652
+ describe('row 10 mints once, however many times the run resumes', () => {
653
+ it('two resumes against a stubbed service fetch exactly one credential', async () => {
654
+ writeRoleguide();
655
+ failAfter = 'memories';
656
+ await provision();
657
+ expect(credentialFetches).toBe(0); // the run never reached row 10
658
+ failAfter = null;
659
+ await provision();
660
+ expect(credentialFetches).toBe(1);
661
+ stdout = [];
662
+ await provision();
663
+ expect(credentialFetches).toBe(1);
664
+ expect(rowLines()[10]).toMatch(/row 10: asserted/);
665
+ // WHAT WAS READ, not who wrote it (security review round 2, Should Fix 1).
666
+ expect(rowLines()[10]).toContain('a file is present at');
667
+ expect(rowLines()[10]).toContain('mode 0600');
668
+ expect(rowLines()[10]).toContain('did not check who wrote it');
669
+ // One cache file, holding what the first fetch wrote.
670
+ const cache = join(root, WORKTREE_REL, '.mx-coordination-token--mx-agent--newteam');
671
+ expect(readFileSync(cache, 'utf-8')).toBe('stub-token-1');
672
+ expect(statSync(cache).mode & 0o777).toBe(0o600);
673
+ });
674
+ });
675
+ // ── Change B: standing memories, and finding 7's `present, stale` ────────────
676
+ describe('a standing memory this team owns asserts its row', () => {
677
+ it('asserts rows 3 to 5 on a resume that finds the three already seeded', async () => {
678
+ writeRoleguide();
679
+ failAfter = 'catalog';
680
+ await provision();
681
+ expect(standingMemories.size).toBe(3);
682
+ stdout = [];
683
+ failAfter = null;
684
+ const second = await provision();
685
+ expect(second.failure).toBeNull();
686
+ for (const n of [3, 4, 5])
687
+ expect(rowLines()[n]).toMatch(/row \d: asserted/);
688
+ expect(rowLines()[3]).toContain('seeded by an earlier run of this team');
689
+ });
690
+ it('prints no memory warning and no manual commands on that same resume (#471)', async () => {
691
+ // THE DEFECT, in one run: rows 3 to 5 asserted, and the same run told the
692
+ // operator the three memories had failed to initialise and handed over three
693
+ // `mx memories create --name` commands. Those commands UPSERT
694
+ // (memnexus#5485), so an operator who followed the instruction the command
695
+ // had just given them replaced the three memories the rows had just verified.
696
+ writeRoleguide();
697
+ failAfter = 'catalog';
698
+ await provision();
699
+ expect(standingMemories.size).toBe(3);
700
+ const { logWarning } = await import('../lib/claude.js');
701
+ const { logManualMemoryCommands } = await import('../lib/memory.js');
702
+ // Run 1's calls are not run 2's evidence.
703
+ vi.mocked(logWarning).mockClear();
704
+ vi.mocked(logManualMemoryCommands).mockClear();
705
+ stdout = [];
706
+ failAfter = null;
707
+ const second = await provision();
708
+ expect(second.failure).toBeNull();
709
+ for (const n of [3, 4, 5])
710
+ expect(rowLines()[n]).toMatch(/row \d: asserted/);
711
+ const warnings = vi.mocked(logWarning).mock.calls.map((c) => String(c[0]));
712
+ expect(warnings.filter((w) => /memor/i.test(w))).toEqual([]);
713
+ expect(vi.mocked(logManualMemoryCommands)).not.toHaveBeenCalled();
714
+ // The DoD checklist line reads the same flag, so it agrees with the rows too.
715
+ expect(stdout.join('\n')).toContain('[✓] Named memories');
716
+ expect(stdout.join('\n')).not.toContain('create manually');
717
+ });
718
+ it('still warns, but prints NO create command, when a standing memory is another team\'s (#471, #493)', async () => {
719
+ // The other half of the #471 fix. A name held by a memory this team does not
720
+ // own is not "present and usable": row 4 stays red, and the warning has to
721
+ // stay with it. A fix that suppressed the warning whenever a name was taken
722
+ // would silence exactly this run.
723
+ //
724
+ // This test used to require the manual create commands here too. #493 (plan
725
+ // #494 amendment 1) removes them: `mx memories create --name` is an upsert,
726
+ // so the command overwrote the other team's memory. The warning stays; the
727
+ // command does not.
728
+ writeRoleguide();
729
+ failAfter = 'catalog';
730
+ await provision();
731
+ const held = standingMemories.get(MEMORY_NAMES[1]);
732
+ standingMemories.set(MEMORY_NAMES[1], {
733
+ ...held,
734
+ codeContext: { product: 'mx-agent', service: 'team-provisioning', team: 'someone-else', role: 'team-lead' },
735
+ });
736
+ const { logWarning } = await import('../lib/claude.js');
737
+ const { logManualMemoryCommands } = await import('../lib/memory.js');
738
+ vi.mocked(logWarning).mockClear();
739
+ vi.mocked(logManualMemoryCommands).mockClear();
740
+ stdout = [];
741
+ failAfter = null;
742
+ const second = await provision();
743
+ expect(second.failure).toBeInstanceOf(CompletionCheckError);
744
+ expect(rowLines()[4]).toMatch(/row 4: not asserted/);
745
+ const warnings = vi.mocked(logWarning).mock.calls.map((c) => String(c[0]));
746
+ expect(warnings.some((w) => w.includes('Some team memories are not there'))).toBe(true);
747
+ expect(warnings.some((w) => w.includes('Create them manually'))).toBe(false);
748
+ expect(vi.mocked(logManualMemoryCommands)).not.toHaveBeenCalled();
749
+ });
750
+ it('reads `present, stale` when the seed differs from what this run would write', async () => {
751
+ writeRoleguide();
752
+ failAfter = 'catalog';
753
+ await provision();
754
+ // The Linkage line names another catalog entry: the shape a team whose
755
+ // catalog path changed between the two runs leaves behind.
756
+ const held = standingMemories.get(MEMORY_NAMES[0]);
757
+ standingMemories.set(MEMORY_NAMES[0], {
758
+ ...held,
759
+ content: held.content.replace(/- Linkage: .*/, '- Linkage: mx-agent-system/teams/old.md, old.md'),
760
+ });
761
+ stdout = [];
762
+ failAfter = null;
763
+ const second = await provision();
764
+ expect(second.failure).toBeNull();
765
+ expect(rowLines()[3]).toContain('present, stale');
766
+ expect(rowLines()[3]).toContain('Linkage');
767
+ // ASSERTED, and told apart from a row this run wrote (#316 review round 2,
768
+ // red-team finding 3). The verdict word is its own, and a line above the
769
+ // table names the row, because a yellow verdict fifteen rows down on a run
770
+ // that exits 0 is easy to read past.
771
+ expect(rowLines()[3]).toMatch(/row 3: asserted, stale/);
772
+ expect(rowLines()[3]).not.toContain('asserted (shape)');
773
+ expect(stdout.join('\n')).toContain('1 row present but stale: row 3');
774
+ expect(stdout.join('\n')).toContain('nothing was overwritten');
775
+ });
776
+ it('names every stale row in the summary line, memories and catalog together', async () => {
777
+ writeRoleguide();
778
+ failAfter = 'catalog';
779
+ await provision();
780
+ const held = standingMemories.get(MEMORY_NAMES[0]);
781
+ standingMemories.set(MEMORY_NAMES[0], {
782
+ ...held,
783
+ content: held.content.replace(/- Linkage: .*/, '- Linkage: teams/old.md, old.md'),
784
+ });
785
+ // The catalog entry gets the same comparison as the memories, instead of an
786
+ // existence check that reads identical for an entry nobody wrote this run.
787
+ const entry = join(root, 'mx-agent-system/teams/newteam.md');
788
+ writeFileSync(entry, `${readFileSync(entry, 'utf-8')}\n## Goal\n\nEdited by a person.\n`);
789
+ stdout = [];
790
+ failAfter = null;
791
+ const second = await provision();
792
+ expect(second.failure).toBeNull();
793
+ expect(rowLines()[2]).toMatch(/row 2: asserted, stale/);
794
+ expect(rowLines()[2]).toContain('differs from what this run would write');
795
+ expect(stdout.join('\n')).toContain('2 rows present but stale: row 2, row 3');
796
+ });
797
+ it('leaves row 2 green when the entry is what this run would write', async () => {
798
+ writeRoleguide();
799
+ failAfter = 'catalog';
800
+ await provision();
801
+ stdout = [];
802
+ failAfter = null;
803
+ const second = await provision();
804
+ expect(second.failure).toBeNull();
805
+ expect(rowLines()[2]).toMatch(/row 2: asserted /);
806
+ expect(rowLines()[2]).not.toContain('stale');
807
+ });
808
+ it('keeps a memory that belongs to another team red, on a resume as on a first run', async () => {
809
+ writeRoleguide();
810
+ failAfter = 'catalog';
811
+ await provision();
812
+ const held = standingMemories.get(MEMORY_NAMES[1]);
813
+ standingMemories.set(MEMORY_NAMES[1], {
814
+ ...held,
815
+ codeContext: { product: 'mx-agent', service: 'team-provisioning', team: 'someone-else', role: 'team-lead' },
816
+ });
817
+ stdout = [];
818
+ failAfter = null;
819
+ const second = await provision();
820
+ expect(second.failure).toBeInstanceOf(CompletionCheckError);
821
+ expect(rowLines()[4]).toMatch(/row 4: not asserted/);
822
+ expect(rowLines()[4]).toContain('another team');
823
+ });
824
+ it('holds for the two present states and for no other one (#471)', () => {
825
+ // WHAT THE PREDICATE EXCLUDES, pinned. `memoryStateHolds` gates rows 3 to 5
826
+ // and, since #471, the `memoriesOk` flag behind the warning and the DoD
827
+ // checklist line. Nothing failed when the predicate was widened to accept
828
+ // `malformed` and `could-not-run`: a security review mutated it to
829
+ // `presence !== 'not-this-team'` and the whole suite still passed, which this
830
+ // lead reproduced before adding this test.
831
+ //
832
+ // What that widening would print is the defect #471 fixes, pointing the other
833
+ // way. `create.ts:3619` reads `!row.asserted && row.couldNotRun === true`, so
834
+ // an asserted row never reaches the could-not-run branch, and a memory nobody
835
+ // could read would print a green row and a green `[✓] Named memories` line.
836
+ //
837
+ // ASSERTED ON THE PREDICATE, not on a rendered row, so it stays true if the
838
+ // printer changes. `Record<MemoryPresence, boolean>` is exhaustive at compile
839
+ // time: a sixth state added to the union fails `tsc` here until someone says
840
+ // which way it goes.
841
+ const expected = {
842
+ present: true,
843
+ 'present-stale': true,
844
+ 'not-this-team': false,
845
+ malformed: false,
846
+ 'could-not-run': false,
847
+ };
848
+ for (const [presence, holds] of Object.entries(expected)) {
849
+ expect([presence, memoryStateHolds(presence)]).toEqual([presence, holds]);
850
+ }
851
+ });
852
+ // ── The row builder's CALL to the predicate, pinned through rendered rows (#478) ──
853
+ //
854
+ // The test above pins `memoryStateHolds`. It does not pin that the row builder
855
+ // still asks it: a security review replaced the call at `create.ts:2867` with
856
+ // `standing.presence !== 'not-this-team'`, left the predicate correct, and the
857
+ // whole suite passed (#478). Under that edit a `malformed` or `could-not-run`
858
+ // memory prints an asserted row, because the printer reads
859
+ // `!row.asserted && row.couldNotRun === true` and an asserted row never reaches
860
+ // the could-not-run branch.
861
+ //
862
+ // These drive the `standing` branch through `runCreate` and assert the PRINTED
863
+ // row, so the edit above fails here. The two states render differently, and
864
+ // each is pinned to its own word: `could-not-run` prints `could not run`, and
865
+ // `malformed` prints `not asserted`, which is what the fresh-creation path
866
+ // prints for a malformed leftover too. Neither prints `asserted`.
867
+ it('prints a malformed standing memory not asserted on a resume, never asserted (#478)', async () => {
868
+ writeRoleguide();
869
+ failAfter = 'catalog';
870
+ await provision();
871
+ // This team's memory, with its seed reduced to one flat sentence: the #6
872
+ // shape `mx-agent window` reads as `unknown`. Ownership still reads
873
+ // `this-team`, so the classification is `malformed`, not `not-this-team`.
874
+ const held = standingMemories.get(MEMORY_NAMES[0]);
875
+ standingMemories.set(MEMORY_NAMES[0], { ...held, content: 'Leader state for newteam.' });
876
+ stdout = [];
877
+ failAfter = null;
878
+ const second = await provision();
879
+ // The row first: under the #478 edit this is the line that reads `asserted`.
880
+ expect(rowLines()[3]).toMatch(/row 3: not asserted/);
881
+ expect(rowLines()[3]).toContain('pre-existing and malformed');
882
+ expect(rowLines()[3]).not.toMatch(/row 3: asserted/);
883
+ expect(second.failure).toBeInstanceOf(CompletionCheckError);
884
+ // The two untouched memories still assert, so the fixture reached the branch.
885
+ for (const n of [4, 5])
886
+ expect(rowLines()[n]).toMatch(/row \d: asserted/);
887
+ expect(stdout.join('\n')).not.toContain('[✓] Named memories');
888
+ });
889
+ it('prints a standing memory nobody could read as could not run on a resume, never asserted (#478)', async () => {
890
+ writeRoleguide();
891
+ failAfter = 'catalog';
892
+ await provision();
893
+ expect(standingMemories.size).toBe(3);
894
+ // The probe found the name taken but brought back no content, which
895
+ // `memoryPresenceState` classifies `could-not-run` (`read: null`).
896
+ unreadableMemories.add(MEMORY_NAMES[2]);
897
+ stdout = [];
898
+ failAfter = null;
899
+ const second = await provision();
900
+ expect(rowLines()[5]).toMatch(/row 5: could not run/);
901
+ expect(rowLines()[5]).toContain('could not read the standing memory');
902
+ expect(rowLines()[5]).not.toMatch(/row 5: asserted/);
903
+ expect(second.failure).toBeInstanceOf(CompletionCheckError);
904
+ for (const n of [3, 4])
905
+ expect(rowLines()[n]).toMatch(/row \d: asserted/);
906
+ expect(stdout.join('\n')).not.toContain('[✓] Named memories');
907
+ });
908
+ it('prints a memory --recheck could not read as could not run, never asserted (#478)', async () => {
909
+ writeRoleguide();
910
+ await provision();
911
+ // `--recheck` reads each name itself. An `unknown` read, the status for a
912
+ // backend that could not be asked, classifies `could-not-run`.
913
+ unreadableMemories.add(MEMORY_NAMES[1]);
914
+ stdout = [];
915
+ const { failure } = await provision({ recheck: true });
916
+ expect(rowLines()[4]).toMatch(/row 4: could not run/);
917
+ expect(rowLines()[4]).toContain('could not read');
918
+ expect(rowLines()[4]).not.toMatch(/row 4: asserted/);
919
+ expect(failure).toBeInstanceOf(CompletionCheckError);
920
+ for (const n of [3, 5])
921
+ expect(rowLines()[n]).toMatch(/row \d: asserted/);
922
+ });
923
+ it('classifies the five states without a fixture', () => {
924
+ const expected = {
925
+ codeContext: { product: 'p', service: 'team-provisioning', team: 't', role: 'team-lead' },
926
+ content: '- Linkage: teams/t.md, roleguides/t.md\n',
927
+ };
928
+ const base = { name: 'p-t-leader-state', leaderState: true, requireProduct: true, expected };
929
+ expect(memoryPresenceState({ ...base, read: null, ownership: 'this-team' }).presence).toBe('could-not-run');
930
+ expect(memoryPresenceState({
931
+ ...base,
932
+ read: { content: expected.content, codeContext: expected.codeContext },
933
+ ownership: 'not-this-team',
934
+ }).presence).toBe('not-this-team');
935
+ expect(memoryPresenceState({
936
+ ...base,
937
+ read: { content: expected.content, codeContext: expected.codeContext },
938
+ ownership: 'unconfirmed',
939
+ }).presence).toBe('not-this-team');
940
+ });
941
+ });
942
+ // ── Change B: finding 8, the catalog entry is terminal ───────────────────────
943
+ describe('a resume leaves the catalog entry byte for byte', () => {
944
+ it('does not rewrite an entry edited between the two runs', async () => {
945
+ writeRoleguide();
946
+ failAfter = 'catalog';
947
+ await provision();
948
+ const entry = join(root, 'mx-agent-system/teams/newteam.md');
949
+ expect(existsSync(entry)).toBe(true);
950
+ const edited = `${readFileSync(entry, 'utf-8')}\n## Goal\n\nWritten by a person between the two runs.\n`;
951
+ writeFileSync(entry, edited);
952
+ failAfter = null;
953
+ const second = await provision();
954
+ expect(second.failure).toBeNull();
955
+ expect(readFileSync(entry, 'utf-8')).toBe(edited);
956
+ });
957
+ });
958
+ // ── Change D: `--recheck` ────────────────────────────────────────────────────
959
+ describe('--recheck reads the rows and writes nothing', () => {
960
+ it('changes no byte under the project root', async () => {
961
+ writeRoleguide();
962
+ await provision();
963
+ const before = snapshot(root);
964
+ stdout = [];
965
+ const { failure } = await provision({ recheck: true });
966
+ expect(failure).toBeNull();
967
+ const after = snapshot(root);
968
+ expect([...after.keys()].sort()).toEqual([...before.keys()].sort());
969
+ for (const [path, bytes] of before)
970
+ expect(after.get(path)).toBe(bytes);
971
+ });
972
+ it('prints the sixteen rows and asserts the ones a finished team holds', async () => {
973
+ writeRoleguide();
974
+ await provision();
975
+ stdout = [];
976
+ const { failure } = await provision({ recheck: true });
977
+ expect(failure).toBeNull();
978
+ expect(rowLines()).toHaveLength(16);
979
+ for (const n of [0, 1, 2, 3, 4, 5, 9, 10]) {
980
+ expect(rowLines()[n]).toMatch(/row \d+: asserted/);
981
+ }
982
+ expect(stdout.join('\n')).toContain('Nothing was written.');
983
+ });
984
+ it('states that row 10 was checked by cache presence only, and names what mints', async () => {
985
+ writeRoleguide();
986
+ await provision();
987
+ stdout = [];
988
+ await provision({ recheck: true });
989
+ expect(rowLines()[10]).toContain('checked by cache presence only');
990
+ expect(rowLines()[10]).toContain('mx-agent provision');
991
+ expect(rowLines()[10]).toContain('mints');
992
+ });
993
+ it('says so, and asks for no credential, when the cache is not there', async () => {
994
+ writeRoleguide();
995
+ await provision();
996
+ rmSync(join(root, WORKTREE_REL, '.mx-coordination-token--mx-agent--newteam'));
997
+ const fetchesBefore = credentialFetches;
998
+ stdout = [];
999
+ const { failure } = await provision({ recheck: true });
1000
+ expect(failure).toBeInstanceOf(CompletionCheckError);
1001
+ expect(credentialFetches).toBe(fetchesBefore);
1002
+ expect(rowLines()[10]).toContain('no credential cache');
1003
+ expect(rowLines()[10]).toContain('checked by cache presence only');
1004
+ });
1005
+ it('refuses when there is no worktree to check', async () => {
1006
+ const { failure } = await provision({ recheck: true });
1007
+ expect(failure).toBeInstanceOf(CompletionCheckError);
1008
+ expect(failure.message).toContain('no worktree');
1009
+ });
1010
+ });
1011
+ // ── Row 7's path, at the two sites that compute it (#406 part 1) ─────────────
1012
+ //
1013
+ // The row tests in `provision-completion-rows.test.ts` hand `checkCompletionRows`
1014
+ // a `roleguideOnBasePath` and assert the row it produces. That proves the row
1015
+ // discriminates. It proves NOTHING about the two call sites that compute the
1016
+ // path, and a wrong basename, a wrong `roleguidesDir` join or a stale
1017
+ // `roleguideRel` at either site would pass every one of those tests while row 7
1018
+ // reported confidently about a different file on a live creation (red-team
1019
+ // finding 2, #407 review round 1).
1020
+ //
1021
+ // These two run the real computation through `runCreate` and assert the exact
1022
+ // string it produced. Nothing about row 7 is stubbed: the reader is the real
1023
+ // one, wrapped only to record its arguments.
1024
+ describe('row 7 is given the path the run computed, at both call sites', () => {
1025
+ /**
1026
+ * The path row 7 must be read at, in this platform's separator, and the
1027
+ * `/`-separated git object path it becomes.
1028
+ *
1029
+ * Two forms because `join` is platform-dependent and a git object path is
1030
+ * `/`-separated everywhere. Both are asserted: the first is the literal string
1031
+ * the call site produced, the second is what the reader interpolates.
1032
+ */
1033
+ const EXPECTED = join('mx-agent-system', 'roleguides', 'newteam-leader.md');
1034
+ const EXPECTED_GIT_PATH = 'mx-agent-system/roleguides/newteam-leader.md';
1035
+ /** The path argument of every recorded call, in call order. */
1036
+ function pathArgs() {
1037
+ return vi.mocked(roleguideOnOriginMain).mock.calls.map((c) => c[1]);
1038
+ }
1039
+ it('provisioning passes the re-anchored copy destination, not the operator string', async () => {
1040
+ writeRoleguide();
1041
+ const { failure } = await provision();
1042
+ expect(failure).toBeNull();
1043
+ expect(pathArgs()).toEqual([EXPECTED]);
1044
+ expect(pathArgs()[0].split(sep).join('/')).toBe(EXPECTED_GIT_PATH);
1045
+ // The three ways the computation is wrong and the row still renders: a bare
1046
+ // basename, an absolute path, and a path anchored inside the new worktree.
1047
+ expect(pathArgs()[0]).not.toBe('newteam-leader.md');
1048
+ expect(isAbsolute(pathArgs()[0])).toBe(false);
1049
+ expect(pathArgs()[0]).not.toContain(WORKTREE_REL);
1050
+ // The root and the ref options are the run's own, not defaults.
1051
+ expect(vi.mocked(roleguideOnOriginMain).mock.calls[0][0]).toBe(root);
1052
+ expect(vi.mocked(roleguideOnOriginMain).mock.calls[0][2])
1053
+ .toEqual({ baseBranch: 'main', fetchOk: true });
1054
+ });
1055
+ it('a re-check reconstructs the same path row 1 reads, from the recorded roleguide', async () => {
1056
+ writeRoleguide();
1057
+ await provision();
1058
+ vi.mocked(roleguideOnOriginMain).mockClear();
1059
+ // No `--roleguide`: the path comes from the catalog entry or the worktree
1060
+ // pointer, through `join(cfg.roleguidesDir, basename(roleguideRel))`. That
1061
+ // is the expression this test exists to pin.
1062
+ const { failure } = await provision({ recheck: true });
1063
+ expect(failure).toBeNull();
1064
+ expect(pathArgs()).toEqual([EXPECTED]);
1065
+ expect(pathArgs()[0].split(sep).join('/')).toBe(EXPECTED_GIT_PATH);
1066
+ expect(vi.mocked(roleguideOnOriginMain).mock.calls[0][0]).toBe(root);
1067
+ expect(vi.mocked(roleguideOnOriginMain).mock.calls[0][2])
1068
+ .toEqual({ baseBranch: 'main', fetchOk: true });
1069
+ });
1070
+ it('the two sites agree, so row 7 reports about one file across a provision and a re-check', async () => {
1071
+ writeRoleguide();
1072
+ await provision();
1073
+ const fromProvision = pathArgs();
1074
+ vi.mocked(roleguideOnOriginMain).mockClear();
1075
+ await provision({ recheck: true });
1076
+ expect(pathArgs()).toEqual(fromProvision);
1077
+ });
1078
+ });
1079
+ // ── Change C: no process.exit in the window ──────────────────────────────────
1080
+ describe('the window between the worktree and the pre-check has no process.exit', () => {
1081
+ it('greps the span in the shipped source', () => {
1082
+ const source = readFileSync(join(__dirname, '..', 'commands', 'create.ts'), 'utf-8');
1083
+ const start = source.indexOf('createGitWorktree(worktreePath, branch, cfg.baseBranch, projectRoot)');
1084
+ const end = source.indexOf('willRefuseAtRow13 = !row13AtGate.asserted;');
1085
+ expect(start).toBeGreaterThan(0);
1086
+ expect(end).toBeGreaterThan(start);
1087
+ const span = source.slice(start, end);
1088
+ // The CALL, not the words: the comments in this file name `process.exit` to
1089
+ // say what the code no longer does.
1090
+ expect(span).not.toContain('process.exit(');
1091
+ });
1092
+ it('has none anywhere in the durable half of the command', () => {
1093
+ const source = readFileSync(join(__dirname, '..', 'commands', 'create.ts'), 'utf-8');
1094
+ const start = source.indexOf('async function runProvisionSteps(');
1095
+ const end = source.indexOf(' * Test-only surface for the two filesystem-containment helpers.');
1096
+ expect(start).toBeGreaterThan(0);
1097
+ expect(end).toBeGreaterThan(start);
1098
+ expect(source.slice(start, end)).not.toContain('process.exit(');
1099
+ });
1100
+ });
1101
+ // ── The fault-injection mechanism itself ─────────────────────────────────────
1102
+ describe('fault injection is refused outside a test build', () => {
1103
+ it('names the step and cuts the run in a test build', async () => {
1104
+ writeRoleguide();
1105
+ failAfter = 'catalog';
1106
+ const { failure } = await provision();
1107
+ expect(failure).toBeInstanceOf(CompletionCheckError);
1108
+ expect(failure.message).toContain('catalog');
1109
+ });
1110
+ it('provisions normally when the variable names no known point', async () => {
1111
+ writeRoleguide();
1112
+ process.env.MX_PROVISION_FAIL_AFTER = 'not-a-step';
1113
+ process.env.MX_PROVISION_FAULT_INJECTION = '1';
1114
+ const { failure } = await provision();
1115
+ expect(failure).toBeNull();
1116
+ });
1117
+ it('needs BOTH the test build and the arming variable', () => {
1118
+ const { faultInjectionStep } = __testing;
1119
+ const armed = { MX_PROVISION_FAIL_AFTER: 'worktree', MX_PROVISION_FAULT_INJECTION: '1' };
1120
+ // Neither alone.
1121
+ expect(faultInjectionStep({ ...armed, NODE_ENV: 'production' })).toBeNull();
1122
+ expect(faultInjectionStep({ MX_PROVISION_FAIL_AFTER: 'worktree', NODE_ENV: 'test' })).toBeNull();
1123
+ // Both.
1124
+ expect(faultInjectionStep({ ...armed, NODE_ENV: 'test' })).toBe('worktree');
1125
+ expect(faultInjectionStep({})).toBeNull();
1126
+ });
1127
+ it('refuses a credential fault point against a service that is not on this host', async () => {
1128
+ // Security review round 2, Should Fix 2. The point reaches a real mint, so a
1129
+ // non-loopback service would spend a token per run and leave it unrevoked.
1130
+ const { isLoopbackServiceUrl } = __testing;
1131
+ expect(isLoopbackServiceUrl('http://127.0.0.1:9')).toBe(true);
1132
+ expect(isLoopbackServiceUrl('http://localhost:8080/x')).toBe(true);
1133
+ expect(isLoopbackServiceUrl('https://coordination.example.invalid')).toBe(false);
1134
+ expect(isLoopbackServiceUrl(undefined)).toBe(false);
1135
+ expect(isLoopbackServiceUrl('not a url')).toBe(false);
1136
+ });
1137
+ it('hands the mint the URL the gate checked, not one the callee re-resolves', async () => {
1138
+ // Security re-check round 3. The gate reads the URL resolved from
1139
+ // `projectRoot`; `obtainCredential` resolves its own with no root, which
1140
+ // derives one from the current directory. Two answers, and this fixture's
1141
+ // resolver gives a different one to each caller, so a run that let the callee
1142
+ // re-resolve would send the request to URL_FROM_CWD while the gate cleared a
1143
+ // loopback stub.
1144
+ writeRoleguide();
1145
+ const { failure } = await provision();
1146
+ expect(failure).toBeNull();
1147
+ expect(credentialServiceUrls).toEqual(['http://127.0.0.1:9']);
1148
+ expect(credentialServiceUrls[0]).not.toBe(URL_FROM_CWD);
1149
+ });
1150
+ it('refuses the injected mint when the project resolves a service off this host', async () => {
1151
+ writeRoleguide();
1152
+ // The project's own URL is remote. The gate must fire on THAT, which is the
1153
+ // URL the request now carries.
1154
+ urlFromProjectRoot = 'https://coordination.example.invalid';
1155
+ failAfter = 'credential-cache-write-once';
1156
+ const { failure } = await provision();
1157
+ expect(failure).toBeInstanceOf(CompletionCheckError);
1158
+ expect(failure.message).toContain('loopback');
1159
+ // Nothing was asked of any service.
1160
+ expect(credentialServiceUrls).toEqual([]);
1161
+ expect(credentialFetches).toBe(0);
1162
+ });
1163
+ });
1164
+ //# sourceMappingURL=provision-resume.test.js.map