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

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