@memnexus-ai/mx-agent-cli 0.1.294-next.0 → 0.1.295-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 (450) 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__/cli-build-integration.test.d.ts +2 -0
  26. package/dist/__tests__/cli-build-integration.test.d.ts.map +1 -0
  27. package/dist/__tests__/cli-build-integration.test.js +64 -0
  28. package/dist/__tests__/cli-build-integration.test.js.map +1 -0
  29. package/dist/__tests__/cli-build.test.d.ts +2 -0
  30. package/dist/__tests__/cli-build.test.d.ts.map +1 -0
  31. package/dist/__tests__/cli-build.test.js +640 -0
  32. package/dist/__tests__/cli-build.test.js.map +1 -0
  33. package/dist/__tests__/codex-deploy-config.test.js +60 -0
  34. package/dist/__tests__/codex-deploy-config.test.js.map +1 -1
  35. package/dist/__tests__/completion-rows-discriminate.test.d.ts +20 -0
  36. package/dist/__tests__/completion-rows-discriminate.test.d.ts.map +1 -0
  37. package/dist/__tests__/completion-rows-discriminate.test.js +481 -0
  38. package/dist/__tests__/completion-rows-discriminate.test.js.map +1 -0
  39. package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts +2 -0
  40. package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts.map +1 -0
  41. package/dist/__tests__/config-fidelity-archived-symlinks.test.js +127 -0
  42. package/dist/__tests__/config-fidelity-archived-symlinks.test.js.map +1 -0
  43. package/dist/__tests__/config-fidelity-display.test.d.ts +2 -0
  44. package/dist/__tests__/config-fidelity-display.test.d.ts.map +1 -0
  45. package/dist/__tests__/config-fidelity-display.test.js +77 -0
  46. package/dist/__tests__/config-fidelity-display.test.js.map +1 -0
  47. package/dist/__tests__/config-fidelity.test.js +166 -33
  48. package/dist/__tests__/config-fidelity.test.js.map +1 -1
  49. package/dist/__tests__/config-generation-gate.test.js +78 -0
  50. package/dist/__tests__/config-generation-gate.test.js.map +1 -1
  51. package/dist/__tests__/config-sync.test.js +35 -0
  52. package/dist/__tests__/config-sync.test.js.map +1 -1
  53. package/dist/__tests__/coordination-401-production-wiring.test.js +12 -7
  54. package/dist/__tests__/coordination-401-production-wiring.test.js.map +1 -1
  55. package/dist/__tests__/coordination-401-recovery.test.js +39 -32
  56. package/dist/__tests__/coordination-401-recovery.test.js.map +1 -1
  57. package/dist/__tests__/coordination-brief-pin.test.js +21 -8
  58. package/dist/__tests__/coordination-brief-pin.test.js.map +1 -1
  59. package/dist/__tests__/coordination-client.test.js +227 -3
  60. package/dist/__tests__/coordination-client.test.js.map +1 -1
  61. package/dist/__tests__/coordination-credential-endpoint.test.d.ts +24 -0
  62. package/dist/__tests__/coordination-credential-endpoint.test.d.ts.map +1 -0
  63. package/dist/__tests__/coordination-credential-endpoint.test.js +1230 -0
  64. package/dist/__tests__/coordination-credential-endpoint.test.js.map +1 -0
  65. package/dist/__tests__/coordination-memory.test.js +20 -4
  66. package/dist/__tests__/coordination-memory.test.js.map +1 -1
  67. package/dist/__tests__/coordination-provision.test.js +22 -14
  68. package/dist/__tests__/coordination-provision.test.js.map +1 -1
  69. package/dist/__tests__/coordination-status-registration.test.d.ts +16 -0
  70. package/dist/__tests__/coordination-status-registration.test.d.ts.map +1 -0
  71. package/dist/__tests__/coordination-status-registration.test.js +480 -0
  72. package/dist/__tests__/coordination-status-registration.test.js.map +1 -0
  73. package/dist/__tests__/coordination-token-multitenant.test.js +11 -11
  74. package/dist/__tests__/coordination-token-multitenant.test.js.map +1 -1
  75. package/dist/__tests__/coordination-token.test.js +35 -28
  76. package/dist/__tests__/coordination-token.test.js.map +1 -1
  77. package/dist/__tests__/creation-pr-class-check.test.d.ts +17 -0
  78. package/dist/__tests__/creation-pr-class-check.test.d.ts.map +1 -0
  79. package/dist/__tests__/creation-pr-class-check.test.js +346 -0
  80. package/dist/__tests__/creation-pr-class-check.test.js.map +1 -0
  81. package/dist/__tests__/digest-team-omission.test.d.ts +15 -0
  82. package/dist/__tests__/digest-team-omission.test.d.ts.map +1 -0
  83. package/dist/__tests__/digest-team-omission.test.js +247 -0
  84. package/dist/__tests__/digest-team-omission.test.js.map +1 -0
  85. package/dist/__tests__/doctor-worktree-path.test.d.ts +17 -0
  86. package/dist/__tests__/doctor-worktree-path.test.d.ts.map +1 -0
  87. package/dist/__tests__/doctor-worktree-path.test.js +158 -0
  88. package/dist/__tests__/doctor-worktree-path.test.js.map +1 -0
  89. package/dist/__tests__/fleet-data.test.js +40 -7
  90. package/dist/__tests__/fleet-data.test.js.map +1 -1
  91. package/dist/__tests__/fleet-tmux.test.js +2 -2
  92. package/dist/__tests__/fleet-tmux.test.js.map +1 -1
  93. package/dist/__tests__/generate-claude.test.js +137 -3
  94. package/dist/__tests__/generate-claude.test.js.map +1 -1
  95. package/dist/__tests__/git-env.test.d.ts +14 -0
  96. package/dist/__tests__/git-env.test.d.ts.map +1 -0
  97. package/dist/__tests__/git-env.test.js +131 -0
  98. package/dist/__tests__/git-env.test.js.map +1 -0
  99. package/dist/__tests__/git-identity-isolation.test.d.ts +33 -0
  100. package/dist/__tests__/git-identity-isolation.test.d.ts.map +1 -0
  101. package/dist/__tests__/git-identity-isolation.test.js +626 -0
  102. package/dist/__tests__/git-identity-isolation.test.js.map +1 -0
  103. package/dist/__tests__/hook-heal.test.js +17 -0
  104. package/dist/__tests__/hook-heal.test.js.map +1 -1
  105. package/dist/__tests__/init-coordination-url.test.d.ts +11 -0
  106. package/dist/__tests__/init-coordination-url.test.d.ts.map +1 -0
  107. package/dist/__tests__/init-coordination-url.test.js +114 -0
  108. package/dist/__tests__/init-coordination-url.test.js.map +1 -0
  109. package/dist/__tests__/memory-autocreate.test.js +574 -8
  110. package/dist/__tests__/memory-autocreate.test.js.map +1 -1
  111. package/dist/__tests__/memory-log-result.test.d.ts +13 -0
  112. package/dist/__tests__/memory-log-result.test.d.ts.map +1 -0
  113. package/dist/__tests__/memory-log-result.test.js +113 -0
  114. package/dist/__tests__/memory-log-result.test.js.map +1 -0
  115. package/dist/__tests__/memory-named-exists.test.d.ts +16 -0
  116. package/dist/__tests__/memory-named-exists.test.d.ts.map +1 -0
  117. package/dist/__tests__/memory-named-exists.test.js +288 -0
  118. package/dist/__tests__/memory-named-exists.test.js.map +1 -0
  119. package/dist/__tests__/mx-agent-cli-pin-validation.test.js +23 -47
  120. package/dist/__tests__/mx-agent-cli-pin-validation.test.js.map +1 -1
  121. package/dist/__tests__/mx-agent-cli-version-pin.test.js +34 -88
  122. package/dist/__tests__/mx-agent-cli-version-pin.test.js.map +1 -1
  123. package/dist/__tests__/new-project-first-team.test.d.ts +15 -0
  124. package/dist/__tests__/new-project-first-team.test.d.ts.map +1 -0
  125. package/dist/__tests__/new-project-first-team.test.js +263 -0
  126. package/dist/__tests__/new-project-first-team.test.js.map +1 -0
  127. package/dist/__tests__/otel-env.test.d.ts +2 -0
  128. package/dist/__tests__/otel-env.test.d.ts.map +1 -0
  129. package/dist/__tests__/otel-env.test.js +127 -0
  130. package/dist/__tests__/otel-env.test.js.map +1 -0
  131. package/dist/__tests__/project-config.test.js +283 -1
  132. package/dist/__tests__/project-config.test.js.map +1 -1
  133. package/dist/__tests__/provision-behavioral-contract.test.js +96 -4
  134. package/dist/__tests__/provision-behavioral-contract.test.js.map +1 -1
  135. package/dist/__tests__/provision-catalog-precondition.test.d.ts +26 -0
  136. package/dist/__tests__/provision-catalog-precondition.test.d.ts.map +1 -0
  137. package/dist/__tests__/provision-catalog-precondition.test.js +620 -0
  138. package/dist/__tests__/provision-catalog-precondition.test.js.map +1 -0
  139. package/dist/__tests__/provision-completion-rows.test.d.ts +17 -0
  140. package/dist/__tests__/provision-completion-rows.test.d.ts.map +1 -0
  141. package/dist/__tests__/provision-completion-rows.test.js +3095 -0
  142. package/dist/__tests__/provision-completion-rows.test.js.map +1 -0
  143. package/dist/__tests__/provision-identity-gate.test.d.ts +20 -0
  144. package/dist/__tests__/provision-identity-gate.test.d.ts.map +1 -0
  145. package/dist/__tests__/provision-identity-gate.test.js +600 -0
  146. package/dist/__tests__/provision-identity-gate.test.js.map +1 -0
  147. package/dist/__tests__/provision-resume.test.d.ts +26 -0
  148. package/dist/__tests__/provision-resume.test.d.ts.map +1 -0
  149. package/dist/__tests__/provision-resume.test.js +1164 -0
  150. package/dist/__tests__/provision-resume.test.js.map +1 -0
  151. package/dist/__tests__/provision-roleguide-anchors.test.d.ts +27 -0
  152. package/dist/__tests__/provision-roleguide-anchors.test.d.ts.map +1 -0
  153. package/dist/__tests__/provision-roleguide-anchors.test.js +747 -0
  154. package/dist/__tests__/provision-roleguide-anchors.test.js.map +1 -0
  155. package/dist/__tests__/provision-skeleton-fill.test.d.ts +16 -0
  156. package/dist/__tests__/provision-skeleton-fill.test.d.ts.map +1 -0
  157. package/dist/__tests__/provision-skeleton-fill.test.js +488 -0
  158. package/dist/__tests__/provision-skeleton-fill.test.js.map +1 -0
  159. package/dist/__tests__/provision-teambuilder-flow.test.js +93 -7
  160. package/dist/__tests__/provision-teambuilder-flow.test.js.map +1 -1
  161. package/dist/__tests__/repo-guard-wiring.test.d.ts +21 -0
  162. package/dist/__tests__/repo-guard-wiring.test.d.ts.map +1 -0
  163. package/dist/__tests__/repo-guard-wiring.test.js +638 -0
  164. package/dist/__tests__/repo-guard-wiring.test.js.map +1 -0
  165. package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts +2 -0
  166. package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts.map +1 -0
  167. package/dist/__tests__/runtime-codex-gateway-pilot.test.js +309 -0
  168. package/dist/__tests__/runtime-codex-gateway-pilot.test.js.map +1 -0
  169. package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts +2 -0
  170. package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts.map +1 -0
  171. package/dist/__tests__/runtime-codex-gateway-provider.test.js +163 -0
  172. package/dist/__tests__/runtime-codex-gateway-provider.test.js.map +1 -0
  173. package/dist/__tests__/runtime-identity.test.d.ts +2 -0
  174. package/dist/__tests__/runtime-identity.test.d.ts.map +1 -0
  175. package/dist/__tests__/runtime-identity.test.js +117 -0
  176. package/dist/__tests__/runtime-identity.test.js.map +1 -0
  177. package/dist/__tests__/session-pause-provisioning.test.js +6 -1
  178. package/dist/__tests__/session-pause-provisioning.test.js.map +1 -1
  179. package/dist/__tests__/session-record-disclosure.test.d.ts +24 -0
  180. package/dist/__tests__/session-record-disclosure.test.d.ts.map +1 -0
  181. package/dist/__tests__/session-record-disclosure.test.js +494 -0
  182. package/dist/__tests__/session-record-disclosure.test.js.map +1 -0
  183. package/dist/__tests__/session.test.js +35 -0
  184. package/dist/__tests__/session.test.js.map +1 -1
  185. package/dist/__tests__/slug-validation.test.js +27 -21
  186. package/dist/__tests__/slug-validation.test.js.map +1 -1
  187. package/dist/__tests__/standards-injection.test.js +23 -1
  188. package/dist/__tests__/standards-injection.test.js.map +1 -1
  189. package/dist/__tests__/start-interactive-role.test.d.ts +22 -0
  190. package/dist/__tests__/start-interactive-role.test.d.ts.map +1 -0
  191. package/dist/__tests__/start-interactive-role.test.js +204 -0
  192. package/dist/__tests__/start-interactive-role.test.js.map +1 -0
  193. package/dist/__tests__/start-team-identity.test.d.ts +25 -0
  194. package/dist/__tests__/start-team-identity.test.d.ts.map +1 -0
  195. package/dist/__tests__/start-team-identity.test.js +307 -0
  196. package/dist/__tests__/start-team-identity.test.js.map +1 -0
  197. package/dist/__tests__/team-memory-commands.test.js +142 -19
  198. package/dist/__tests__/team-memory-commands.test.js.map +1 -1
  199. package/dist/__tests__/template-sync.test.d.ts +19 -0
  200. package/dist/__tests__/template-sync.test.d.ts.map +1 -0
  201. package/dist/__tests__/template-sync.test.js +270 -0
  202. package/dist/__tests__/template-sync.test.js.map +1 -0
  203. package/dist/__tests__/test-project.test.d.ts +18 -0
  204. package/dist/__tests__/test-project.test.d.ts.map +1 -0
  205. package/dist/__tests__/test-project.test.js +465 -0
  206. package/dist/__tests__/test-project.test.js.map +1 -0
  207. package/dist/__tests__/usage-per-call-grouping.test.d.ts +25 -0
  208. package/dist/__tests__/usage-per-call-grouping.test.d.ts.map +1 -0
  209. package/dist/__tests__/usage-per-call-grouping.test.js +952 -0
  210. package/dist/__tests__/usage-per-call-grouping.test.js.map +1 -0
  211. package/dist/__tests__/verify-hooks-check-all.test.d.ts +32 -0
  212. package/dist/__tests__/verify-hooks-check-all.test.d.ts.map +1 -0
  213. package/dist/__tests__/verify-hooks-check-all.test.js +553 -0
  214. package/dist/__tests__/verify-hooks-check-all.test.js.map +1 -0
  215. package/dist/__tests__/worktree-sync-fixture.test.d.ts +17 -0
  216. package/dist/__tests__/worktree-sync-fixture.test.d.ts.map +1 -0
  217. package/dist/__tests__/worktree-sync-fixture.test.js +519 -0
  218. package/dist/__tests__/worktree-sync-fixture.test.js.map +1 -0
  219. package/dist/__tests__/worktree-sync-hardening.test.d.ts +13 -0
  220. package/dist/__tests__/worktree-sync-hardening.test.d.ts.map +1 -0
  221. package/dist/__tests__/worktree-sync-hardening.test.js +919 -0
  222. package/dist/__tests__/worktree-sync-hardening.test.js.map +1 -0
  223. package/dist/__tests__/worktree-sync-shell-free.test.d.ts +25 -0
  224. package/dist/__tests__/worktree-sync-shell-free.test.d.ts.map +1 -0
  225. package/dist/__tests__/worktree-sync-shell-free.test.js +185 -0
  226. package/dist/__tests__/worktree-sync-shell-free.test.js.map +1 -0
  227. package/dist/__tests__/worktree.test.js +75 -1
  228. package/dist/__tests__/worktree.test.js.map +1 -1
  229. package/dist/agent-config/.mx-config-generation.json +2 -2
  230. package/dist/agent-config/AGENTS.md.template +2 -2
  231. package/dist/agent-config/agents/bar-raiser.md +34 -1
  232. package/dist/agent-config/agents/red-team.md +34 -1
  233. package/dist/agent-config/agents/security-reviewer.md +22 -1
  234. package/dist/agent-config/claude-md/CLAUDE.core.md +6 -1
  235. package/dist/agent-config/claude-md/CLAUDE.overlay.memnexus.md +1 -3
  236. package/dist/agent-config/coordination-rosters.generated.json +10 -0
  237. package/dist/agent-config/hooks/HOOK-TIMEOUTS.md +27 -1
  238. package/dist/agent-config/hooks/OR-TRUE-AUDIT.md +8 -8
  239. package/dist/agent-config/hooks/auto-capture-precompact.sh +279 -0
  240. package/dist/agent-config/hooks/auto-capture-session-end.sh +277 -0
  241. package/dist/agent-config/hooks/coordination-brief.sh +290 -245
  242. package/dist/agent-config/hooks/deploy-verification-reminder.sh +359 -22
  243. package/dist/agent-config/hooks/git-mutation-guard.sh +85 -13
  244. package/dist/agent-config/hooks/session-idle-gate.sh +177 -12
  245. package/dist/agent-config/hooks/subagent-write-guard.sh +670 -0
  246. package/dist/agent-config/hooks/worktree-guard.sh +36 -7
  247. package/dist/agent-config/settings.json +15 -2
  248. package/dist/agent-config/shared/creation-pr-review-checklist.md +317 -0
  249. package/dist/commands/bootstrap.d.ts.map +1 -1
  250. package/dist/commands/bootstrap.js +22 -10
  251. package/dist/commands/bootstrap.js.map +1 -1
  252. package/dist/commands/config.d.ts.map +1 -1
  253. package/dist/commands/config.js +28 -1
  254. package/dist/commands/config.js.map +1 -1
  255. package/dist/commands/coordination.d.ts +150 -8
  256. package/dist/commands/coordination.d.ts.map +1 -1
  257. package/dist/commands/coordination.js +519 -25
  258. package/dist/commands/coordination.js.map +1 -1
  259. package/dist/commands/create.d.ts +913 -1
  260. package/dist/commands/create.d.ts.map +1 -1
  261. package/dist/commands/create.js +4879 -345
  262. package/dist/commands/create.js.map +1 -1
  263. package/dist/commands/digest.d.ts.map +1 -1
  264. package/dist/commands/digest.js +91 -7
  265. package/dist/commands/digest.js.map +1 -1
  266. package/dist/commands/fleet-tmux.js +1 -1
  267. package/dist/commands/fleet-tmux.js.map +1 -1
  268. package/dist/commands/init.d.ts +8 -0
  269. package/dist/commands/init.d.ts.map +1 -1
  270. package/dist/commands/init.js +26 -1
  271. package/dist/commands/init.js.map +1 -1
  272. package/dist/commands/list.d.ts +32 -1
  273. package/dist/commands/list.d.ts.map +1 -1
  274. package/dist/commands/list.js +98 -5
  275. package/dist/commands/list.js.map +1 -1
  276. package/dist/commands/new.d.ts +2 -0
  277. package/dist/commands/new.d.ts.map +1 -1
  278. package/dist/commands/new.js +114 -21
  279. package/dist/commands/new.js.map +1 -1
  280. package/dist/commands/session.js +1 -1
  281. package/dist/commands/session.js.map +1 -1
  282. package/dist/commands/start.d.ts +38 -0
  283. package/dist/commands/start.d.ts.map +1 -1
  284. package/dist/commands/start.js +171 -8
  285. package/dist/commands/start.js.map +1 -1
  286. package/dist/commands/sync.d.ts +57 -0
  287. package/dist/commands/sync.d.ts.map +1 -1
  288. package/dist/commands/sync.js +117 -3
  289. package/dist/commands/sync.js.map +1 -1
  290. package/dist/commands/usage.d.ts +64 -0
  291. package/dist/commands/usage.d.ts.map +1 -1
  292. package/dist/commands/usage.js +96 -3
  293. package/dist/commands/usage.js.map +1 -1
  294. package/dist/commands/verify-hooks.d.ts +37 -1
  295. package/dist/commands/verify-hooks.d.ts.map +1 -1
  296. package/dist/commands/verify-hooks.js +114 -2
  297. package/dist/commands/verify-hooks.js.map +1 -1
  298. package/dist/commands/window.d.ts +10 -0
  299. package/dist/commands/window.d.ts.map +1 -0
  300. package/dist/commands/window.js +265 -0
  301. package/dist/commands/window.js.map +1 -0
  302. package/dist/commands/worktree-sync.d.ts +54 -0
  303. package/dist/commands/worktree-sync.d.ts.map +1 -0
  304. package/dist/commands/worktree-sync.js +135 -0
  305. package/dist/commands/worktree-sync.js.map +1 -0
  306. package/dist/index.d.ts.map +1 -1
  307. package/dist/index.js +122 -11
  308. package/dist/index.js.map +1 -1
  309. package/dist/lib/agent-session.d.ts.map +1 -1
  310. package/dist/lib/agent-session.js +6 -1
  311. package/dist/lib/agent-session.js.map +1 -1
  312. package/dist/lib/catalog.d.ts +321 -2
  313. package/dist/lib/catalog.d.ts.map +1 -1
  314. package/dist/lib/catalog.js +490 -11
  315. package/dist/lib/catalog.js.map +1 -1
  316. package/dist/lib/claude.d.ts +53 -23
  317. package/dist/lib/claude.d.ts.map +1 -1
  318. package/dist/lib/claude.js +306 -17
  319. package/dist/lib/claude.js.map +1 -1
  320. package/dist/lib/cli-build.d.ts +172 -0
  321. package/dist/lib/cli-build.d.ts.map +1 -0
  322. package/dist/lib/cli-build.js +654 -0
  323. package/dist/lib/cli-build.js.map +1 -0
  324. package/dist/lib/code-context-file.d.ts +109 -0
  325. package/dist/lib/code-context-file.d.ts.map +1 -0
  326. package/dist/lib/code-context-file.js +219 -0
  327. package/dist/lib/code-context-file.js.map +1 -0
  328. package/dist/lib/code-context-file.test.d.ts +19 -0
  329. package/dist/lib/code-context-file.test.d.ts.map +1 -0
  330. package/dist/lib/code-context-file.test.js +202 -0
  331. package/dist/lib/code-context-file.test.js.map +1 -0
  332. package/dist/lib/config-fidelity.d.ts +40 -20
  333. package/dist/lib/config-fidelity.d.ts.map +1 -1
  334. package/dist/lib/config-fidelity.js +144 -56
  335. package/dist/lib/config-fidelity.js.map +1 -1
  336. package/dist/lib/coordination-client.d.ts +73 -0
  337. package/dist/lib/coordination-client.d.ts.map +1 -1
  338. package/dist/lib/coordination-client.js +180 -8
  339. package/dist/lib/coordination-client.js.map +1 -1
  340. package/dist/lib/coordination-token.d.ts +304 -6
  341. package/dist/lib/coordination-token.d.ts.map +1 -1
  342. package/dist/lib/coordination-token.js +851 -52
  343. package/dist/lib/coordination-token.js.map +1 -1
  344. package/dist/lib/fleet-data.d.ts +34 -0
  345. package/dist/lib/fleet-data.d.ts.map +1 -1
  346. package/dist/lib/fleet-data.js +37 -9
  347. package/dist/lib/fleet-data.js.map +1 -1
  348. package/dist/lib/fleet-render.js +1 -1
  349. package/dist/lib/fleet-render.js.map +1 -1
  350. package/dist/lib/git-identity.d.ts +302 -0
  351. package/dist/lib/git-identity.d.ts.map +1 -0
  352. package/dist/lib/git-identity.js +546 -0
  353. package/dist/lib/git-identity.js.map +1 -0
  354. package/dist/lib/hook-staleness.d.ts +95 -0
  355. package/dist/lib/hook-staleness.d.ts.map +1 -0
  356. package/dist/lib/hook-staleness.js +304 -0
  357. package/dist/lib/hook-staleness.js.map +1 -0
  358. package/dist/lib/jsonl.d.ts +270 -2
  359. package/dist/lib/jsonl.d.ts.map +1 -1
  360. package/dist/lib/jsonl.js +472 -76
  361. package/dist/lib/jsonl.js.map +1 -1
  362. package/dist/lib/memory.d.ts +350 -23
  363. package/dist/lib/memory.d.ts.map +1 -1
  364. package/dist/lib/memory.js +751 -38
  365. package/dist/lib/memory.js.map +1 -1
  366. package/dist/lib/otel-env.d.ts +90 -0
  367. package/dist/lib/otel-env.d.ts.map +1 -0
  368. package/dist/lib/otel-env.js +98 -0
  369. package/dist/lib/otel-env.js.map +1 -0
  370. package/dist/lib/project-config.d.ts +167 -0
  371. package/dist/lib/project-config.d.ts.map +1 -1
  372. package/dist/lib/project-config.js +321 -5
  373. package/dist/lib/project-config.js.map +1 -1
  374. package/dist/lib/projects-registry.d.ts +82 -0
  375. package/dist/lib/projects-registry.d.ts.map +1 -0
  376. package/dist/lib/projects-registry.js +145 -0
  377. package/dist/lib/projects-registry.js.map +1 -0
  378. package/dist/lib/projects-registry.test.d.ts +2 -0
  379. package/dist/lib/projects-registry.test.d.ts.map +1 -0
  380. package/dist/lib/projects-registry.test.js +176 -0
  381. package/dist/lib/projects-registry.test.js.map +1 -0
  382. package/dist/lib/repo-guard-scope.d.ts +126 -0
  383. package/dist/lib/repo-guard-scope.d.ts.map +1 -0
  384. package/dist/lib/repo-guard-scope.js +249 -0
  385. package/dist/lib/repo-guard-scope.js.map +1 -0
  386. package/dist/lib/roster.d.ts +87 -0
  387. package/dist/lib/roster.d.ts.map +1 -0
  388. package/dist/lib/roster.js +332 -0
  389. package/dist/lib/roster.js.map +1 -0
  390. package/dist/lib/roster.test.d.ts +15 -0
  391. package/dist/lib/roster.test.d.ts.map +1 -0
  392. package/dist/lib/roster.test.js +299 -0
  393. package/dist/lib/roster.test.js.map +1 -0
  394. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  395. package/dist/lib/runtime/codex-adapter.js +5 -0
  396. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  397. package/dist/lib/runtime/codex-config.d.ts +129 -0
  398. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  399. package/dist/lib/runtime/codex-config.js +225 -0
  400. package/dist/lib/runtime/codex-config.js.map +1 -1
  401. package/dist/lib/runtime/identity.d.ts +72 -0
  402. package/dist/lib/runtime/identity.d.ts.map +1 -0
  403. package/dist/lib/runtime/identity.js +128 -0
  404. package/dist/lib/runtime/identity.js.map +1 -0
  405. package/dist/lib/standards.d.ts +10 -1
  406. package/dist/lib/standards.d.ts.map +1 -1
  407. package/dist/lib/standards.js +8 -1
  408. package/dist/lib/standards.js.map +1 -1
  409. package/dist/lib/team-identity.d.ts +134 -0
  410. package/dist/lib/team-identity.d.ts.map +1 -0
  411. package/dist/lib/team-identity.js +193 -0
  412. package/dist/lib/team-identity.js.map +1 -0
  413. package/dist/lib/templates.d.ts +29 -2
  414. package/dist/lib/templates.d.ts.map +1 -1
  415. package/dist/lib/templates.js +1042 -82
  416. package/dist/lib/templates.js.map +1 -1
  417. package/dist/lib/test-project.d.ts +95 -0
  418. package/dist/lib/test-project.d.ts.map +1 -0
  419. package/dist/lib/test-project.js +103 -0
  420. package/dist/lib/test-project.js.map +1 -0
  421. package/dist/lib/vault.d.ts +60 -0
  422. package/dist/lib/vault.d.ts.map +1 -0
  423. package/dist/lib/vault.js +102 -0
  424. package/dist/lib/vault.js.map +1 -0
  425. package/dist/lib/vault.test.d.ts +17 -0
  426. package/dist/lib/vault.test.d.ts.map +1 -0
  427. package/dist/lib/vault.test.js +169 -0
  428. package/dist/lib/vault.test.js.map +1 -0
  429. package/dist/lib/window-view.d.ts +63 -0
  430. package/dist/lib/window-view.d.ts.map +1 -0
  431. package/dist/lib/window-view.js +217 -0
  432. package/dist/lib/window-view.js.map +1 -0
  433. package/dist/lib/window-view.test.d.ts +2 -0
  434. package/dist/lib/window-view.test.d.ts.map +1 -0
  435. package/dist/lib/window-view.test.js +168 -0
  436. package/dist/lib/window-view.test.js.map +1 -0
  437. package/dist/lib/worktree-sync.d.ts +439 -0
  438. package/dist/lib/worktree-sync.d.ts.map +1 -0
  439. package/dist/lib/worktree-sync.js +1167 -0
  440. package/dist/lib/worktree-sync.js.map +1 -0
  441. package/dist/lib/worktree.d.ts +58 -1
  442. package/dist/lib/worktree.d.ts.map +1 -1
  443. package/dist/lib/worktree.js +91 -4
  444. package/dist/lib/worktree.js.map +1 -1
  445. package/dist/standards/decision-request.md +8 -0
  446. package/dist/standards/po-communication-standard.md +126 -0
  447. package/dist/standards/report-format.md +8 -0
  448. package/dist/standards/writing-standard.md +146 -4
  449. package/package.json +1 -1
  450. package/scripts/generate-claude.mjs +119 -46
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { spawnSync } from 'child_process';
5
5
  import chalk from 'chalk';
