@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
@@ -13,8 +13,13 @@
13
13
  * (.mx-coordination-team). It is NEVER derived from CLAUDE_TEAM_NAME
14
14
  * or the worktree name. The PROJECT is the committed project-config
15
15
  * signal (resolveProductSlug), never a queue-mode client assertion.
16
- * - SF-2 The (project, team) is validated against the per-project roster
17
- * BEFORE any `az` call. A non-member fails CLOSED (no fetch).
16
+ * - SF-2 For a Key Vault project the (project, team) is validated against the
17
+ * per-project roster BEFORE any `az` call; a non-member fails CLOSED
18
+ * (no fetch). For a credential-endpoint project (#288) the SERVICE's
19
+ * grant table is that gate: it answers a byte-identical 403 to an
20
+ * identity holding no grant, so the offline roster file is not
21
+ * consulted and cannot refuse a team the service admits. The #220
22
+ * interlock runs in its place, BEFORE any network call.
18
23
  * - MF-1 The token cache filename embeds BOTH slugs
19
24
  * (.mx-coordination-token--<project>--<team>), per worktree. A worktree
20
25
  * recycled to a different team/project can never read another tenant's
@@ -27,6 +32,21 @@
27
32
  * report "unprovisioned" so the caller degrades, never crash.
28
33
  * - Fail-CLOSED only on a roster mismatch.
29
34
  *
35
+ * THE PROJECT SWITCH (#288, C3 of #164; inverted by #507). Every project
36
+ * obtains its team token by presenting the operator's MemNexus user key to POST
37
+ * /admin/credential on the coordination service, except the two named in
38
+ * KEY_VAULT_PROJECTS, `memnexus` and `spearmint-private`, which keep the Key
39
+ * Vault path byte for byte. The switch is KEY_VAULT_PROJECTS below and nothing
40
+ * else in this file branches on a project name. What is identical on both paths: the per-worktree cache
41
+ * (filename with both slugs, born 0600, same location), the
42
+ * MX_COORD_SERVICE_TOKEN env/config short-circuit, the `.mx-coordination-team`
43
+ * marker read, and the refresh path's fetch-first / delete-only-on-success order.
44
+ *
45
+ * THE USER KEY. Read where the `mx` CLI keeps it, by defaultReadUserKey below,
46
+ * and placed in exactly one request header. It is never logged, never cached,
47
+ * never stored, never included in an error, a `--verbose` line, a doctor row or
48
+ * an observability payload, and its length is never reported.
49
+ *
30
50
  * ROTATION RECOVERY (#4970): resolveCoordinationToken serves the per-worktree
31
51
  * cache unconditionally, so a rotated secret would be presented forever. The
32
52
  * companion refreshCoordinationToken() deletes that cache and refetches from the
@@ -42,10 +62,11 @@
42
62
  * vault; Phase 2 renames the secrets and the fallback is removed.
43
63
  */
44
64
  import { execFileSync } from 'node:child_process';
45
- import { existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
65
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, rmSync, statSync, writeFileSync, } from 'node:fs';
46
66
  import { join } from 'node:path';
47
67
  import { getConfigValue } from './config.js';
48
- import { CONFIG_KEY_TOKEN } from './coordination-client.js';
68
+ import { CONFIG_KEY_TOKEN, DEFAULT_HTTP_TIMEOUT_MS, URL_SOURCE_LABEL, projectUrlValidationError, resolveCoordinationUrl, } from './coordination-client.js';
69
+ import { validateCoordinationServiceUrl, COORDINATION_CREDENTIAL_SUFFIX_CONFIG_KEY, } from './project-config.js';
49
70
  import { resolveProductSlug, DEFAULT_PRODUCT_SLUG } from './coordination-memory.js';
50
71
  import { isValidProjectSlug, invalidProjectSlugMessage } from './slug.js';
51
72
  /**
@@ -69,6 +90,164 @@ const BUILTIN_ROSTERS = {
69
90
  [DEFAULT_PRODUCT_SLUG]: COORD_ROSTER,
70
91
  };
71
92
  export const KEYVAULT_NAME = 'mx-dev-eastus2-kv-001';
93
+ // ── The project switch (#288, C3 of #164; a denylist since #507) ─────────────
94
+ //
95
+ // This module is shared code. Its identity is (project, team). Until #507 the
96
+ // switch was an allowlist: only `mx-agent` and `mx-agent-test` used POST
97
+ // /admin/credential, and every other project, including one created the day
98
+ // before, needed a Key Vault secret per team. #507 lets the coordination
99
+ // service create a new project and its teams on the first authenticated
100
+ // credential request, so the default flips: every project uses the credential
101
+ // endpoint except the two whose tokens live in Key Vault today. KEYVAULT_NAME,
102
+ // the `az` invocation and the KV secret-name helpers below stay for those two.
103
+ //
104
+ // Moving a project off Key Vault is removing one entry here. Nothing else in
105
+ // this file branches on a project name, so the switch is one reviewable
106
+ // expression.
107
+ /**
108
+ * The projects whose teams obtain a coordination token from Key Vault. Every
109
+ * other project uses POST /admin/credential.
110
+ *
111
+ * `memnexus` and `spearmint-private` have per-team secrets in Key Vault and are
112
+ * served by deployments that hold no grants for them, so sending their sessions
113
+ * to the credential endpoint would break them. `mx-agent` and `mx-agent-test`
114
+ * are NOT here: the service is deployed by this repository and holds their
115
+ * grants, and no secret is created for the test team in any vault (#259).
116
+ *
117
+ * NO OPERATOR AUTHORISES THE TEST TEAM. Its first credential request enrols it:
118
+ * the service finds no grant, sees the compiled test partition, writes a grant
119
+ * to the requesting identity labelled `auto-enrolled:test-partition`, and
120
+ * issues the token (`coordination-service/src/server/credential-routes.ts`,
121
+ * `isTestPartitionTeam` in that package's config/rosters.ts). Nothing on this
122
+ * side of the wire changes for it: the CLI makes the same request it makes for
123
+ * every `mx-agent` team, and a 403 still means what it has always meant.
124
+ */
125
+ export const KEY_VAULT_PROJECTS = ['memnexus', 'spearmint-private'];
126
+ /** Whether this project takes the credential-endpoint path instead of Key Vault. */
127
+ export function usesCredentialEndpoint(project) {
128
+ return !KEY_VAULT_PROJECTS.includes(project);
129
+ }
130
+ /**
131
+ * The largest 200 body this client will read (#290 Should Fix 2).
132
+ *
133
+ * A credential response is a few hundred bytes. Without a cap, `res.json()` reads
134
+ * whatever the peer sends, and the abort timer used to be cleared as soon as the
135
+ * headers arrived, so a slow unbounded body had neither a deadline nor a size
136
+ * limit. The timer now covers the body read as well, and is cleared once.
137
+ */
138
+ const MAX_CREDENTIAL_BODY_BYTES = 64 * 1024;
139
+ /** The credential route on the coordination service. */
140
+ export const CREDENTIAL_PATH = '/admin/credential';
141
+ /** The one header the MemNexus user key is ever placed in. */
142
+ export const USER_KEY_HEADER = 'x-mx-user-key';
143
+ /** Env name the `mx` CLI reads first for the operator's MemNexus user key. */
144
+ export const ENV_KEY_USER_KEY = 'MX_API_KEY';
145
+ /** The configstore id the `mx` CLI writes its config under (its package name). */
146
+ const MX_CLI_PACKAGE_NAME = '@memnexus-ai/cli';
147
+ /**
148
+ * Env var naming the team this session asserts it is. Non-secret interlock
149
+ * state, already set by the session-start hook and by prepareClient.
150
+ */
151
+ export const ENV_KEY_EXPECT_TEAM = 'MX_COORD_EXPECT_TEAM';
152
+ /** Companion for the project half of the asserted identity (#220). */
153
+ export const ENV_KEY_EXPECT_PROJECT = 'MX_COORD_EXPECT_PROJECT';
154
+ /**
155
+ * The CLI's word for a 401. It names the KEY and says nothing about the team,
156
+ * because at a 401 the service has not looked at the team yet.
157
+ */
158
+ export const CREDENTIAL_INVALID_KEY_DETAIL = 'the coordination service rejected the MemNexus user key this worktree presented. ' +
159
+ 'That is a statement about the key alone. ' +
160
+ 'Refresh it with `mx auth login`, or set MX_API_KEY.';
161
+ /**
162
+ * The CLI's word for a 403, fixed and identical for every team.
163
+ *
164
+ * The service answers a byte-identical 403 whether the team exists or not, so
165
+ * that a shared deployment is not an enumeration oracle (#164 criterion 1). The
166
+ * CLI must add no word that distinguishes the two cases, so this string is a
167
+ * constant: it names the missing grant and nothing else. Do not interpolate the
168
+ * team, the project, or any part of the response body into it.
169
+ *
170
+ * UNCHANGED BY AUTO-ENROLMENT, deliberately. A test-partition team is enrolled
171
+ * by the service on its first request, so this string reaching a test team means
172
+ * the service has no test roster or has not been redeployed. Wording that case
173
+ * differently would make the CLI's own message the enumeration oracle the
174
+ * service's byte-identical 403 exists to prevent, and the CLI cannot tell the
175
+ * two cases apart anyway: the 403 body is the same either way.
176
+ */
177
+ export const CREDENTIAL_NOT_AUTHORIZED_DETAIL = 'this identity is not authorized to hold a credential for the requested team: no grant exists for it. ' +
178
+ 'An operator creates one with POST /admin/grant on the coordination service.';
179
+ /**
180
+ * The CLI's word for a 503, a timeout, or an unreachable service. Never
181
+ * `unprovisioned`: a service that is down must not send an operator to mint or
182
+ * register anything, and it must not degrade silently.
183
+ */
184
+ export const CREDENTIAL_UNAVAILABLE_DETAIL = 'the coordination service is UNAVAILABLE for credential issuance right now (identity introspection is ' +
185
+ 'down or at its concurrency limit). This is not a rejection and not an unprovisioned team. ' +
186
+ 'Retry in a few seconds; if every retry answers the same way, the service needs an operator.';
187
+ /** The CLI's word for a 409, reachable only by a caller that HOLDS a grant. */
188
+ /**
189
+ * The CLI's word for a 429 (#507): the service refused to CREATE a project or
190
+ * team on login because a creation limit is reached. A refusal, not an outage,
191
+ * so it never says "retry in a few seconds".
192
+ *
193
+ * FIXED TEXT, like every refusal constant here: nothing from the response body
194
+ * is interpolated. The service's 429 body says which of the three limits was
195
+ * met; the CLI names all three, and the numbers are held equal to the service
196
+ * constants by a test in coordination-service (`create-on-login.test.ts`,
197
+ * MAX_PROJECTS_PER_OWNER, MAX_TEAMS_PER_SELF_CREATED_PROJECT,
198
+ * MAX_SELF_CREATED_PROJECTS_PER_WINDOW).
199
+ */
200
+ export const CREDENTIAL_LIMIT_REACHED_DETAIL = 'the coordination service refused to create this project or team on login: a creation limit is reached. ' +
201
+ 'The limits are 10 projects per identity, 50 teams per project, and 20 new projects across the service in 24 hours. ' +
202
+ 'This is a refusal, not an outage, and retrying soon will not help. ' +
203
+ 'An operator can create the project or team with POST /admin/provision, which these limits do not apply to.';
204
+ export const CREDENTIAL_NOT_REGISTERED_DETAIL = 'this identity holds a grant for the team, but the coordination service roster does not list it. ' +
205
+ 'Register the team on the service, then retry.';
206
+ /**
207
+ * Which suffix set the KEY-BEARING request is held to (#290, second delta).
208
+ *
209
+ * The built-in set, plus `coordination-credential-allowed-suffixes` and nothing
210
+ * else. Not `coordination-url-allowed-suffixes`, which governs ordinary
211
+ * coordination traffic, and not the source the URL came from.
212
+ *
213
+ * WHY NOT BY SOURCE, which is what the previous round did. That version honoured
214
+ * the ordinary extension when the URL came from the `project` source, on the
215
+ * reasoning that a committed repository file and an operator's own config are two
216
+ * independent parties. That reasoning was wrong, and was measured wrong: nothing
217
+ * on this path consults git. `resolveCoordinationUrl()` is called with no root,
218
+ * so it falls to `findProjectRoot()`, which returns `MX_PROJECT_ROOT` for ANY
219
+ * directory and otherwise the main worktree root, both writable by the uid the
220
+ * agent runs as. So the "project" file is a working-tree file an attacker can
221
+ * create and point at with one environment variable, and the second "party" is a
222
+ * file in $HOME under the same uid. There was one party.
223
+ *
224
+ * WHAT THE SPLIT DOES AND DOES NOT DO, stated so nobody rests on it twice. It
225
+ * does NOT stop an actor who can write `~/.mx-agent/config.json`: that actor can
226
+ * set the new key as easily as the old one, and can read the user key out of the
227
+ * configstore directly without involving this code at all. What it removes is the
228
+ * combination: an operator who widens the allowlist for a self-hosted service no
229
+ * longer thereby authorizes that host to receive a non-expiring user key, so a
230
+ * legitimate, already-present widening cannot be borrowed by anything that only
231
+ * controls the environment. Widening the credential path is now its own act.
232
+ */
233
+ function credentialSuffixReader() {
234
+ return () => {
235
+ try {
236
+ return getConfigValue(COORDINATION_CREDENTIAL_SUFFIX_CONFIG_KEY);
237
+ }
238
+ catch {
239
+ // A config read failure is not an extension.
240
+ return undefined;
241
+ }
242
+ };
243
+ }
244
+ /** No coordination service URL is configured, so no credential can be requested. */
245
+ export const CREDENTIAL_NO_URL_DETAIL = 'coordination service URL not set, so no credential can be requested. ' +
246
+ 'Set MX_COORD_SERVICE_URL, run `mx-agent config set coordination-service-url <https-url>`, ' +
247
+ 'or set coordinationServiceUrl in mx-agent.config.json.';
248
+ /** No MemNexus user key is available on this machine. The key itself is never named. */
249
+ export const CREDENTIAL_NO_USER_KEY_DETAIL = 'no MemNexus user key is available on this machine, so no credential can be requested. ' +
250
+ 'Run `mx auth login`, or set MX_API_KEY.';
72
251
  /** Env override for the offline roster file path (test seam / operator override). */
73
252
  export const ENV_KEY_ROSTER_FILE = 'MX_COORD_ROSTER_FILE';
74
253
  /** Repo-relative location of the committed generated offline roster file (ND-2). */
@@ -90,6 +269,12 @@ function legacyKvSecretName(team) {
90
269
  function cacheFileName(project, team) {
91
270
  return `.mx-coordination-token--${project}--${team}`;
92
271
  }
272
+ /** The rejected token stays on disk, so the next session is refused again, loudly. */
273
+ const REFRESH_STAYS_LOUD_CLAUSE = ' The rejected token was LEFT in the per-worktree cache on purpose, so this failure stays loud every session.';
274
+ /** No cached token exists, so the next session degrades with nothing on screen. */
275
+ const REFRESH_GOES_SILENT_CLAUSE = ' This worktree holds NO cached token to fail loudly with. NEEDS MANUAL ATTENTION BEFORE THE NEXT SESSION: ' +
276
+ 'the next session-start brief will find no cache, fail the same way, and exit silently with no output, so ' +
277
+ 'queued cross-team escalations will read as an empty inbox.';
93
278
  /** Default marker/cache reader: undefined on missing or unreadable file. */
94
279
  function defaultReadFileText(path) {
95
280
  try {
@@ -116,14 +301,222 @@ function defaultFetchSecret(vault, secretName) {
116
301
  return undefined;
117
302
  }
118
303
  }
304
+ /**
305
+ * The operator's MemNexus user key, read exactly where the `mx` CLI keeps it:
306
+ * `process.env.MX_API_KEY || store.get('apiKey')`
307
+ * (@memnexus-ai/cli/dist/lib/config.js:77). That store is a `configstore` built
308
+ * from the mx CLI's package name, which resolves to
309
+ * `<XDG_CONFIG_HOME or $HOME/.config>/configstore/<package name>.json`. The read
310
+ * is reproduced here rather than imported: the mx CLI is a separate package and
311
+ * is not a dependency of this one.
312
+ *
313
+ * NO-ECHO, and this is the whole of it. The returned value goes to ONE request
314
+ * header (USER_KEY_HEADER) in defaultFetchCredential and to nothing else. It is
315
+ * never logged, never written to the token cache or any other file, never put in
316
+ * an error, a `--verbose` line, an `mx-agent doctor` row, or an observability
317
+ * payload, and its length is never reported. Nothing downstream stores it: every
318
+ * caller passes it straight into the request and lets it go out of scope.
319
+ *
320
+ * Any failure is `undefined`, which the caller reports as "no user key", naming
321
+ * neither the file nor anything read from it.
322
+ */
323
+ function defaultReadUserKey(env) {
324
+ const fromEnv = env[ENV_KEY_USER_KEY];
325
+ if (typeof fromEnv === 'string' && fromEnv !== '')
326
+ return fromEnv;
327
+ const configHome = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : undefined);
328
+ if (!configHome)
329
+ return undefined;
330
+ const path = join(configHome, 'configstore', `${MX_CLI_PACKAGE_NAME}.json`);
331
+ let raw;
332
+ try {
333
+ if (!existsSync(path))
334
+ return undefined;
335
+ raw = readFileSync(path, 'utf-8');
336
+ }
337
+ catch {
338
+ return undefined;
339
+ }
340
+ try {
341
+ const parsed = JSON.parse(raw);
342
+ const key = parsed?.apiKey;
343
+ return typeof key === 'string' && key !== '' ? key : undefined;
344
+ }
345
+ catch {
346
+ return undefined;
347
+ }
348
+ }
349
+ /** The request timeout, from the same env var the coordination client reads. */
350
+ function credentialTimeoutMs(env) {
351
+ const raw = env.MX_COORD_HTTP_TIMEOUT_MS;
352
+ const parsed = raw ? Number.parseInt(raw, 10) : NaN;
353
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_HTTP_TIMEOUT_MS;
354
+ }
355
+ /**
356
+ * Read a response body with a hard byte ceiling, counting what actually arrives.
357
+ *
358
+ * #290 delta review 2. The header check alone trusted `content-length`, and a
359
+ * chunked response declares none, so `res.json()` was unbounded on exactly the
360
+ * responses a hostile peer controls. This counts decoded bytes as they arrive and
361
+ * cancels the stream the moment the ceiling is passed, so nothing beyond the
362
+ * limit is ever buffered.
363
+ *
364
+ * Returns null when the body is too large. Never throws.
365
+ */
366
+ async function readBoundedText(res, limit) {
367
+ const stream = res.body;
368
+ // No body to stream: `res.text()` here is UNCAPPED, and it is the one read on
369
+ // this path that is. It is not reachable on undici for a 200 that has a body
370
+ // (`res.body` is a stream whenever there is one), so it covers a bodyless
371
+ // response and a runtime that exposes no stream. If either ever changes, this
372
+ // is the line that needs the ceiling, and the header check above is the only
373
+ // bound it has.
374
+ if (!stream)
375
+ return res.text();
376
+ const reader = stream.getReader();
377
+ const decoder = new TextDecoder();
378
+ let total = 0;
379
+ let out = '';
380
+ for (;;) {
381
+ const { done, value } = await reader.read();
382
+ if (done)
383
+ break;
384
+ total += value.byteLength;
385
+ if (total > limit) {
386
+ await reader.cancel().catch(() => undefined);
387
+ return null;
388
+ }
389
+ out += decoder.decode(value, { stream: true });
390
+ }
391
+ out += decoder.decode();
392
+ return out;
393
+ }
394
+ /**
395
+ * POST /admin/credential, classified into the five outcomes.
396
+ *
397
+ * The response BODY is read on exactly one status: 200, for the token. A 401,
398
+ * 403 or 409 body is never read and never printed, so no server wording can
399
+ * reach the operator through this path and turn a deliberately-uniform 403 into
400
+ * a distinguishing message. A non-2xx contributes at most its numeric status.
401
+ */
402
+ async function defaultFetchCredential(req) {
403
+ const controller = new AbortController();
404
+ const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS);
405
+ let res;
406
+ try {
407
+ res = await fetch(`${req.url.replace(/\/+$/, '')}${CREDENTIAL_PATH}`, {
408
+ method: 'POST',
409
+ headers: {
410
+ 'content-type': 'application/json',
411
+ // The ONE place the user key is used. Not a query string, not the body,
412
+ // not an environment variable, not a subprocess argument.
413
+ [USER_KEY_HEADER]: req.userKey,
414
+ },
415
+ body: JSON.stringify({ project: req.project, team: req.team }),
416
+ signal: controller.signal,
417
+ // #290 Must Fix 2 (CWE-601/CWE-200). NOT the default 'follow'.
418
+ //
419
+ // fetch strips `Authorization` on a cross-origin redirect. It does NOT
420
+ // strip a custom header, and this one carries the operator's MemNexus user
421
+ // key. Measured on this machine with two loopback servers and a fake key:
422
+ // `x-mx-user-key` was forwarded to the second origin while the control
423
+ // `Authorization` header was stripped. A 302 from the service, its ingress,
424
+ // or anything answering for it would therefore send the key to a host the
425
+ // operator never configured, against a URL that passes every check above.
426
+ //
427
+ // 'error' rejects the promise instead, and the catch below reports it as
428
+ // `unavailable` with the error name only. A coordination service that needs
429
+ // a redirect to work is a service configuration to fix, not a redirect to
430
+ // follow with a credential in hand.
431
+ redirect: 'error',
432
+ });
433
+ }
434
+ catch (err) {
435
+ // The error NAME only. A fetch error message can hold the URL and a proxy's
436
+ // response text, and neither belongs in an operator line. A refused redirect
437
+ // arrives here, which is why 'error' above needs no branch of its own.
438
+ clearTimeout(timer);
439
+ return { status: 'unavailable', detail: `service unreachable: ${err instanceof Error ? err.name : 'error'}` };
440
+ }
441
+ // The timer stays ARMED across the body read and is cleared once, below. It
442
+ // used to be cleared as soon as the headers arrived, which left `res.json()`
443
+ // reading an unbounded body with the signal disarmed (#290 Should Fix 2).
444
+ try {
445
+ if (res.status === 401)
446
+ return { status: 'invalid-key' };
447
+ if (res.status === 403)
448
+ return { status: 'not-authorized' };
449
+ if (res.status === 409)
450
+ return { status: 'not-registered' };
451
+ if (res.status === 429)
452
+ return { status: 'limit-reached' };
453
+ if (res.status === 503)
454
+ return { status: 'unavailable' };
455
+ if (res.status !== 200)
456
+ return { status: 'unavailable', detail: `service answered HTTP ${res.status}` };
457
+ // Two checks, not one. The declared length is the EARLY refusal: it costs
458
+ // nothing and rejects an honest oversized answer before a byte is read. It is
459
+ // not the control, because `content-length` is optional and peer-supplied.
460
+ const declared = Number.parseInt(res.headers.get('content-length') ?? '', 10);
461
+ if (Number.isFinite(declared) && declared > MAX_CREDENTIAL_BODY_BYTES) {
462
+ return { status: 'unavailable', detail: `service answered 200 with a body over ${MAX_CREDENTIAL_BODY_BYTES} bytes` };
463
+ }
464
+ let text;
465
+ try {
466
+ // The control: count what actually arrives. A chunked response declares no
467
+ // length and would otherwise be read whole.
468
+ text = await readBoundedText(res, MAX_CREDENTIAL_BODY_BYTES);
469
+ }
470
+ catch {
471
+ // An abort during the body read lands here, and reads as unavailable,
472
+ // which is what a service that stopped mid-answer is.
473
+ return { status: 'unavailable', detail: 'service answered 200 with a body that could not be read' };
474
+ }
475
+ if (text === null) {
476
+ return { status: 'unavailable', detail: `service answered 200 with a body over ${MAX_CREDENTIAL_BODY_BYTES} bytes` };
477
+ }
478
+ let body;
479
+ try {
480
+ body = JSON.parse(text);
481
+ }
482
+ catch {
483
+ return { status: 'unavailable', detail: 'service answered 200 with a body that is not JSON' };
484
+ }
485
+ const token = body?.token;
486
+ // The same usability rule the vault path applies (SF-4): a blank answer is
487
+ // not a token, and must not be cached or returned.
488
+ if (!isUsableSecret(typeof token === 'string' ? token : undefined)) {
489
+ return { status: 'unavailable', detail: 'service answered 200 with no token' };
490
+ }
491
+ return { status: 'issued', token: token };
492
+ }
493
+ finally {
494
+ clearTimeout(timer);
495
+ }
496
+ }
119
497
  /**
120
498
  * SF-3 born-0600 cache write. A write failure is tolerated (fail-open) but is
121
499
  * REPORTED: `true` only when the bytes actually landed. Callers use that to decide
122
500
  * whether they may tell the operator a cached copy was replaced — see writeCache
123
501
  * in TokenResolveDeps.
124
502
  */
503
+ export function writeCredentialCache(path, value) {
504
+ return defaultWriteCache(path, value);
505
+ }
125
506
  function defaultWriteCache(path, value) {
126
507
  try {
508
+ // #290 Informational 2. `mode` applies only when writeFileSync CREATES the
509
+ // file, so writing over a pre-existing entry inherits whatever mode that
510
+ // entry had: a cache file left at 0644 by anything else stays 0644 and the
511
+ // SF-3 born-0600 property silently does not hold. Removing it first makes
512
+ // every write a create. `force` so a missing file is not an error, and the
513
+ // remove-then-write order is the one the refresh path already uses.
514
+ //
515
+ // It also removes a SYMLINK planted at the cache path, rather than following
516
+ // it: `rmSync` unlinks the link itself, so the write that follows creates a
517
+ // regular file at 0600 here instead of writing the token through the link to
518
+ // wherever it pointed.
519
+ rmSync(path, { force: true });
127
520
  writeFileSync(path, value, { mode: 0o600 });
128
521
  return true;
129
522
  }
@@ -182,7 +575,49 @@ export function resolveRoster(project, env, readFileText) {
182
575
  }
183
576
  return BUILTIN_ROSTERS[project] ?? [];
184
577
  }
185
- function resolveIdentity(env, readFileText, projectOverride) {
578
+ /**
579
+ * The #220 interlock: does the resolved identity match what the caller asserted?
580
+ *
581
+ * Returns the operator-facing reason on a mismatch, undefined when the two agree
582
+ * or when nothing was asserted. Both slugs are non-secret and both are named, the
583
+ * way the drain interlock names them (`commands/coordination.ts`), because the
584
+ * operator cannot act on "a mismatch" without knowing which two values disagree.
585
+ *
586
+ * Why this exists on the credential path and not the vault path: a cwd mismatch
587
+ * under Key Vault names a secret that does not exist, so it fails safe on its
588
+ * own. A MemNexus user key is valid for every grant the operator holds, so the
589
+ * same mismatch would obtain a REAL token for a project and team the session
590
+ * never selected. #220's full fix is separate; this closes the path C3 opens.
591
+ *
592
+ * WHAT AN ASSERTION IS WORTH DEPENDS ON WHERE IT CAME FROM (#290 Must Fix 3).
593
+ * The check is only as good as the independence of the two values it compares.
594
+ *
595
+ * - `commands/start.ts` asserts the team the operator asked to start, which is
596
+ * read from the command line and not from any file in the worktree. That
597
+ * assertion is independent of the marker and catches marker tampering.
598
+ * - `commands/coordination.ts` asserts MX_COORD_EXPECT_PROJECT and
599
+ * MX_COORD_EXPECT_TEAM from the environment the session was launched with.
600
+ * - The session-start hook (`coordination-brief.sh:154`) derives its value from
601
+ * the marker it read at `:114`. A marker-derived assertion covers the
602
+ * CLAUDE_WORKTREE_PATH mismatch ONLY: the two values have one source, so a
603
+ * tampered marker agrees with itself and this check cannot see it. That is a
604
+ * real limit of the interlock, not a property it has and this comment
605
+ * understates.
606
+ */
607
+ function identityInterlockMismatch(project, slug, env, expect) {
608
+ const expectedProject = expect?.project ?? env[ENV_KEY_EXPECT_PROJECT];
609
+ if (expectedProject && expectedProject !== project) {
610
+ return `this worktree resolved project "${project}" but the caller asserted "${expectedProject}" ` +
611
+ `(${ENV_KEY_EXPECT_PROJECT}); refusing to request a credential for an identity this session did not select`;
612
+ }
613
+ const expectedTeam = expect?.team ?? env[ENV_KEY_EXPECT_TEAM];
614
+ if (expectedTeam && expectedTeam !== slug) {
615
+ return `this worktree resolved team "${slug}" but the caller asserted "${expectedTeam}" ` +
616
+ `(${ENV_KEY_EXPECT_TEAM}); refusing to request a credential for an identity this session did not select`;
617
+ }
618
+ return undefined;
619
+ }
620
+ function resolveIdentity(env, readFileText, projectOverride, expect) {
186
621
  // Resolve the PROJECT (config-derived, default memnexus). Never throws.
187
622
  const project = projectOverride ?? resolveProductSlug();
188
623
  // Validate the resolved project slug BEFORE any roster lookup or az/KV call
@@ -207,11 +642,41 @@ function resolveIdentity(env, readFileText, projectOverride) {
207
642
  if (!slug) {
208
643
  return { ok: false, fail: { status: 'unprovisioned', project, detail: 'coordination marker is empty' } };
209
644
  }
210
- // SF-2: roster-membership gate for THIS project BEFORE any az call. The roster
211
- // comes from the OFFLINE file (single source), builtin fallback.
212
- const roster = resolveRoster(project, env, readFileText);
213
- if (!roster.includes(slug)) {
214
- return { ok: false, fail: { status: 'not-on-roster', project, slug } };
645
+ if (usesCredentialEndpoint(project)) {
646
+ // #290 Should Fix 1 (CWE-22). The TEAM slug is shape-checked here.
647
+ //
648
+ // On the vault path `roster.includes(slug)` is what refused a malformed
649
+ // value: only a listed name could pass, so the shape came free. Bypassing the
650
+ // roster for this project removed that check and put nothing in its place,
651
+ // and the slug is then joined into a cache path. Measured with a marker of
652
+ // `../../../../tmp/pwned`: the credential path resolved and wrote a cache
653
+ // OUTSIDE the worktree, while the vault path refused. The live service also
654
+ // refuses that shape, but that is a control in another package and this one
655
+ // must not depend on it.
656
+ //
657
+ // The same rules the project slug is held to, from the same function.
658
+ if (!isValidProjectSlug(slug)) {
659
+ return { ok: false, fail: { status: 'misconfigured', project, slug, detail: invalidProjectSlugMessage(slug) } };
660
+ }
661
+ // #220 interlock, BEFORE any network call. Fail-CLOSED.
662
+ const mismatch = identityInterlockMismatch(project, slug, env, expect);
663
+ if (mismatch) {
664
+ return { ok: false, fail: { status: 'identity-mismatch', project, slug, detail: mismatch } };
665
+ }
666
+ // SF-2 on this path is the SERVICE's grant table, not the offline file. The
667
+ // service authorizes (identity, project, team) and answers a byte-identical
668
+ // 403 when it does not, so a local roster file that predates a registration
669
+ // would refuse a team the service admits. The committed roster file and the
670
+ // builtin fallback are untouched: `mx-agent list` and the catalog parity test
671
+ // still read them.
672
+ }
673
+ else {
674
+ // SF-2: roster-membership gate for THIS project BEFORE any az call. The roster
675
+ // comes from the OFFLINE file (single source), builtin fallback.
676
+ const roster = resolveRoster(project, env, readFileText);
677
+ if (!roster.includes(slug)) {
678
+ return { ok: false, fail: { status: 'not-on-roster', project, slug } };
679
+ }
215
680
  }
216
681
  // MF-1: (project, team)-bound per-worktree cache.
217
682
  return { ok: true, id: { project, slug, cachePath: join(worktree, cacheFileName(project, slug)) } };
@@ -228,13 +693,122 @@ function fetchFromKeyVault(id, fetchSecret) {
228
693
  }
229
694
  return fetched;
230
695
  }
696
+ /**
697
+ * Obtain this identity's token from POST /admin/credential.
698
+ *
699
+ * The one place the credential path's five service outcomes become the CLI's
700
+ * statuses. Every message is a module constant, so the 403 wording is a single
701
+ * string that cannot vary with the team, and the mapping is one table a reviewer
702
+ * reads in one place.
703
+ *
704
+ * Never throws. A configuration gap (no URL, no user key) is `unprovisioned`
705
+ * because the operator provisions something to fix it; a service that is down is
706
+ * `unavailable` because the operator provisions nothing.
707
+ */
708
+ async function obtainCredential(id, env, deps) {
709
+ let url = deps.serviceUrl;
710
+ let urlSource = 'supplied';
711
+ if (!url) {
712
+ try {
713
+ const resolved = resolveCoordinationUrl();
714
+ url = resolved?.url;
715
+ urlSource = resolved?.source ?? 'supplied';
716
+ }
717
+ catch {
718
+ url = undefined;
719
+ }
720
+ }
721
+ if (!url) {
722
+ // "Not set" and "set and refused" are different states with different
723
+ // remedies, and the project source reported the first for both: its
724
+ // validation happens at load, inside a try that discards the reason
725
+ // (#290 second delta, Informational 2).
726
+ const refused = projectUrlValidationError();
727
+ if (refused)
728
+ return { status: 'misconfigured', detail: refused };
729
+ return { status: 'unprovisioned', detail: CREDENTIAL_NO_URL_DETAIL };
730
+ }
731
+ // #290 Must Fix 1 (CWE-319/CWE-346). The URL is scheme- and host-checked HERE,
732
+ // before the key is read, and on EVERY source.
733
+ //
734
+ // `resolveCoordinationUrl` walks MX_COORD_SERVICE_URL, then the global config
735
+ // key, then the committed project config, and only the third was ever
736
+ // validated. That was survivable while the URL received a revocable per-team
737
+ // token. It is not survivable now: this request carries the operator's MemNexus
738
+ // user key, which has no expiry and is valid for every grant its holder has, so
739
+ // anything able to set that environment variable or run
740
+ // `mx-agent config set coordination-service-url http://<host>` would otherwise
741
+ // make the next brief, escalate or drain in any mx-agent worktree POST the key
742
+ // in cleartext and cache the attacker's reply as the team token.
743
+ //
744
+ // The rules are the committed config's rules, unchanged and not duplicated: one
745
+ // exported function decides for all three sources, so they cannot drift.
746
+ // MISCONFIGURED, not unprovisioned: nothing is missing, a configured value is
747
+ // refused, and the operator has to change it rather than provision anything.
748
+ try {
749
+ url = validateCoordinationServiceUrl(url, credentialSuffixReader(), URL_SOURCE_LABEL[urlSource] ?? URL_SOURCE_LABEL.supplied);
750
+ }
751
+ catch (err) {
752
+ // The validator never prints the value back (a rejected URL can hold a
753
+ // password in its userinfo), so its message is safe to pass through.
754
+ return { status: 'misconfigured', detail: err instanceof Error ? err.message : 'coordination service URL is not usable' };
755
+ }
756
+ const readUserKey = deps.readUserKey ?? defaultReadUserKey;
757
+ let userKey;
758
+ try {
759
+ userKey = readUserKey(env);
760
+ }
761
+ catch {
762
+ userKey = undefined;
763
+ }
764
+ // The key is absent or unreadable. Neither the file nor anything read from it
765
+ // is named, and nothing reports whether a value was found but rejected.
766
+ if (!userKey)
767
+ return { status: 'unprovisioned', detail: CREDENTIAL_NO_USER_KEY_DETAIL };
768
+ const fetchCredential = deps.fetchCredential ?? defaultFetchCredential;
769
+ let out;
770
+ try {
771
+ out = await fetchCredential({
772
+ url,
773
+ project: id.project,
774
+ team: id.slug,
775
+ userKey,
776
+ timeoutMs: credentialTimeoutMs(env),
777
+ });
778
+ }
779
+ catch (err) {
780
+ // The fetcher is documented never-throws; belt and braces. The error NAME
781
+ // only, for the same reason defaultFetchCredential gives.
782
+ return {
783
+ status: 'unavailable',
784
+ detail: `${CREDENTIAL_UNAVAILABLE_DETAIL} (${err instanceof Error ? err.name : 'error'})`,
785
+ };
786
+ }
787
+ switch (out.status) {
788
+ case 'issued':
789
+ return { status: 'resolved', token: out.token };
790
+ case 'invalid-key':
791
+ return { status: 'invalid-key', detail: CREDENTIAL_INVALID_KEY_DETAIL };
792
+ case 'not-authorized':
793
+ return { status: 'not-authorized', detail: CREDENTIAL_NOT_AUTHORIZED_DETAIL };
794
+ case 'not-registered':
795
+ return { status: 'not-on-roster', detail: CREDENTIAL_NOT_REGISTERED_DETAIL };
796
+ case 'limit-reached':
797
+ return { status: 'limit-reached', detail: CREDENTIAL_LIMIT_REACHED_DETAIL };
798
+ default:
799
+ return {
800
+ status: 'unavailable',
801
+ detail: out.detail ? `${CREDENTIAL_UNAVAILABLE_DETAIL} (${out.detail})` : CREDENTIAL_UNAVAILABLE_DETAIL,
802
+ };
803
+ }
804
+ }
231
805
  /**
232
806
  * Resolve the coordination token, self-provisioning from Key Vault when none is
233
807
  * configured. Never throws — every failure is a typed result the caller acts on.
234
808
  * The returned token (when present) must be handed to the client in-memory
235
809
  * (process env for the request); it must NOT be written to the global config.
236
810
  */
237
- export function resolveCoordinationToken(deps = {}) {
811
+ export async function resolveCoordinationToken(deps = {}) {
238
812
  const env = deps.env ?? process.env;
239
813
  const readFileText = deps.readFileText ?? defaultReadFileText;
240
814
  // 1. Already configured → use it, skip KV. Env preferred, then global config.
@@ -253,18 +827,39 @@ export function resolveCoordinationToken(deps = {}) {
253
827
  // 2-4. Resolve + gate the (project, team) identity: project slug validity,
254
828
  // authoritative marker, roster membership. Shared with the 401 refresh
255
829
  // path so both obey the same gates.
256
- const identity = resolveIdentity(env, readFileText, deps.project);
830
+ const identity = resolveIdentity(env, readFileText, deps.project, deps.expect);
257
831
  if (!identity.ok)
258
832
  return identity.fail;
259
833
  const { project, slug, cachePath } = identity.id;
260
- // 5. MF-1: (project, team)-bound per-worktree cache.
834
+ // 5. MF-1: (project, team)-bound per-worktree cache. Unchanged on both paths:
835
+ // same filename, same location, and a warm cache still makes no call.
261
836
  const cachedRaw = readFileText(cachePath);
262
837
  if (cachedRaw) {
263
838
  const cached = firstLineNoSpace(cachedRaw);
264
839
  if (cached)
265
840
  return { status: 'resolved', token: cached, project, slug, source: 'cache' };
266
841
  }
267
- // 6. Fetch from Key Vault (ND-1 primary name, memnexus legacy fallback).
842
+ // 6a. Credential-endpoint projects present the operator's MemNexus user key to
843
+ // the coordination service instead of reading Key Vault (#288).
844
+ if (usesCredentialEndpoint(project)) {
845
+ const got = await obtainCredential(identity.id, env, deps);
846
+ if (got.status === 'resolved' && isUsableSecret(got.token)) {
847
+ // SF-3: same cache, same filename, born 0600. NEVER the global config.
848
+ const writeCredentialCache = deps.writeCache ?? defaultWriteCache;
849
+ writeCredentialCache(cachePath, got.token);
850
+ return { status: 'resolved', token: got.token, project, slug, source: 'credential' };
851
+ }
852
+ // SF-4: an issued-but-blank token is not a token. It is not cached and it is
853
+ // not returned, and the outcome is could-not-run rather than a refusal,
854
+ // because nothing about the grant was decided.
855
+ return {
856
+ status: got.status === 'resolved' ? 'unavailable' : got.status,
857
+ project,
858
+ slug,
859
+ detail: got.status === 'resolved' ? CREDENTIAL_UNAVAILABLE_DETAIL : got.detail,
860
+ };
861
+ }
862
+ // 6b. Fetch from Key Vault (ND-1 primary name, memnexus legacy fallback).
268
863
  const fetchSecret = deps.fetchSecret ?? defaultFetchSecret;
269
864
  const fetched = fetchFromKeyVault(identity.id, fetchSecret);
270
865
  const source = 'keyvault';
@@ -324,10 +919,10 @@ function defaultRemoveFile(path) {
324
919
  *
325
920
  * `rejectedToken` is compared but never logged; pass '' when it is unknown.
326
921
  */
327
- export function refreshCoordinationToken(rejectedToken, deps = {}) {
922
+ export async function refreshCoordinationToken(rejectedToken, deps = {}) {
328
923
  const env = deps.env ?? process.env;
329
924
  const readFileText = deps.readFileText ?? defaultReadFileText;
330
- const identity = resolveIdentity(env, readFileText, deps.project);
925
+ const identity = resolveIdentity(env, readFileText, deps.project, deps.expect);
331
926
  if (!identity.ok)
332
927
  return identity.fail;
333
928
  const { project, slug, cachePath } = identity.id;
@@ -354,41 +949,73 @@ export function refreshCoordinationToken(rejectedToken, deps = {}) {
354
949
  // every single session until someone fixes it. A credential the service
355
950
  // already refuses grants nothing; losing the ONLY local copy costs the alarm.
356
951
  //
357
- // So: nothing is deleted unless we hold a replacement in hand.
358
- const fetchSecret = deps.fetchSecret ?? defaultFetchSecret;
359
- const fetched = fetchFromKeyVault(identity.id, fetchSecret);
360
- if (!isUsableSecret(fetched)) {
361
- // SF-1 of the delta security review: which of the TWO states we are in decides
362
- // whether the loudness guarantee above actually holds, so the message is
363
- // derived from the cache we just read, never asserted unconditionally.
364
- //
365
- // (a) The cache still holds the rejected token. The reasoning above applies
366
- // verbatim: it is presented again next session, refused again, and the
367
- // loud block fires again. Nothing to do beyond fixing the vault.
368
- // (b) There is NO cached token — no cache file, an empty/whitespace-only
369
- // one, or a write that failed earlier (the hook's cache write ends in
370
- // `|| true`, and a token supplied via MX_COORD_SERVICE_TOKEN or the
371
- // global config never writes a cache at all). Then the guarantee does
372
- // NOT hold: next session resolveCoordinationToken finds no cache, its own
373
- // az fetch fails, the session-start hook takes its fail-open exit 0 with
374
- // no output, and the channel that carries P0 escalations goes silent with
375
- // nothing on screen. This state needs a human before the next session,
376
- // and the message has to say so — it is the only warning that gets shown.
377
- const rejectedStillCached = cached !== '' && cached === rejectedToken;
378
- return {
379
- status: 'unprovisioned',
380
- project,
381
- slug,
382
- cacheInvalidated: false,
383
- detail: rejectedStillCached
384
- ? 'Key Vault returned no token (az not logged in, KV unreachable, or secret missing); ' +
385
- 'the rejected token was LEFT in the per-worktree cache on purpose, so this failure stays loud every session'
386
- : 'Key Vault returned no token (az not logged in, KV unreachable, or secret missing), and this worktree ' +
387
- 'holds NO cached token to fail loudly with. NEEDS MANUAL ATTENTION BEFORE THE NEXT SESSION: the next ' +
388
- 'session-start brief will find no cache, fail the same fetch, and exit silently with no output, so ' +
389
- 'queued cross-team escalations will read as an empty inbox. Run `az login` in this worktree, or ask the ' +
390
- 'platform team to re-issue this team\'s token (P1).',
391
- };
952
+ // So: nothing is deleted unless we hold a replacement in hand. That ordering is
953
+ // the same on the credential path (#288): the credential is requested first,
954
+ // and the cache is deleted only once a replacement token is in hand.
955
+ let fetched;
956
+ let source = 'keyvault';
957
+ if (usesCredentialEndpoint(project)) {
958
+ source = 'credential';
959
+ const got = await obtainCredential(identity.id, env, deps);
960
+ if (got.status === 'resolved' && isUsableSecret(got.token)) {
961
+ fetched = got.token;
962
+ }
963
+ else {
964
+ // Nothing was deleted, for the reason stated above. Which of the two states
965
+ // we are in decides whether the loudness guarantee holds, so the clause is
966
+ // derived from the cache that was read, never asserted unconditionally
967
+ // (SF-1 of the #4970 delta security review).
968
+ const rejectedStillCachedOnCredentialPath = cached !== '' && cached === rejectedToken;
969
+ return {
970
+ status: got.status === 'resolved' ? 'unavailable' : got.status,
971
+ project,
972
+ slug,
973
+ cacheInvalidated: false,
974
+ detail: (got.status === 'resolved' ? CREDENTIAL_UNAVAILABLE_DETAIL : got.detail ?? CREDENTIAL_UNAVAILABLE_DETAIL) +
975
+ (rejectedStillCachedOnCredentialPath ? REFRESH_STAYS_LOUD_CLAUSE : REFRESH_GOES_SILENT_CLAUSE),
976
+ };
977
+ }
978
+ }
979
+ else {
980
+ const fetchSecret = deps.fetchSecret ?? defaultFetchSecret;
981
+ const kv = fetchFromKeyVault(identity.id, fetchSecret);
982
+ if (!isUsableSecret(kv)) {
983
+ // SF-1 of the delta security review: which of the TWO states we are in decides
984
+ // whether the loudness guarantee above actually holds, so the message is
985
+ // derived from the cache we just read, never asserted unconditionally.
986
+ //
987
+ // (a) The cache still holds the rejected token. The reasoning above applies
988
+ // verbatim: it is presented again next session, refused again, and the
989
+ // loud block fires again. Nothing to do beyond fixing the vault.
990
+ // (b) There is NO cached token — no cache file, an empty/whitespace-only
991
+ // one, or a write that failed earlier (the hook's cache write ends in
992
+ // `|| true`, and a token supplied via MX_COORD_SERVICE_TOKEN or the
993
+ // global config never writes a cache at all). Then the guarantee does
994
+ // NOT hold: next session resolveCoordinationToken finds no cache, its own
995
+ // az fetch fails, the session-start hook takes its fail-open exit 0 with
996
+ // no output, and the channel that carries P0 escalations goes silent with
997
+ // nothing on screen. This state needs a human before the next session,
998
+ // and the message has to say so — it is the only warning that gets shown.
999
+ const rejectedStillCached = cached !== '' && cached === rejectedToken;
1000
+ return {
1001
+ status: 'unprovisioned',
1002
+ project,
1003
+ slug,
1004
+ cacheInvalidated: false,
1005
+ detail: rejectedStillCached
1006
+ ? 'Key Vault returned no token (az not logged in, KV unreachable, or secret missing); ' +
1007
+ 'the rejected token was LEFT in the per-worktree cache on purpose, so this failure stays loud every session'
1008
+ : 'Key Vault returned no token (az not logged in, KV unreachable, or secret missing), and this worktree ' +
1009
+ 'holds NO cached token to fail loudly with. NEEDS MANUAL ATTENTION BEFORE THE NEXT SESSION: the next ' +
1010
+ 'session-start brief will find no cache, fail the same fetch, and exit silently with no output, so ' +
1011
+ 'queued cross-team escalations will read as an empty inbox. Run `az login` in this worktree. ' +
1012
+ // One string, not two: the acceptance grep reads the source, and a phrase
1013
+ // split across a concatenation is invisible to a single-line search (#59
1014
+ // acceptance item 11).
1015
+ 'Filing an escalation from here queues locally and will not reach `bootstrap` until a token works again.',
1016
+ };
1017
+ }
1018
+ fetched = kv;
392
1019
  }
393
1020
  // Delete-then-write, in that order, is deliberate: writeFileSync applies `mode`
394
1021
  // only when it CREATES the file, so writing over a surviving entry would inherit
@@ -408,7 +1035,7 @@ export function refreshCoordinationToken(rejectedToken, deps = {}) {
408
1035
  token: fetched,
409
1036
  project,
410
1037
  slug,
411
- source: 'keyvault',
1038
+ source,
412
1039
  // Replaced = the old entry is gone AND the new one landed. `removed === false`
413
1040
  // with a successful write is a first-time cache fill, not a replacement.
414
1041
  cacheInvalidated: removed && writeResult === true,
@@ -417,4 +1044,200 @@ export function refreshCoordinationToken(rejectedToken, deps = {}) {
417
1044
  unchanged: fetched === rejectedToken,
418
1045
  };
419
1046
  }
1047
+ /**
1048
+ * Where the new team's first session looks for its token, exported so a caller
1049
+ * that only needs the PATH (a no-write re-check) does not rebuild the filename.
1050
+ */
1051
+ export function credentialCachePath(project, team, worktreePath) {
1052
+ return join(worktreePath, cacheFileName(project, team));
1053
+ }
1054
+ /**
1055
+ * Read the cache state for (project, team) in a worktree. Never throws, never
1056
+ * returns the secret.
1057
+ */
1058
+ export function credentialCacheState(i) {
1059
+ const cachePath = credentialCachePath(i.project, i.team, i.worktreePath);
1060
+ // AN INJECTED READER IS THE TEST PATH ONLY, and it is answered first so a test
1061
+ // can state a cache without a file. Every other caller takes the branch below,
1062
+ // which never follows a link.
1063
+ if (i.readCache) {
1064
+ let raw;
1065
+ try {
1066
+ raw = i.readCache(cachePath);
1067
+ }
1068
+ catch {
1069
+ raw = undefined;
1070
+ }
1071
+ if (raw === undefined)
1072
+ return { kind: 'absent', cachePath };
1073
+ if (!isUsableSecret(raw))
1074
+ return { kind: 'blank', cachePath };
1075
+ const statMode = i.statMode ?? defaultStatMode;
1076
+ return { kind: 'usable', cachePath, mode: statMode(cachePath) };
1077
+ }
1078
+ // NO SYMLINK IS FOLLOWED, and this is the whole reason the read is written out
1079
+ // here rather than reusing `defaultReadFileText` (:427-434) and
1080
+ // `defaultStatMode` (:1400-1406). Both follow links, and the pre-mint check
1081
+ // this function feeds runs BEFORE `defaultWriteCache`'s `rmSync` (:654-657),
1082
+ // which is what used to unlink a planted link. So a link at the cache path
1083
+ // would answer `usable` with its TARGET's mode, assert row 10, and stop the
1084
+ // mint: an attacker who can write into the new worktree decides that the team
1085
+ // has a credential, and the team's first session then reads a file it does not
1086
+ // control. Measured on the code this replaces: kind usable, mode 0o600,
1087
+ // fetches 0, link intact (security review round 2, Must Fix).
1088
+ //
1089
+ // Three defences, in order: `lstatSync` decides on the LINK rather than its
1090
+ // target; `O_NOFOLLOW` refuses at open time, so nothing is read even if the
1091
+ // path is swapped between the two calls; and the mode is taken from `fstat` on
1092
+ // the descriptor that was actually read, never from a second path lookup.
1093
+ //
1094
+ // ANYTHING THAT IS NOT A REGULAR FILE READS AS `blank`, not as absent: the
1095
+ // path is occupied, so the caller must not claim the row and must not treat it
1096
+ // as a clean slate. `blank` makes the run mint, and the writer's
1097
+ // remove-then-create clears whatever is in the way.
1098
+ let linkStat;
1099
+ try {
1100
+ linkStat = lstatSync(cachePath);
1101
+ }
1102
+ catch {
1103
+ return { kind: 'absent', cachePath };
1104
+ }
1105
+ if (!linkStat.isFile())
1106
+ return { kind: 'blank', cachePath };
1107
+ let fd;
1108
+ try {
1109
+ fd = openSync(cachePath, constants.O_RDONLY | constants.O_NOFOLLOW);
1110
+ }
1111
+ catch {
1112
+ // ELOOP is a link that appeared between the lstat and the open. Every other
1113
+ // errno is a file this run cannot read, and neither is evidence of a
1114
+ // credential.
1115
+ return { kind: 'blank', cachePath };
1116
+ }
1117
+ try {
1118
+ const opened = fstatSync(fd);
1119
+ if (!opened.isFile())
1120
+ return { kind: 'blank', cachePath };
1121
+ // Bounded. A cache entry is one secret on one line; a file larger than this
1122
+ // is not one, and it is not read into memory to find that out.
1123
+ const buffer = Buffer.alloc(Math.min(opened.size, MAX_CACHE_BYTES));
1124
+ const bytes = opened.size === 0 ? 0 : readSync(fd, buffer, 0, buffer.length, 0);
1125
+ // The VALUE never leaves this block, and neither does its length: the return
1126
+ // states usable or not, and the mode. `AGENTS.md`'s no-echo rule covers a
1127
+ // credential met on the way to another answer, which is exactly this one.
1128
+ if (!isUsableSecret(buffer.subarray(0, bytes).toString('utf-8'))) {
1129
+ return { kind: 'blank', cachePath };
1130
+ }
1131
+ return { kind: 'usable', cachePath, mode: opened.mode & 0o777 };
1132
+ }
1133
+ catch {
1134
+ return { kind: 'blank', cachePath };
1135
+ }
1136
+ finally {
1137
+ closeSync(fd);
1138
+ }
1139
+ }
1140
+ /** Largest cache entry this reader will look at. A token is far below it. */
1141
+ const MAX_CACHE_BYTES = 64 * 1024;
1142
+ /** Default permission read-back: null when the file cannot be stated. */
1143
+ function defaultStatMode(path) {
1144
+ try {
1145
+ return statSync(path).mode & 0o777;
1146
+ }
1147
+ catch {
1148
+ return null;
1149
+ }
1150
+ }
1151
+ /**
1152
+ * Row 10 for a credential-endpoint project: is a credential OBTAINABLE for this
1153
+ * team, and if so, cache it where the team's first session will look.
1154
+ *
1155
+ * This replaces the vault question for `mx-agent` only. The vault question was
1156
+ * "has the product owner minted this team's token"; the credential question is
1157
+ * "does a grant authorize this operator to hold this team's token", which is the
1158
+ * fact that now decides whether the new team has a cross-team channel.
1159
+ *
1160
+ * Unlike the vault probe, this WRITES: on 200 the issued token is the token the
1161
+ * first session needs, and dropping it would mean minting a second one. It is
1162
+ * written born 0600 into `.mx-coordination-token--<project>--<team>` in the new
1163
+ * worktree, the same filename and location every other path uses, and the mode is
1164
+ * read back rather than assumed.
1165
+ *
1166
+ * NO ENVIRONMENT INTERLOCK HERE, deliberately. `provision` legitimately creates a
1167
+ * team that is NOT the running session's team, so comparing against the session's
1168
+ * MX_COORD_EXPECT_TEAM would refuse every real creation. The asserted identity on
1169
+ * this path is the (project, team) the creation is for, and it is passed straight
1170
+ * to the request. The interlock that #220 needs guards the SESSION path, in
1171
+ * resolveIdentity, where an identity resolved from a worktree marker can disagree
1172
+ * with what the caller asked for.
1173
+ *
1174
+ * Never throws.
1175
+ */
1176
+ export async function provisionCredentialForWorktree(i) {
1177
+ const env = i.env ?? process.env;
1178
+ if (!isValidProjectSlug(i.project)) {
1179
+ return { kind: 'could-not-run', detail: invalidProjectSlugMessage(i.project) };
1180
+ }
1181
+ // The team slug is joined into the new worktree's cache path, so it is held to
1182
+ // the same rules (#290 Should Fix 1).
1183
+ if (!isValidProjectSlug(i.team)) {
1184
+ return { kind: 'could-not-run', detail: invalidProjectSlugMessage(i.team) };
1185
+ }
1186
+ const cachePath = credentialCachePath(i.project, i.team, i.worktreePath);
1187
+ // BEFORE ANY MINT (#316 change B, red-team Critical 1). A usable cache is this
1188
+ // row's claim already met: the new team's first session reads this file, and
1189
+ // asking the service again would issue a second token for a team that holds
1190
+ // one. The mode is reported as it is found, so a cache left world-readable by
1191
+ // something else still fails the row through the caller's 0600 rule rather
1192
+ // than being re-minted into a fresh file.
1193
+ const existing = credentialCacheState({
1194
+ project: i.project,
1195
+ team: i.team,
1196
+ worktreePath: i.worktreePath,
1197
+ readCache: i.readCache,
1198
+ statMode: i.statMode,
1199
+ });
1200
+ if (existing.kind === 'usable') {
1201
+ return { kind: 'obtainable', cachePath, mode: existing.mode, fromCache: true };
1202
+ }
1203
+ const got = await obtainCredential({ project: i.project, slug: i.team, cachePath }, env, {
1204
+ env,
1205
+ serviceUrl: i.serviceUrl,
1206
+ readUserKey: i.readUserKey,
1207
+ fetchCredential: i.fetchCredential,
1208
+ });
1209
+ if (got.status === 'resolved' && isUsableSecret(got.token)) {
1210
+ const writeCache = i.writeCache ?? defaultWriteCache;
1211
+ let landed = writeCache(cachePath, got.token);
1212
+ if (landed === false) {
1213
+ // RETRY IN PROCESS, once (#316 change B). The token is in memory here and
1214
+ // nowhere else: returning now abandons a credential the service has
1215
+ // already minted, and the next run mints another. The common causes of a
1216
+ // first failure are transient (a directory created moments earlier, a
1217
+ // full-then-freed disk), so the write is attempted a second time before
1218
+ // the run gives up on it. The value is passed straight back to the writer
1219
+ // and is never logged, and no third attempt is made — a second failure is
1220
+ // a real one and could-not-run is its own outcome.
1221
+ landed = writeCache(cachePath, got.token);
1222
+ }
1223
+ if (landed === false) {
1224
+ // A credential WAS issued, so the refusal is not about authorization; the
1225
+ // row cannot claim the team's first session will find it, either.
1226
+ return {
1227
+ kind: 'could-not-run',
1228
+ detail: 'a credential was issued but it could not be written to the new worktree\'s token cache ' +
1229
+ `(${cachePath}), and the write was retried once; the team's first session will request its own`,
1230
+ };
1231
+ }
1232
+ const statMode = i.statMode ?? defaultStatMode;
1233
+ return { kind: 'obtainable', cachePath, mode: statMode(cachePath) };
1234
+ }
1235
+ // A refusal and a could-not-run are different rows. 401, 403, 409 and 429
1236
+ // are the service deciding; 503, a timeout, a missing URL and a missing key
1237
+ // are not.
1238
+ if (got.status === 'invalid-key' || got.status === 'not-authorized' || got.status === 'not-on-roster' || got.status === 'limit-reached') {
1239
+ return { kind: 'refused', detail: got.detail ?? CREDENTIAL_NOT_AUTHORIZED_DETAIL, reason: got.status };
1240
+ }
1241
+ return { kind: 'could-not-run', detail: got.detail ?? CREDENTIAL_UNAVAILABLE_DETAIL };
1242
+ }
420
1243
  //# sourceMappingURL=coordination-token.js.map