6
+ import { PROJECT_CONFIG_DEFAULTS } from './project-config.js';
6
7
  // ── mx availability ───────────────────────────────────────────────────
7
8
  export function isMxAvailable() {
8
9
  const result = spawnSync('mx', ['--version'], { stdio: 'pipe' });
@@ -13,15 +14,22 @@ function runCreate(args) {
13
14
  const result = spawnSync('mx', args, { stdio: 'pipe', encoding: 'utf-8' });
14
15
  const stdout = result.stdout || '';
15
16
  const stderr = result.stderr || '';
16
- return { status: result.status, output: (stdout + stderr), stderr, error: Boolean(result.error) };
17
+ // `output` stays stdout+stderr for the operator-facing log line; `stdout` is
18
+ // kept separate because the id parser must never read diagnostics.
19
+ return { status: result.status, output: (stdout + stderr), stdout, stderr, error: Boolean(result.error) };
17
20
  }
18
21
  /**
19
22
  * Wrap a string in POSIX single quotes for safe copy-paste into a shell — the
20
23
  * only metacharacter live inside single quotes is `'` itself, escaped as `'\''`.
21
24
  * Prevents `$(...)`, backticks, and other expansions in printed manual commands
22
25
  * (CWE-78) even when the value embeds an unvalidated path.
26
+ *
27
+ * Exported because `create.ts` prints the same shape of copy-paste command in
28
+ * three refusal messages. Path containment validates where a path RESOLVES, not
29
+ * which characters it contains, so `--roleguide 'roleguides/$(id).md'` reaches
30
+ * those printed lines intact and would run on paste.
23
31
  */
24
- function shellSingleQuote(s) {
32
+ export function shellSingleQuote(s) {
25
33
  return `'${s.replace(/'/g, "'\\''")}'`;
26
34
  }
27
35
  /**
@@ -59,13 +67,24 @@ function isUnknownCodeContextError(stderr) {
59
67
  * so we fail toward creating the memory (unscoped) rather than not at all.
60
68
  */
61
69
  export function createNamedMemory(opts) {
62
- const { name, content, conversationId = 'NEW', topics, codeContext } = opts;
70
+ const { name, content, topics, codeContext } = opts;
71
+ // COERCE AT THE SINK, where the argv element is built. A destructuring default
72
+ // fires on `undefined` only, so `conversationId: ''` satisfied the type and was
73
+ // passed through as `--conversation-id ''`. Validating at the call site alone
74
+ // leaves this function accepting whatever a future caller hands it. `NEW` is
75
+ // now the value for undefined, empty, malformed and out-of-range alike.
76
+ const conversationId = asConversationId(opts.conversationId) ?? 'NEW';
63
77
  const baseArgs = [
64
78
  'memories',
65
79
  'create',
66
80
  '--name', name,
67
81
  '--conversation-id', conversationId,
68
82
  '--content', content,
83
+ // EXPLICIT, and it must stay: without it the CLI falls back to
84
+ // `config.getFormat()`, whose shipped default is `table`. The id parser would
85
+ // then never see JSON on any host but one with json configured locally, and
86
+ // every id would come from a UUID scan over human text.
87
+ '--format', 'json',
69
88
  ];
70
89
  if (topics && topics.length > 0) {
71
90
  baseArgs.push('--topics', topics.join(','));
@@ -77,6 +96,7 @@ export function createNamedMemory(opts) {
77
96
  const args = hasCtx ? [...baseArgs, '--code-context', ctxJson] : baseArgs;
78
97
  let r = runCreate(args);
79
98
  let output = r.output;
99
+ let stdout = r.stdout;
80
100
  let ok = r.status === 0 && !r.error;
81
101
  // Older-mx downgrade: retry once WITHOUT --code-context on an unknown-option
82
102
  // error. Match stderr only (CWE-20) so echoed stdout content cannot trigger it.
@@ -85,20 +105,401 @@ export function createNamedMemory(opts) {
85
105
  `(upgrade mx to scope this memory)`));
86
106
  r = runCreate(baseArgs);
87
107
  output = r.output;
108
+ stdout = r.stdout;
88
109
  ok = r.status === 0 && !r.error;
89
110
  }
90
111
  // mx memories create --name exits non-zero even on success in some versions.
91
112
  // Fall back to verifying the memory exists if the command appeared to fail.
92
- if (!ok) {
93
- const verify = spawnSync('mx', ['memories', 'get', '--name', name], {
94
- stdio: 'pipe',
95
- encoding: 'utf-8',
96
- });
97
- if (verify.status === 0 && !verify.error) {
98
- ok = true;
113
+ //
114
+ // Through the shared reader: this call had no timeout, no killSignal and no
115
+ // --format json, which is the precise shape of the hang measured in
116
+ // memnexus#5482, sitting on the primary creation path.
117
+ if (!ok && readNamedMemoryJson(name).status === 'present') {
118
+ ok = true;
119
+ }
120
+ // The id lets the completion check verify THIS run's memory rather than any
121
+ // memory that happens to hold the name (#48). Two guards: stdout only, never
122
+ // diagnostics, and only from a create that REPORTED SUCCESS — an id quoted in a
123
+ // failure paragraph is not evidence that this run wrote anything. Null is a
124
+ // normal outcome on an older mx; the caller degrades to the pre-existence probe.
125
+ //
126
+ // `conversationId` is read under the same two guards, and it is what lets the
127
+ // caller put a team's three seeds in one conversation (#93). Null is normal;
128
+ // the caller then passes `NEW`, never an empty string.
129
+ return {
130
+ ok,
131
+ output: output.trim(),
132
+ id: ok ? parseCreatedMemoryId(stdout) : null,
133
+ conversationId: ok ? parseCreatedConversationId(stdout) : null,
134
+ };
135
+ }
136
+ // -- Named memory existence -------------------------------------------
137
+ /**
138
+ * How long a single `mx memories get` may take before the check gives up. ONE
139
+ * ceiling for every read in this module — the by-name reader and the by-id
140
+ * verifier had 15 s and 30 s, which is two answers to one question.
141
+ *
142
+ * `mx` normally answers in well under a second. The ceiling exists because
143
+ * provisioning must not hang on it: a stalled read would leave the operator
144
+ * staring at a created worktree with no verdict. Matches the `timeout -s KILL 30 mx`
145
+ * practice `AGENTS.md` sets for interactive use.
146
+ */
147
+ const MEMORY_GET_TIMEOUT_MS = 30_000;
148
+ /** Output ceiling for one `mx memories get`. Node's default is 1 MiB; a leader-state
149
+ * memory with a long iteration table can pass that, and ENOBUFS would then read as
150
+ * "could not run" for a memory that exists. */
151
+ const MEMORY_GET_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
152
+ /** Strip control characters and cap length: mx output is printed back to a terminal. */
153
+ function safeDetail(text, maxLength = 200) {
154
+ const printable = text.replace(/[\u0000-\u001F\u007F]/g, ' ').trim();
155
+ // REDACT, not just strip. This text is mx output on its way to a terminal, a
156
+ // row block, a PR body and CI logs. mx relays server message bodies verbatim,
157
+ // and an echoing endpoint can put an Authorization header into one, so the
158
+ // redaction belongs at the single point where the detail is built.
159
+ const redacted = redactSecrets(printable);
160
+ return redacted.length > maxLength ? `${redacted.slice(0, maxLength)}...` : redacted;
161
+ }
162
+ /**
163
+ * Whether a named memory resolves, and why not when it does not.
164
+ *
165
+ * Used by the provisioning completion check (#48) to verify the three team
166
+ * memories AFTER creation, rather than trusting the create call's own exit code.
167
+ * `createNamedMemory` above already documents that some mx versions exit non-zero
168
+ * on success, which means its result is not evidence either way.
169
+ *
170
+ * `ok: false` covers two different outcomes: mx answered and the memory is not
171
+ * there, or mx could not be asked (not installed, not authenticated, timed out).
172
+ * `detail` keeps them apart, because collapsing could-not-run into failed is the
173
+ * defect `mx-agent-system/standards/fail-loud-standard.md` names. Neither proves
174
+ * the memory exists, so both are `ok: false`.
175
+ */
176
+ /**
177
+ * The memory id in whatever `mx memories create` printed, or null.
178
+ *
179
+ * STDOUT ONLY. The previous version was handed `stdout + stderr` and scanned the
180
+ * lot for any UUID, so a failed create whose error paragraph happened to quote an
181
+ * id — a conflict, a rate-limit notice, a stack trace — produced an "id minted by
182
+ * this run" that the completion check would then verify successfully. Diagnostics
183
+ * are not results.
184
+ *
185
+ * Defensive by design otherwise: the single-create JSON shape is not documented in
186
+ * `mx memories create --help`, so this tries JSON first (top level, then the two
187
+ * common wrappers) and falls back to a bare UUID in the text. A null return is a
188
+ * normal outcome, not an error — the caller degrades to the pre-existence probe
189
+ * rather than failing.
190
+ *
191
+ * `mx memories get --name <x> --format json` was inspected directly and returns a
192
+ * flat object carrying top-level `id` and `name`, which is what verification uses.
193
+ */
194
+ export function parseCreatedMemoryId(stdout) {
195
+ const trimmed = stdout.trim();
196
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
197
+ try {
198
+ const parsed = JSON.parse(trimmed);
199
+ for (const candidate of [
200
+ parsed?.id,
201
+ parsed?.memory?.id,
202
+ parsed?.data?.id,
203
+ ]) {
204
+ if (typeof candidate === 'string' && candidate.length > 0)
205
+ return candidate;
206
+ }
207
+ }
208
+ catch {
209
+ /* fall through to the text scan */
99
210
  }
100
211
  }
101
- return { ok, output: output.trim() };
212
+ const uuid = trimmed.match(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i);
213
+ return uuid ? uuid[0] : null;
214
+ }
215
+ /**
216
+ * `conv_` plus a UUID, measured at 41 characters (`.mx-qa-report-28.md:49`).
217
+ * Bounded at 64 because the combined argv already holds a seed content near
218
+ * 1 KB, and an unbounded element can exceed ARG_MAX and fail the spawn with
219
+ * E2BIG, which reports as a create failure with no useful reason.
220
+ *
221
+ * `(?![\s\S])` and not `$`: without the `m` flag `$` still matches BEFORE a
222
+ * final newline, so `/^conv_[A-Za-z0-9-]{1,80}$/.test('conv_abc\n')` is true and
223
+ * a value holding a trailing newline would reach a line the operator reads.
224
+ *
225
+ * The `conv_` prefix anchored at position 0 is the control that stops argument
226
+ * injection (CWE-88), and the quoting is not. `spawnSync` defaults `shell` to
227
+ * false, so `mx` parses the argv itself and a value of `--content` would be a
228
+ * flag-shaped token to its option parser.
229
+ */
230
+ const CONVERSATION_ID_RE = /^conv_[A-Za-z0-9_-]{1,64}(?![\s\S])/;
231
+ /** The value when it is shaped like a conversation id, else null. */
232
+ export function asConversationId(value) {
233
+ return typeof value === 'string' && CONVERSATION_ID_RE.test(value) ? value : null;
234
+ }
235
+ /**
236
+ * The conversation id in whatever `mx memories create` printed, or null.
237
+ *
238
+ * STDOUT ONLY, and only from a create that reported success, for the reasons
239
+ * `parseCreatedMemoryId` gives above. JSON only, which is one narrowing: `id`
240
+ * keeps a bare-UUID text scan because the create JSON shape was undocumented,
241
+ * while `conversationId` was measured as a top-level key on all three JSON
242
+ * commands (`.mx-qa-report-28.md`). A text scan would read echoed memory
243
+ * content, so there is none.
244
+ */
245
+ export function parseCreatedConversationId(stdout) {
246
+ const trimmed = stdout.trim();
247
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('['))
248
+ return null;
249
+ try {
250
+ const parsed = JSON.parse(trimmed);
251
+ for (const candidate of [
252
+ parsed?.conversationId,
253
+ parsed?.memory?.conversationId,
254
+ parsed?.data?.conversationId,
255
+ ]) {
256
+ const id = asConversationId(candidate);
257
+ if (id)
258
+ return id;
259
+ }
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ return null;
265
+ }
266
+ /**
267
+ * Whether `id` resolves AND carries `expectedName`.
268
+ *
269
+ * Existence by NAME cannot tell a memory this run created from one that was
270
+ * already there under the same name — a re-provision of a retired slug, or a name
271
+ * collision on the shared account, would read as a green row over a failed write.
272
+ * An id minted by this run's create call can.
273
+ */
274
+ export function namedMemoryResolvesById(id, expectedName) {
275
+ const r = spawnSync('mx', ['memories', 'get', id, '--format', 'json'], {
276
+ stdio: 'pipe',
277
+ encoding: 'utf-8',
278
+ timeout: MEMORY_GET_TIMEOUT_MS,
279
+ killSignal: 'SIGKILL',
280
+ maxBuffer: MEMORY_GET_MAX_BUFFER_BYTES,
281
+ });
282
+ // The same three-state classifier every other read uses: a read that could not
283
+ // be performed must not render as "the memory is not there".
284
+ const read = classifyNamedMemoryRead({
285
+ status: r.status,
286
+ stdout: r.stdout || '',
287
+ stderr: r.stderr || '',
288
+ spawnFailed: Boolean(r.error),
289
+ errorMessage: r.error?.message,
290
+ });
291
+ if (read.status === 'unknown') {
292
+ return { ok: false, detail: read.reason ?? 'mx could not be asked' };
293
+ }
294
+ if (read.status === 'absent') {
295
+ return { ok: false, detail: `id ${id} does not resolve` };
296
+ }
297
+ const name = read.body?.name;
298
+ if (name !== expectedName) {
299
+ return {
300
+ ok: false,
301
+ detail: `id resolves to name ${safeDetail(String(name), 80)}, expected ${expectedName}`,
302
+ };
303
+ }
304
+ return { ok: true, detail: '' };
305
+ }
306
+ export function namedMemoryExists(name) {
307
+ const read = readNamedMemoryJson(name);
308
+ if (read.status === 'present')
309
+ return { ok: true, detail: '' };
310
+ if (read.status === 'absent')
311
+ return { ok: false, detail: 'mx returned no such memory' };
312
+ return { ok: false, detail: read.reason ?? 'mx could not be asked' };
313
+ }
314
+ /**
315
+ * The `service` every seeded memory is scoped to.
316
+ *
317
+ * `service` names the surface a memory belongs to, and a team's roleguide picks
318
+ * it: `product-definition` for product, `team-provisioning` for bootstrap.
319
+ * Provisioning cannot read that value out of the roleguide. Both roleguides in
320
+ * this repo state their codeContext JSON outside the behavioral block
321
+ * (`bootstrap-leader.md:422`, block ends at 205; `product-leader.md:567`, block
322
+ * ends at 201), and `mx-agent.config.json` has no service field, so there is
323
+ * nothing cheap to regex. The seed therefore names the surface that WROTE it,
324
+ * which is provisioning, and the team's first session replaces the memory whole,
325
+ * codeContext included, with its roleguide's own value.
326
+ *
327
+ * Accepted consequence, time-boxed to that window: between creation and the first
328
+ * session every team's seeds carry this same value, so `service` does not tell two
329
+ * brand-new teams apart. `team` does, and it is on all three memories.
330
+ */
331
+ export const PROVISIONED_MEMORY_SERVICE = 'team-provisioning';
332
+ /**
333
+ * The shape a roleguide-derived suffix must hold before it becomes half a memory
334
+ * name.
335
+ *
336
+ * Hyphen-separated alphanumeric groups, so `watch-log` passes and `--`, `-foo`
337
+ * and `foo-` do not. `[a-z0-9-]+` alone accepts all three of those: it excludes
338
+ * only the empty string, and a name like `mx-agent-<slug>--foo` is one no
339
+ * roleguide means to write (security pre-ruling M2 check 3, re-check gap 4).
340
+ *
341
+ * No metacharacter survives this class, which is what lets the accepted value be
342
+ * concatenated into a memory name and a printed shell command without further
343
+ * quoting. `commands/create.ts` applies the same rule before this file sees it.
344
+ */
345
+ export const EXTRA_ANCHOR_SUFFIX_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
346
+ /**
347
+ * Resolve a spec by key, as a typed failure rather than an unchecked cast.
348
+ *
349
+ * The previous form was `specs.find((s) => s.key === key) as TeamMemorySpec`
350
+ * (`:753-754`), which returned `undefined` for an unknown key and then had
351
+ * `spec.name` read off it, so a key with no spec crashed with a TypeError
352
+ * instead of refusing. That was inert while the three keys were hardcoded and
353
+ * the union was closed. It is not inert now that the key list is derived from a
354
+ * file (security pre-ruling M4 on #190).
355
+ *
356
+ * Returns null, and never throws, so the caller decides what a missing spec
357
+ * means. Exported for the test that asserts exactly that.
358
+ */
359
+ export function specByKey(specs, key) {
360
+ return specs.find((s) => s.key === key) ?? null;
361
+ }
362
+ /** `YYYY-MM-DD HH:MM`, UTC. The stamp the leader-state header carries. */
363
+ function stampMinutes(now) {
364
+ return now.toISOString().slice(0, 16).replace('T', ' ');
365
+ }
366
+ /** `YYYY-MM-DD`, UTC. */
367
+ function stampDay(now) {
368
+ return now.toISOString().slice(0, 10);
369
+ }
370
+ /**
371
+ * Flatten a value that must occupy exactly one line of a seeded memory.
372
+ *
373
+ * Line breaks become spaces rather than being dropped, so the text a reader sees
374
+ * still holds every character that was in the path; what it cannot do is start a
375
+ * new `- Field: value` line that a memory parser would then read as a field.
376
+ */
377
+ function oneLineValue(value) {
378
+ return value.replace(/[\r\n]+/g, ' ').trim();
379
+ }
380
+ /**
381
+ * The leader-state seed: the block every roleguide prescribes, filled with the
382
+ * values a provisioning run knows.
383
+ *
384
+ * `mx-agent window` reads this memory through `parseLeaderState`
385
+ * (`lib/fleet-data.ts`), which resolves `unknown` for content it does not
386
+ * recognise and for any unedited `[a | b]` placeholder. The seed was one flat
387
+ * sentence, so every new team read as `unknown` from creation until a human
388
+ * rewrote the memory by hand (#6). Every line below is a real value for that
389
+ * reason: no placeholders, and `ok` because a team that has just been created is
390
+ * not blocked and is not waiting on anyone.
391
+ *
392
+ * The section headers are left empty on purpose. Provisioning knows what it
393
+ * built, not what the team is for, and a sentence nobody wrote under
394
+ * `What I Am Doing Now` reads as the team's own report of itself.
395
+ */
396
+ function leaderStateSeed(teamDisplayName, roleguide, catalogPath, now) {
397
+ // ONE LINE, at the sink. Both paths reach here from the command line, and a
398
+ // path is validated for where it RESOLVES, not for the bytes it holds, so a
399
+ // roleguide whose filename embeds a newline plus `- Iteration: PWNED` would
400
+ // add a line to this memory. Measured against the real parser before the fix:
401
+ // `parseLeaderState` returned iteration `PWNED-99`. Same shape as `safeDetail`
402
+ // above, which strips control characters from mx output for the same reason.
403
+ const linkage = `${oneLineValue(catalogPath)}, ${oneLineValue(roleguide)}`;
404
+ // The two paths are what provisioning knows. The team's own template
405
+ // (`roleguides/bootstrap-leader.md:479`) puts issue, PR and memory-id
406
+ // references on this line instead, and the first wholesale update replaces the
407
+ // whole memory, so these two paths stand only until the first session writes.
408
+ //
409
+ // ORDERING INVARIANT, load-bearing: the three fields `parseLeaderState` reads
410
+ // as claims — status, decision, finding — are emitted BEFORE any line built
411
+ // from an operator-supplied string, and the parser takes the FIRST match for
412
+ // each. So an injected line can add a field the reader already resolved but
413
+ // cannot overwrite it. Keep Linkage last in this block, and put no new
414
+ // operator-influenced line above it.
415
+ return [
416
+ `## ${teamDisplayName} Leader State, updated ${stampMinutes(now)}`,
417
+ '',
418
+ '### Async Status Block',
419
+ '- Async status: ok',
420
+ '- Decision needed: none',
421
+ `- Last finding: none (provisioned ${stampDay(now)}, no session yet)`,
422
+ `- Linkage: ${linkage}`,
423
+ '',
424
+ '### Current Position',
425
+ '- Iteration: none',
426
+ '- Loop step: 0',
427
+ '- North star: not yet measured',
428
+ '',
429
+ '### What I Just Did',
430
+ '',
431
+ '### What I Am Doing Now',
432
+ '',
433
+ '### What Is Next',
434
+ '',
435
+ '### Key Numbers This Iteration',
436
+ '',
437
+ '### Open Decisions',
438
+ '',
439
+ '### Degradation Signals',
440
+ '',
441
+ ].join('\n');
442
+ }
443
+ /**
444
+ * The iteration-log seed: the rolling-window preamble and the empty table.
445
+ *
446
+ * The preamble is the one every team's log carries, because a named memory caps
447
+ * near 2000 words and an unbounded log hits that ceiling silently (#17).
448
+ */
449
+ function iterationLogSeed(teamDisplayName, now) {
450
+ return [
451
+ `## ${teamDisplayName} Iteration Log, updated ${stampDay(now)}`,
452
+ '',
453
+ 'Rolling window: keep the last 10 iterations here and give every iteration its own discrete memory, ' +
454
+ 'so nothing is lost when a row rolls out. Named memories cap near 2000 words ' +
455
+ '(`mx-agent-system/agent-config/agents/memory-creator.md:53`), which is why this list is bounded.',
456
+ '',
457
+ '| Iteration | Fix | North Star Before | North Star After | human_intervention | measurable_outcome | Status | PRs |',
458
+ '|---|---|---|---|---|---|---|---|',
459
+ '',
460
+ 'Total iterations completed: 0.',
461
+ '',
462
+ ].join('\n');
463
+ }
464
+ /** The known-issues seed: the open-items-only preamble and an empty list. */
465
+ function knownIssuesSeed(teamDisplayName, now) {
466
+ return [
467
+ `## ${teamDisplayName} Known Issues, updated ${stampDay(now)}`,
468
+ '',
469
+ 'Open items only; a resolved item moves to the footer with a pointer to its record. Written by the ' +
470
+ 'team lead from evidence gathered directly or reported by a named agent.',
471
+ '',
472
+ 'No open items at provisioning time. The first session populates this list.',
473
+ '',
474
+ ].join('\n');
475
+ }
476
+ /**
477
+ * The seed for an anchor the roleguide's table names beyond the three.
478
+ *
479
+ * GENERATED FROM THE SUFFIX, never from the table's Content cell (security
480
+ * pre-ruling S5 on #190). The Content column is prose written for whoever reads
481
+ * the roleguide; treating it as a template would put an unbounded string into a
482
+ * memory that caps near 2000 words, where it truncates silently (#17).
483
+ *
484
+ * Provisioning knows the anchor's name and nothing else about it, so the body
485
+ * says that and stops. The same reasoning as `leaderStateSeed`'s empty section
486
+ * headers: a sentence nobody wrote reads as the team's own report of itself.
487
+ *
488
+ * `suffix` reaches here only after `EXTRA_ANCHOR_SUFFIX_RE`, so it holds no
489
+ * markdown or shell metacharacter and no line break.
490
+ */
491
+ function extraAnchorSeed(teamDisplayName, suffix, name, now) {
492
+ const title = suffix.split('-').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
493
+ return [
494
+ `## ${teamDisplayName} ${title}, updated ${stampDay(now)}`,
495
+ '',
496
+ `Named memory anchor \`${name}\`. The team's roleguide names it in the Named Memory Anchors ` +
497
+ 'table, so provisioning created it; what it holds is the team\'s to write. Named memories cap ' +
498
+ 'near 2000 words, so keep this one bounded and give anything longer its own discrete memory.',
499
+ '',
500
+ 'No entries at provisioning time. The first session populates this memory.',
501
+ '',
502
+ ].join('\n');
102
503
  }
103
504
  /**
104
505
  * The three standard team-bootstrap memories (name + initial content) — the
@@ -106,30 +507,79 @@ export function createNamedMemory(opts) {
106
507
  * and `logManualMemoryCommands` (which prints ready-to-paste create commands when
107
508
  * automatic creation is skipped or fails). Keeping one definition guarantees the
108
509
  * printed fallback commands write exactly what the successful path would have.
510
+ *
511
+ * The same seed shape is written in prose in `roleguides/team-builder.md` step
512
+ * 6c, the manual path a team-builder session follows when it seeds by hand. Edit
513
+ * both together, and regenerate the embedded copy in `templates.ts` with
514
+ * `scripts/sync-team-builder-roleguide.mjs` (`template-sync.test.ts` fails on
515
+ * drift).
109
516
  */
110
- export function teamMemorySpecs(teamSlug, teamDisplayName, roleguide, projectSlug = '') {
517
+ export function teamMemorySpecs(teamSlug, teamDisplayName, roleguide, projectSlug = '', opts = {}) {
111
518
  const prefix = projectSlug ? `${projectSlug}-` : '';
519
+ const now = opts.now ?? new Date();
520
+ const catalogPath = opts.catalogPath ?? `${PROJECT_CONFIG_DEFAULTS.teamsDir}/${teamSlug}.md`;
521
+ const codeContext = {
522
+ product: projectSlug,
523
+ service: PROVISIONED_MEMORY_SERVICE,
524
+ team: teamSlug,
525
+ role: 'team-lead',
526
+ };
112
527
  return [
113
528
  {
114
529
  key: 'leaderState',
115
530
  name: `${prefix}${teamSlug}-leader-state`,
116
- content: `${teamDisplayName} team leader state — initialized. Roleguide: ${roleguide}. First session: read roleguide, check memories, begin iteration 1.`,
117
- codeContext: { product: projectSlug, team: teamSlug, role: 'team-lead' },
531
+ content: leaderStateSeed(teamDisplayName, roleguide, catalogPath, now),
532
+ codeContext: { ...codeContext },
118
533
  },
119
534
  {
120
535
  key: 'iterationLog',
121
536
  name: `${prefix}${teamSlug}-iteration-log`,
122
- content: `${teamDisplayName} iteration log — initialized. No iterations completed yet.`,
123
- codeContext: { product: projectSlug, team: teamSlug },
537
+ content: iterationLogSeed(teamDisplayName, now),
538
+ codeContext: { ...codeContext },
124
539
  },
125
540
  {
126
541
  key: 'knownIssues',
127
542
  name: `${prefix}${teamSlug}-known-issues`,
128
- content: `${teamDisplayName} known issues — initialized. No known issues.`,
129
- codeContext: { product: projectSlug, team: teamSlug },
543
+ content: knownIssuesSeed(teamDisplayName, now),
544
+ codeContext: { ...codeContext },
130
545
  },
546
+ // APPENDED, so the three keep their positions. `logManualMemoryCommands`
547
+ // opens the conversation on index 0 and joins it from index 1, and
548
+ // `create.ts` reads rows 3 to 5 off the first three; both stay correct.
549
+ // Deduped against the three and against each other, because a table naming
550
+ // `leader-state` twice, or naming it again as an extra row, would otherwise
551
+ // build two specs for one name and probe it twice.
552
+ ...dedupeSuffixes(opts.extraAnchorSuffixes ?? []).map((suffix) => ({
553
+ key: `extra:${suffix}`,
554
+ name: `${prefix}${teamSlug}-${suffix}`,
555
+ content: extraAnchorSeed(teamDisplayName, suffix, `${prefix}${teamSlug}-${suffix}`, now),
556
+ codeContext: { ...codeContext },
557
+ })),
131
558
  ];
132
559
  }
560
+ /**
561
+ * The extra suffixes that survive shape and duplication checks, in caller order.
562
+ *
563
+ * Three suffixes are dropped rather than refused here: this function is not the
564
+ * gate. `commands/create.ts` refuses the whole table before anything is seeded
565
+ * (M1), and by the time a suffix reaches this file it has passed that gate. What
566
+ * remains is defence in depth for a future caller that forgets, and its failure
567
+ * mode must be "no memory built from unchecked text", not "a memory with a name
568
+ * nobody validated".
569
+ */
570
+ function dedupeSuffixes(suffixes) {
571
+ const taken = new Set(['leader-state', 'iteration-log', 'known-issues']);
572
+ const out = [];
573
+ for (const suffix of suffixes) {
574
+ if (!EXTRA_ANCHOR_SUFFIX_RE.test(suffix))
575
+ continue;
576
+ if (taken.has(suffix))
577
+ continue;
578
+ taken.add(suffix);
579
+ out.push(suffix);
580
+ }
581
+ return out;
582
+ }
133
583
  /**
134
584
  * The prefix every team memory in this repo is written under. Kept separate from
135
585
  * `projectSlug` on purpose: `projectSlug` configures the WRITE path (what a newly
@@ -140,10 +590,12 @@ export const FLEET_MEMORY_PREFIX = 'memnexus';
140
590
  /**
141
591
  * Leader-state memory names for a team, in the order a reader must probe them.
142
592
  *
143
- * The ordering is the fix for #4612. When `projectSlug` is unset — which is the
144
- * case in this repo, whose `mx-agent.config.json` carries only
145
- * `coordinationMode` — `teamMemorySpecs` derives the UNPREFIXED name
146
- * (`<team>-leader-state`). Readers probed that first and returned on first
593
+ * The ordering is the fix for #4612. When `projectSlug` is unset,
594
+ * `teamMemorySpecs` derives the UNPREFIXED name (`<team>-leader-state`). This
595
+ * repo is NOT that case: `mx-agent.config.json` sets `projectSlug` to
596
+ * `mx-agent`, so names here are prefixed and the ownership check in
597
+ * `bootstrapTeamMemories` compares `product` as well as `team`. The unset case
598
+ * is the one a consumer project hits. Readers probed that first and returned on first
147
599
  * success, so for the six teams that have both spellings live they resolved an
148
600
  * abandoned pre-migration memory. Three of those parsed as `status=ok` on
149
601
  * March/April 2026 content and were reported as current fleet health.
@@ -168,15 +620,216 @@ export function leaderStateNameCandidates(teamSlug, projectSlug = '') {
168
620
  * When set, keys become `<projectSlug>-<teamSlug>-leader-state` etc., preventing
169
621
  * collisions when multiple projects share the same MemNexus account.
170
622
  * Defaults to '' (no prefix — backwards compatible).
623
+ * @param opts - Seed-content inputs (catalog path for the Linkage line, clock).
171
624
  */
172
- export function bootstrapTeamMemories(teamSlug, teamDisplayName, roleguide, projectSlug = '') {
173
- const specs = teamMemorySpecs(teamSlug, teamDisplayName, roleguide, projectSlug);
174
- const byKey = (key) => specs.find((s) => s.key === key);
175
- const leaderState = createNamedMemory({ name: byKey('leaderState').name, content: byKey('leaderState').content, codeContext: byKey('leaderState').codeContext });
176
- const iterationLog = createNamedMemory({ name: byKey('iterationLog').name, content: byKey('iterationLog').content, codeContext: byKey('iterationLog').codeContext });
177
- const knownIssues = createNamedMemory({ name: byKey('knownIssues').name, content: byKey('knownIssues').content, codeContext: byKey('knownIssues').codeContext });
178
- return { leaderState, iterationLog, knownIssues };
625
+ export function bootstrapTeamMemories(teamSlug, teamDisplayName, roleguide, projectSlug = '', opts = {}) {
626
+ // `opts` is passed straight through, and the caller builds it ONCE: the seeds
627
+ // stamp a clock, so a second `teamMemorySpecs` call for the printed manual
628
+ // commands would otherwise print a different stamp from the one created.
629
+ const specs = teamMemorySpecs(teamSlug, teamDisplayName, roleguide, projectSlug, opts);
630
+ /**
631
+ * Probe BEFORE creating. This is the load-bearing half of attribution and the
632
+ * only half that does not depend on what `mx memories create` prints: if the
633
+ * name already resolves, no later read can tell this run's write from what was
634
+ * already there. Probing costs one sub-second read per memory.
635
+ */
636
+ const create = (key, conversation = 'NEW') => {
637
+ const spec = specByKey(specs, key);
638
+ // NO SPEC IS A REFUSAL, not a crash. `specByKey` returns null rather than
639
+ // casting `undefined` to a spec and letting the next line read `.name` off
640
+ // it (security pre-ruling M4 on #190). Reachable only when a caller passes a
641
+ // key `teamMemorySpecs` did not build — today that means a suffix
642
+ // `dedupeSuffixes` dropped — and it must report a failed creation, because a
643
+ // thrown TypeError here would abandon a provision run midway through
644
+ // seeding, which is the partial-seed state M1 exists to prevent.
645
+ if (!spec) {
646
+ return {
647
+ ok: false,
648
+ output: `no memory spec for key "${key}" — nothing was probed and nothing was created`,
649
+ id: null,
650
+ conversationId: null,
651
+ preExisting: false,
652
+ probeConclusive: false,
653
+ probeReason: 'no spec for this key',
654
+ };
655
+ }
656
+ // THREE-STATE, deliberately. `present` is the only reading that means the
657
+ // name was taken, and `unknown` is not evidence that it was free.
658
+ const probe = readNamedMemoryJson(spec.name);
659
+ // DO NOT CREATE OVER A TAKEN NAME. `mx memories create --name` is an UPSERT:
660
+ // on a name conflict the installed CLI falls into an auto-upsert branch and
661
+ // calls updateNamedMemory(name, { content, ... })
662
+ // (@memnexus-ai/cli/dist/commands/memories.js:1824-1880), so the seed content
663
+ // REPLACES whatever the memory held and bumps its version. Two consequences,
664
+ // both bad: a re-provision after a failed run bumps three versions every pass
665
+ // and can never turn the row green, and a slug that collides with a live team
666
+ // on the shared account overwrites that team's leader state with boilerplate.
667
+ // The probe already told us the name is taken; creating anyway is the one
668
+ // action that destroys data.
669
+ if (probe.status === 'present') {
670
+ // OWNERSHIP, from the body the probe already read. `team` must be this
671
+ // team, and `product` must be this project when one is configured. When it
672
+ // is not this team's memory, this run reads no value out of it at all.
673
+ const ctx = probe.body?.codeContext && typeof probe.body.codeContext === 'object' &&
674
+ !Array.isArray(probe.body.codeContext)
675
+ ? probe.body.codeContext
676
+ : null;
677
+ // UNCONFIRMED is its own answer. A memory that names no team does not say
678
+ // it is another team's; it says nothing, and the two are reported apart.
679
+ const ownership = ctx === null || typeof ctx.team !== 'string'
680
+ ? 'unconfirmed'
681
+ : projectSlug !== '' && typeof ctx.product !== 'string'
682
+ ? 'unconfirmed'
683
+ : ctx.team === teamSlug && (projectSlug === '' || ctx.product === projectSlug)
684
+ ? 'this-team'
685
+ : 'not-this-team';
686
+ const mine = ownership === 'this-team';
687
+ return {
688
+ ok: false,
689
+ output: 'name already taken — not created, because create over an existing name replaces its content',
690
+ id: null,
691
+ // Nothing was written, so this run put no memory in any conversation.
692
+ conversationId: null,
693
+ preExisting: true,
694
+ preExistingOwnership: ownership,
695
+ preExistingConversationId: mine ? asConversationId(probe.body?.conversationId) : null,
696
+ probeConclusive: true,
697
+ // Handed to the completion check so the row can say whether the memory
698
+ // standing in the way is usable. A run killed between the first create
699
+ // and the third leaves a leader-state behind; every later provision then
700
+ // refuses the name, correctly, and the operator was told only that the
701
+ // name was taken. If that leftover is malformed it is the #6 symptom by
702
+ // another route, and it takes a hand edit to clear either way.
703
+ preExistingRead: { content: probe.content, codeContext: probe.body?.codeContext },
704
+ };
705
+ }
706
+ const result = createNamedMemory({
707
+ name: spec.name,
708
+ content: spec.content,
709
+ codeContext: spec.codeContext,
710
+ // Always a non-empty string: 'NEW' by default, and the caller only passes
711
+ // a value `asConversationId` accepted. `createNamedMemory` checks it again
712
+ // at the sink, so an empty or malformed value becomes 'NEW' there too.
713
+ conversationId: conversation,
714
+ });
715
+ // `present` returned above, so the name was not taken at probe time: absent
716
+ // (positively established) or unknown (no verdict). tsc enforces that.
717
+ return {
718
+ ...result,
719
+ preExisting: false,
720
+ probeConclusive: probe.status !== 'unknown',
721
+ probeReason: probe.status === 'unknown' ? probe.reason : undefined,
722
+ };
723
+ };
724
+ // ORDER, and it is the point of the function now. The leader-state create is
725
+ // what opens the conversation; the other two join it. Before this the three
726
+ // creates each defaulted to `NEW`, so one team's seeds landed in three
727
+ // conversations and no retrieval of one surfaced the other two (#93).
728
+ const leaderState = create('leaderState');
729
+ // RE-PROVISION. When the leader-state name is taken, this run created nothing,
730
+ // so it has no conversation of its own. It uses the standing memory's, and only
731
+ // when that memory is this team's. A run killed between the first create and
732
+ // the third then converges on one conversation on the next run, instead of
733
+ // reproducing the split, and a name that collided with another team's memory
734
+ // groups nothing with that team.
735
+ const thread = (() => {
736
+ if (!leaderState.preExisting) {
737
+ const id = asConversationId(leaderState.conversationId);
738
+ return id
739
+ ? { id, outcome: 'threaded-by-this-run' }
740
+ : { id: null, outcome: 'create-returned-no-conversation-id' };
741
+ }
742
+ if (leaderState.preExistingOwnership !== 'this-team') {
743
+ return {
744
+ id: null,
745
+ outcome: leaderState.preExistingOwnership === 'not-this-team'
746
+ ? 'standing-leader-state-is-not-this-team'
747
+ : 'standing-leader-state-ownership-unconfirmed',
748
+ };
749
+ }
750
+ const id = asConversationId(leaderState.preExistingConversationId);
751
+ return id
752
+ ? { id, outcome: 'threaded-onto-the-standing-leader-state' }
753
+ : { id: null, outcome: 'standing-leader-state-has-no-conversation-id' };
754
+ })();
755
+ // The only two values that reach `--conversation-id` from here are a validated
756
+ // `conv_` string and the literal 'NEW'. `createNamedMemory` checks again at
757
+ // the sink.
758
+ const follower = thread.id ?? 'NEW';
759
+ const iterationLog = create('iterationLog', follower);
760
+ const knownIssues = create('knownIssues', follower);
761
+ // ANCHORS FOUR AND BEYOND, on the same conversation and through the same
762
+ // `create` closure (security pre-ruling M3 and M5 on #190). Same probe, same
763
+ // three-state reading, same ownership classification, same refusal on a taken
764
+ // name. There is deliberately no second call site for `createNamedMemory`:
765
+ // `mx memories create --name` is an upsert, and a direct create for "just the
766
+ // extras" would lose every one of those protections at the one place the name
767
+ // came from a file rather than from this module.
768
+ //
769
+ // Read off `specs`, not off `opts.extraAnchorSuffixes`, so the list this loop
770
+ // walks is exactly the list `teamMemorySpecs` built — a suffix
771
+ // `dedupeSuffixes` dropped is never probed.
772
+ const extras = specs
773
+ .filter((s) => s.key.startsWith('extra:'))
774
+ .map((spec) => ({
775
+ suffix: spec.key.slice('extra:'.length),
776
+ name: spec.name,
777
+ creation: create(spec.key, follower),
778
+ }));
779
+ // RECONCILE, rather than assert from the first create. Passing an id to calls
780
+ // two and three is a request, and the result claims where three memories ARE.
781
+ // Two ways the request does not hold. A follower create fails, so its memory
782
+ // was never written and a later run creates it somewhere else. Or a follower
783
+ // succeeds and reports a different conversation, which is the service
784
+ // declining the one it was given.
785
+ //
786
+ // A follower that reports no conversation at all is not counted against the
787
+ // claim: an older mx prints no such key, and the leader-state create had the
788
+ // same gap covered by `create-returned-no-conversation-id`.
789
+ //
790
+ // EVERY follower, not the two the three-anchor version enumerated. With a
791
+ // fourth anchor a fixed pair would report `conversationThreaded: true` while
792
+ // that anchor sat in its own conversation, which is #93 returning silently
793
+ // (security pre-ruling M5 on #190). The list is built once and reused, so the
794
+ // claim and the count cannot drift.
795
+ const followers = [iterationLog, knownIssues, ...extras.map((e) => e.creation)];
796
+ const followersJoined = thread.id !== null &&
797
+ followers.every((c) => c.ok && (c.conversationId === null || c.conversationId === thread.id));
798
+ const threaded = thread.id !== null && followersJoined;
799
+ return {
800
+ leaderState,
801
+ iterationLog,
802
+ knownIssues,
803
+ extras,
804
+ conversationThreaded: threaded,
805
+ conversationId: threaded ? thread.id : null,
806
+ conversationOutcome: threaded ? thread.outcome : (
807
+ // The first create gave a conversation and the followers did not join it.
808
+ // That is a different outcome from never having one to give, and it is the
809
+ // one an operator has to act on: two memories exist somewhere else.
810
+ thread.id !== null ? 'follower-create-rejected-the-conversation' : thread.outcome),
811
+ };
179
812
  }
813
+ /**
814
+ * The stand-in for the conversation id in the printed commands.
815
+ *
816
+ * Two properties, both required. It holds no shell metacharacter, because the
817
+ * line it appears on is printed for a human to paste into a shell: `<conv_ from
818
+ * the first command>` reads as a stdin redirect and a stdout redirect that
819
+ * truncates a file named `command`, and the paste then writes a file instead of
820
+ * creating a memory.
821
+ *
822
+ * It does not begin `conv_`, because a placeholder that looks like an id is one
823
+ * a reader pastes without replacing, and one that would pass
824
+ * `asConversationId`. All-caps with underscores reads as a slot to fill and
825
+ * fails that check.
826
+ *
827
+ * It is spelled differently from the `conv_xyz` in `roleguides/team-builder.md`
828
+ * step 6c on purpose. That block is a `create_memory({...})` call, not a shell
829
+ * command line, so a literal paste there sends the string to the service rather
830
+ * than running a redirect.
831
+ */
832
+ export const CONVERSATION_ID_PLACEHOLDER = 'PASTE_CONVERSATION_ID_FROM_STEP_1';
180
833
  /**
181
834
  * Print ready-to-paste `mx memories create` commands for the three team
182
835
  * memories. Used when automatic initialisation is skipped (mx CLI missing) or
@@ -185,17 +838,46 @@ export function bootstrapTeamMemories(teamSlug, teamDisplayName, roleguide, proj
185
838
  * have written plus the team's codeContext. Printed output only; creates nothing.
186
839
  */
187
840
  export function logManualMemoryCommands(specs) {
188
- for (const spec of specs) {
841
+ specs.forEach((spec, idx) => {
189
842
  // Same serializer auto-create uses — printer and auto-create cannot drift.
190
843
  const codeContext = codeContextJson(spec.codeContext);
191
- // Single-quote content + codeContext so an embedded $(...)/backtick in the
192
- // (unvalidated) roleguide path is inert when the command is pasted (CWE-78).
193
- console.log(chalk.dim(` mx memories create --name ${spec.name} --conversation-id NEW ` +
844
+ // The first command opens the conversation; the other two join it, which is
845
+ // the order `roleguides/team-builder.md` step 6c prescribes and the order the
846
+ // automated path now follows. The banner printed `NEW` three times, so an
847
+ // operator who pasted it got the split the code path was fixed to stop.
848
+ // Quoted with the same helper the other fields use, so the pasted line holds
849
+ // one inert token wherever the id goes.
850
+ const conversation = idx === 0 ? 'NEW' : shellSingleQuote(CONVERSATION_ID_PLACEHOLDER);
851
+ if (idx === 1) {
852
+ // Between the commands, not above them: this is the one line an operator
853
+ // has to act on, and the placeholder is on the two lines below it. Printed
854
+ // undimmed so it is not read as more command text.
855
+ console.log(chalk.yellow(` # Replace ${CONVERSATION_ID_PLACEHOLDER} below with the conversationId the ` +
856
+ 'command above printed. The three memories belong in one conversation.'));
857
+ }
858
+ // Single-quote NAME, content and codeContext so an embedded metacharacter is
859
+ // inert when the command is pasted (CWE-78). The name was the one field left
860
+ // bare, and it is built from `projectSlug`, which reaches here less validated
861
+ // than the team slug does: `SLUG_RE` in create.ts constrains the team slug,
862
+ // while `validateProjectConfig` only denies a metacharacter list, so a
863
+ // projectSlug of `a b*` is accepted by config load and word-splits and globs
864
+ // in an unquoted paste. Quoting the field costs nothing and does not depend
865
+ // on which denylist upstream happens to hold.
866
+ console.log(chalk.dim(` mx memories create --name ${shellSingleQuote(spec.name)} --conversation-id ${conversation} ` +
194
867
  `--content ${shellSingleQuote(spec.content)} --code-context ${shellSingleQuote(codeContext)}`));
195
- }
868
+ });
196
869
  }
197
870
  /**
198
871
  * Log the result of a memory creation step.
872
+ *
873
+ * "run manually" is printed ONLY for a genuine create failure (#493). The manual
874
+ * action for a memory is `mx memories create --name`, which UPSERTS: on a taken
875
+ * name it replaces the standing memory's content. So a taken name must never be
876
+ * reported with that instruction, whoever the memory belongs to. The taken-name
877
+ * branch of `bootstrapTeamMemories` returns `ok: false` with `preExisting: true`
878
+ * and `preExistingOwnership` set, and those two fields decide the line here.
879
+ * Whether a this-team memory is usable or malformed is the completion rows' job,
880
+ * not this line's, so the line claims neither.
199
881
  */
200
882
  export function logMemoryResult(label, result) {
201
883
  if (result.ok) {
@@ -204,6 +886,28 @@ export function logMemoryResult(label, result) {
204
886
  console.log(chalk.dim(` ${result.output.split('\n')[0]}`));
205
887
  }
206
888
  }
889
+ else if (result.preExisting === true) {
890
+ if (result.preExistingOwnership === 'this-team') {
891
+ // This team's own memory from an earlier run. Nothing failed and nothing
892
+ // is to be done by hand; rows 3-5 of the completion check give its verdict.
893
+ console.log(chalk.cyan(` • ${label} (already present, not created; the completion rows below give its verdict)`));
894
+ }
895
+ else if (result.preExistingOwnership === 'not-this-team') {
896
+ // Another team's or another project's memory. Still yellow: the operator
897
+ // has a name collision to resolve, just never by creating over it.
898
+ console.log(chalk.yellow(` ⚠ ${label} (not created: the name is held by another team's memory; do not create over it)`));
899
+ }
900
+ else {
901
+ // `unconfirmed`, and also a taken name with no ownership recorded at all.
902
+ // The PRD (#494) does not name the second case; `bootstrapTeamMemories`
903
+ // always sets ownership alongside preExisting. Defaulting to the
904
+ // unconfirmed wording keeps "run manually" off every taken name.
905
+ console.log(chalk.yellow(` ⚠ ${label} (not created: the name is taken and its owner is unconfirmed; do not create over it)`));
906
+ }
907
+ if (result.output) {
908
+ console.log(chalk.dim(` ${result.output.split('\n')[0]}`));
909
+ }
910
+ }
207
911
  else {
208
912
  console.log(chalk.yellow(` ⚠ ${label} (failed — run manually)`));
209
913
  if (result.output) {
@@ -324,7 +1028,7 @@ export function classifyNamedMemoryRead(res) {
324
1028
  status: 'unknown',
325
1029
  content: '',
326
1030
  exitCode: res.status,
327
- reason: `mx could not be run${res.errorMessage ? `: ${redactSecrets(res.errorMessage).slice(0, 160)}` : ''}`,
1031
+ reason: `mx could not be run${res.errorMessage ? `: ${safeDetail(res.errorMessage, 160)}` : ''}`,
328
1032
  };
329
1033
  }
330
1034
  if (res.status === 0) {
@@ -451,7 +1155,10 @@ function firstMeaningfulLine(stderr) {
451
1155
  .split('\n')
452
1156
  .map((l) => l.replace(/^[-\\|/\s✔✖❌⚠]+/, '').trim())
453
1157
  .find((l) => l.length > 0);
454
- return line ? redactSecrets(line).slice(0, 160) : '';
1158
+ // safeDetail, not redactSecrets alone: this string is printed to a terminal by
1159
+ // the provisioning row block, and mx stderr can carry escape sequences that a
1160
+ // terminal would interpret rather than display. Strip, redact, cap — one call.
1161
+ return line ? safeDetail(line, 160) : '';
455
1162
  }
456
1163
  /**
457
1164
  * Read a named memory's structured JSON, three-state (see `NamedMemoryRead`).
@@ -465,8 +1172,14 @@ export function readNamedMemoryJson(name) {
465
1172
  const result = spawnSync('mx', ['memories', 'get', '--name', name, '--format', 'json'], {
466
1173
  stdio: 'pipe',
467
1174
  encoding: 'utf-8',
468
- timeout: 15000,
469
- maxBuffer: 1024 * 1024,
1175
+ timeout: MEMORY_GET_TIMEOUT_MS,
1176
+ // SIGTERM is spawnSync's default and the installed mx was measured ignoring
1177
+ // it (memnexus#5482), so without this a hung read outlives its own timeout.
1178
+ killSignal: 'SIGKILL',
1179
+ // Raised from 1 MiB: a leader-state memory with a long iteration table
1180
+ // passes that, and ENOBUFS would then classify as `unknown` for a memory
1181
+ // that is merely large.
1182
+ maxBuffer: MEMORY_GET_MAX_BUFFER_BYTES,
470
1183
  });
471
1184
  return classifyNamedMemoryRead({
472
1185
  status: result.status,