rcf-lite 0.28.2 → 0.29.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 (327) hide show
  1. package/CHANGELOG.md +317 -0
  2. package/bin/rcf.js +8 -0
  3. package/fixtures/canary-manifest.json +9 -9
  4. package/guidance/define-draft-shapes.md +89 -0
  5. package/guidance/define-intake.md +97 -0
  6. package/guidance/define-intent.md +107 -0
  7. package/guidance/discover-prototype.md +67 -0
  8. package/guidance/discovery-prototypes.md +69 -0
  9. package/guidance/harness-template.md +34 -0
  10. package/guidance/managed/agent-instructions-block.hash +1 -1
  11. package/guidance/managed/agent-instructions-block.md +34 -0
  12. package/guidance/manifest.json +9 -2
  13. package/package.json +1 -1
  14. package/rcf/adrs/adr-4120-canonical-json-hashing.json +30 -0
  15. package/rcf/adrs/adr-4121-define-sidecars.json +30 -0
  16. package/rcf/adrs/adr-4122-define-gates-blocking-and-optout.json +30 -0
  17. package/rcf/adrs/adr-4123-readiness-single-object.json +30 -0
  18. package/rcf/adrs/adr-4124-define-freeze-verb.json +30 -0
  19. package/rcf/adrs/adr-4126-persona-tagged-blockers-two-levels.json +40 -0
  20. package/rcf/adrs/adr-4127-readiness-tab-order-and-register.json +40 -0
  21. package/rcf/adrs/adr-4129-questions-harness-driven-loop.json +25 -0
  22. package/rcf/adrs/adr-4130-intake-harness-split-tool-scanned.json +20 -0
  23. package/rcf/adrs/adr-4132-prototypes-in-discovery-as-evidence.json +20 -0
  24. package/rcf/adrs/adr-4133-dag-dependency-depth-layout.json +40 -0
  25. package/rcf/adrs/adr-4134-index-json-route.json +35 -0
  26. package/rcf/adrs/adr-4135-readiness-po-register-and-adapter.json +35 -0
  27. package/rcf/adrs/adr-4136-embedding-host-fixture.json +35 -0
  28. package/rcf/code-nodes/cn-700.json +23 -0
  29. package/rcf/code-nodes/cn-701.json +14 -0
  30. package/rcf/code-nodes/cn-702.json +14 -0
  31. package/rcf/code-nodes/cn-703.json +16 -0
  32. package/rcf/code-nodes/cn-720.json +15 -0
  33. package/rcf/code-nodes/cn-721.json +15 -0
  34. package/rcf/code-nodes/cn-722.json +15 -0
  35. package/rcf/code-nodes/cn-723.json +18 -0
  36. package/rcf/code-nodes/cn-724.json +14 -0
  37. package/rcf/code-nodes/cn-725.json +37 -0
  38. package/rcf/code-nodes/cn-726.json +25 -0
  39. package/rcf/code-nodes/cn-727.json +23 -0
  40. package/rcf/code-nodes/cn-728.json +37 -0
  41. package/rcf/code-nodes/cn-729.json +26 -0
  42. package/rcf/code-nodes/cn-730.json +24 -0
  43. package/rcf/code-nodes/cn-731.json +20 -0
  44. package/rcf/code-nodes/cn-732.json +14 -0
  45. package/rcf/code-nodes/cn-733.json +14 -0
  46. package/rcf/code-nodes/cn-734.json +14 -0
  47. package/rcf/code-nodes/cn-735.json +20 -0
  48. package/rcf/code-nodes/cn-736.json +14 -0
  49. package/rcf/code-nodes/cn-737.json +14 -0
  50. package/rcf/code-nodes/cn-738.json +14 -0
  51. package/rcf/code-nodes/cn-739.json +18 -0
  52. package/rcf/code-nodes/cn-740.json +19 -0
  53. package/rcf/code-nodes/cn-741.json +16 -0
  54. package/rcf/code-nodes/cn-742.json +16 -0
  55. package/rcf/code-nodes/cn-743.json +15 -0
  56. package/rcf/code-nodes/cn-744.json +22 -0
  57. package/rcf/code-nodes/cn-745.json +16 -0
  58. package/rcf/code-nodes/cn-746.json +14 -0
  59. package/rcf/code-nodes/cn-747.json +18 -0
  60. package/rcf/code-nodes/cn-748.json +16 -0
  61. package/rcf/code-nodes/cn-749.json +16 -0
  62. package/rcf/code-nodes/cn-750.json +15 -0
  63. package/rcf/code-nodes/cn-751.json +18 -0
  64. package/rcf/code-nodes/cn-752.json +14 -0
  65. package/rcf/fbs/fbs-190.json +37 -0
  66. package/rcf/fbs/fbs-191.json +34 -0
  67. package/rcf/fbs/fbs-192.json +17 -0
  68. package/rcf/fbs/fbs-193.json +37 -0
  69. package/rcf/fbs/fbs-194.json +35 -0
  70. package/rcf/fbs/fbs-195.json +37 -0
  71. package/rcf/fbs/fbs-196.json +45 -0
  72. package/rcf/fbs/fbs-197.json +41 -0
  73. package/rcf/fbs/fbs-198.json +42 -0
  74. package/rcf/fbs/fbs-199.json +59 -0
  75. package/rcf/fbs/fbs-200.json +46 -0
  76. package/rcf/fbs/fbs-201.json +49 -0
  77. package/rcf/fbs/fbs-202.json +110 -0
  78. package/rcf/fbs/fbs-203.json +100 -0
  79. package/rcf/requirements/req-001.json +2 -1
  80. package/rcf/requirements/req-002.json +3 -2
  81. package/rcf/requirements/req-003.json +2 -1
  82. package/rcf/requirements/req-004.json +2 -1
  83. package/rcf/requirements/req-005.json +2 -1
  84. package/rcf/requirements/req-006.json +2 -1
  85. package/rcf/requirements/req-007.json +2 -1
  86. package/rcf/requirements/req-008.json +2 -1
  87. package/rcf/requirements/req-009.json +2 -1
  88. package/rcf/requirements/req-010.json +5 -2
  89. package/rcf/requirements/req-011.json +2 -1
  90. package/rcf/requirements/req-012.json +2 -1
  91. package/rcf/requirements/req-013.json +2 -1
  92. package/rcf/requirements/req-014.json +2 -1
  93. package/rcf/requirements/req-015.json +2 -1
  94. package/rcf/requirements/req-016.json +5 -2
  95. package/rcf/requirements/req-017.json +6 -2
  96. package/rcf/requirements/req-018.json +5 -2
  97. package/rcf/requirements/req-019.json +5 -2
  98. package/rcf/requirements/req-020.json +5 -2
  99. package/rcf/requirements/req-021.json +5 -2
  100. package/rcf/requirements/req-022.json +5 -2
  101. package/rcf/requirements/req-023.json +6 -4
  102. package/rcf/requirements/req-024.json +5 -2
  103. package/rcf/requirements/req-025.json +5 -2
  104. package/rcf/requirements/req-026.json +5 -2
  105. package/rcf/requirements/req-027.json +5 -2
  106. package/rcf/requirements/req-028.json +5 -2
  107. package/rcf/requirements/req-029.json +5 -2
  108. package/rcf/requirements/req-030.json +5 -2
  109. package/rcf/requirements/req-040.json +5 -2
  110. package/rcf/requirements/req-041.json +5 -2
  111. package/rcf/requirements/req-042.json +5 -2
  112. package/rcf/requirements/req-043.json +5 -2
  113. package/rcf/requirements/req-050.json +5 -2
  114. package/rcf/requirements/req-051.json +5 -2
  115. package/rcf/requirements/req-052.json +5 -2
  116. package/rcf/requirements/req-053.json +5 -2
  117. package/rcf/requirements/req-054.json +5 -2
  118. package/rcf/requirements/req-060.json +5 -2
  119. package/rcf/requirements/req-061.json +5 -2
  120. package/rcf/requirements/req-062.json +5 -2
  121. package/rcf/requirements/req-063.json +5 -2
  122. package/rcf/requirements/req-070.json +5 -2
  123. package/rcf/requirements/req-071.json +5 -2
  124. package/rcf/requirements/req-072.json +5 -2
  125. package/rcf/requirements/req-073.json +5 -2
  126. package/rcf/requirements/req-074.json +5 -2
  127. package/rcf/requirements/req-075.json +5 -2
  128. package/rcf/requirements/req-076.json +5 -2
  129. package/rcf/requirements/req-077.json +5 -2
  130. package/rcf/requirements/req-080.json +5 -2
  131. package/rcf/requirements/req-081.json +5 -2
  132. package/rcf/requirements/req-082.json +5 -2
  133. package/rcf/requirements/req-083.json +5 -2
  134. package/rcf/requirements/req-084.json +5 -2
  135. package/rcf/requirements/req-085.json +5 -2
  136. package/rcf/requirements/req-086.json +5 -2
  137. package/rcf/requirements/req-090.json +5 -2
  138. package/rcf/requirements/req-091.json +5 -2
  139. package/rcf/requirements/req-092.json +5 -2
  140. package/rcf/requirements/req-093.json +5 -2
  141. package/rcf/requirements/req-094.json +5 -2
  142. package/rcf/requirements/req-100.json +5 -2
  143. package/rcf/requirements/req-101.json +5 -2
  144. package/rcf/requirements/req-102.json +5 -2
  145. package/rcf/requirements/req-103.json +5 -2
  146. package/rcf/requirements/req-104.json +5 -2
  147. package/rcf/requirements/req-110.json +5 -2
  148. package/rcf/requirements/req-111.json +5 -2
  149. package/rcf/requirements/req-112.json +5 -2
  150. package/rcf/requirements/req-113.json +5 -2
  151. package/rcf/requirements/req-114.json +5 -2
  152. package/rcf/requirements/req-115.json +5 -2
  153. package/rcf/requirements/req-120.json +5 -2
  154. package/rcf/requirements/req-121.json +5 -2
  155. package/rcf/requirements/req-122.json +5 -2
  156. package/rcf/requirements/req-123.json +5 -2
  157. package/rcf/requirements/req-124.json +5 -2
  158. package/rcf/requirements/req-125.json +5 -2
  159. package/rcf/requirements/req-130.json +6 -2
  160. package/rcf/requirements/req-131.json +6 -2
  161. package/rcf/requirements/req-132.json +6 -2
  162. package/rcf/requirements/req-133.json +6 -2
  163. package/rcf/requirements/req-134.json +6 -2
  164. package/rcf/requirements/req-140.json +5 -2
  165. package/rcf/requirements/req-145.json +5 -2
  166. package/rcf/requirements/req-150.json +6 -2
  167. package/rcf/requirements/req-151.json +6 -2
  168. package/rcf/requirements/req-152.json +6 -2
  169. package/rcf/requirements/req-153.json +6 -2
  170. package/rcf/requirements/req-154.json +5 -2
  171. package/rcf/requirements/req-155.json +4 -1
  172. package/rcf/requirements/req-156.json +4 -1
  173. package/rcf/requirements/req-157.json +4 -1
  174. package/rcf/requirements/req-158.json +4 -1
  175. package/rcf/requirements/req-159.json +4 -1
  176. package/rcf/requirements/req-160.json +4 -1
  177. package/rcf/requirements/req-161.json +4 -1
  178. package/rcf/requirements/req-162.json +4 -1
  179. package/rcf/requirements/req-163.json +5 -2
  180. package/rcf/requirements/req-164.json +5 -2
  181. package/rcf/requirements/req-165.json +5 -2
  182. package/rcf/requirements/req-170.json +33 -0
  183. package/rcf/requirements/req-171.json +44 -0
  184. package/rcf/requirements/req-172.json +25 -0
  185. package/rcf/requirements/req-173.json +25 -0
  186. package/rcf/requirements/req-174.json +31 -0
  187. package/rcf/requirements/req-175.json +31 -0
  188. package/rcf/requirements/req-176.json +25 -0
  189. package/rcf/requirements/req-180.json +31 -0
  190. package/rcf/requirements/req-181.json +31 -0
  191. package/rcf/requirements/req-182.json +25 -0
  192. package/rcf/requirements/req-186.json +25 -0
  193. package/rcf/requirements/req-187.json +31 -0
  194. package/rcf/requirements/req-188.json +25 -0
  195. package/rcf/tacs/tac-4120-define-delta-and-freeze.json +21 -0
  196. package/rcf/tacs/tac-4121-define-ledgers.json +35 -0
  197. package/rcf/tacs/tac-4122-define-gates.json +61 -0
  198. package/rcf/tacs/tac-4123-define-readiness.json +61 -0
  199. package/rcf/tacs/tac-4124-define-freeze.json +28 -0
  200. package/rcf/tacs/tac-4127-readiness-view.json +49 -0
  201. package/rcf/tacs/tac-4128-define-guidance.json +53 -0
  202. package/rcf/tacs/tac-4129-define-questions.json +45 -0
  203. package/rcf/tacs/tac-4130-define-intake-brief.json +35 -0
  204. package/rcf/tacs/tac-4131-build-dag-view.json +39 -0
  205. package/rcf/tacs/tac-4132-id-lookup.json +42 -0
  206. package/rcf/tacs/tac-4133-readiness-po-layer.json +37 -0
  207. package/rcf/tacs/tac-4134-wespa-host-fixture.json +54 -0
  208. package/rcf/test-suites/ts-016.json +3 -3
  209. package/rcf/test-suites/ts-204.json +30 -0
  210. package/rcf/test-suites/ts-205.json +22 -0
  211. package/rcf/test-suites/ts-206.json +22 -0
  212. package/rcf/test-suites/ts-207.json +22 -0
  213. package/rcf/test-suites/ts-208.json +22 -0
  214. package/rcf/test-suites/ts-209.json +22 -0
  215. package/rcf/test-suites/ts-210.json +22 -0
  216. package/rcf/test-suites/ts-211.json +22 -0
  217. package/rcf/test-suites/ts-212.json +22 -0
  218. package/rcf/test-suites/ts-213.json +50 -0
  219. package/rcf/test-suites/ts-214.json +74 -0
  220. package/rcf/test-suites/ts-215.json +211 -0
  221. package/rcf/test-suites/ts-216.json +94 -0
  222. package/rcf/test-suites/ts-217.json +62 -0
  223. package/rcf/test-suites/ts-218.json +78 -0
  224. package/rcf/test-suites/ts-219.json +70 -0
  225. package/rcf/test-suites/ts-220.json +78 -0
  226. package/rcf/test-suites/ts-221.json +78 -0
  227. package/rcf/test-suites/ts-222.json +100 -0
  228. package/rcf/test-suites/ts-223.json +94 -0
  229. package/rcf/test-suites/ts-224.json +70 -0
  230. package/rcf/test-suites/ts-225.json +78 -0
  231. package/rcf/test-suites/ts-226.json +158 -0
  232. package/rcf/test-suites/ts-227.json +38 -0
  233. package/rcf/test-suites/ts-228.json +86 -0
  234. package/rcf/test-suites/ts-229.json +83 -0
  235. package/rcf/user-stories/us-15601.json +4 -4
  236. package/rcf/user-stories/us-17001.json +27 -0
  237. package/rcf/user-stories/us-17002.json +22 -0
  238. package/rcf/user-stories/us-17003.json +22 -0
  239. package/rcf/user-stories/us-17004.json +22 -0
  240. package/rcf/user-stories/us-17005.json +22 -0
  241. package/rcf/user-stories/us-17006.json +21 -0
  242. package/rcf/user-stories/us-17007.json +21 -0
  243. package/rcf/user-stories/us-17008.json +22 -0
  244. package/rcf/user-stories/us-17101.json +22 -0
  245. package/rcf/user-stories/us-17102.json +22 -0
  246. package/rcf/user-stories/us-17201.json +38 -0
  247. package/rcf/user-stories/us-17301.json +38 -0
  248. package/rcf/user-stories/us-17302.json +50 -0
  249. package/rcf/user-stories/us-17401.json +70 -0
  250. package/rcf/user-stories/us-17402.json +55 -0
  251. package/rcf/user-stories/us-17403.json +60 -0
  252. package/rcf/user-stories/us-17501.json +48 -0
  253. package/rcf/user-stories/us-17502.json +60 -0
  254. package/rcf/user-stories/us-17503.json +65 -0
  255. package/rcf/user-stories/us-17601.json +58 -0
  256. package/rcf/user-stories/us-18001.json +55 -0
  257. package/rcf/user-stories/us-18002.json +35 -0
  258. package/rcf/user-stories/us-18101.json +35 -0
  259. package/rcf/user-stories/us-18202.json +40 -0
  260. package/rcf/user-stories/us-18601.json +55 -0
  261. package/rcf/user-stories/us-18602.json +50 -0
  262. package/rcf/user-stories/us-18603.json +45 -0
  263. package/rcf/user-stories/us-18701.json +50 -0
  264. package/rcf/user-stories/us-18702.json +50 -0
  265. package/rcf/user-stories/us-18801.json +45 -0
  266. package/rcf/user-stories/us-204.json +59 -0
  267. package/rcf/user-stories/us-205.json +64 -0
  268. package/rcf/user-stories/us-206.json +54 -0
  269. package/releases/releases.yaml +31 -1
  270. package/src/cli/feedback.js +126 -10
  271. package/src/cli/freeze.js +730 -0
  272. package/src/cli/help.js +23 -0
  273. package/src/cli/ledger.js +615 -0
  274. package/src/cli/questions.js +288 -0
  275. package/src/cli/readiness.js +498 -0
  276. package/src/cli/view.js +29 -0
  277. package/src/core/store/writer.js +86 -6
  278. package/src/define/freeze-record.js +247 -0
  279. package/src/define/ledgers.js +712 -0
  280. package/src/feedback/redact.js +105 -19
  281. package/src/intake/index.js +1 -1
  282. package/src/intake/orchestrator.js +117 -0
  283. package/src/mcp/tools.js +354 -0
  284. package/src/query/delta.js +282 -0
  285. package/src/query/gates.js +1107 -0
  286. package/src/query/index.js +50 -0
  287. package/src/query/questions.js +438 -0
  288. package/src/query/readiness.js +574 -0
  289. package/src/server/index.js +60 -1
  290. package/src/server/routes.js +133 -4
  291. package/src/setup/identity-seed.js +17 -0
  292. package/src/view/build-dag.js +563 -0
  293. package/src/view/components/badge.js +41 -0
  294. package/src/view/components/diff.js +72 -0
  295. package/src/view/components/doc-row.js +62 -0
  296. package/src/view/components/empty-state.js +35 -0
  297. package/src/view/components/entity-selector.js +137 -0
  298. package/src/view/components/filter-bar.js +97 -0
  299. package/src/view/components/findings-list.js +49 -0
  300. package/src/view/components/index.js +12 -0
  301. package/src/view/components/pill.js +46 -0
  302. package/src/view/components/sub-tab-strip.js +43 -0
  303. package/src/view/components/toast.js +25 -0
  304. package/src/view/components-fixture.js +265 -0
  305. package/src/view/doc-renderers/architecture.js +304 -0
  306. package/src/view/doc-renderers/build.js +160 -0
  307. package/src/view/doc-renderers/helpers.js +2 -2
  308. package/src/view/doc-renderers/index.js +2 -0
  309. package/src/view/doc-renderers/prd.js +35 -6
  310. package/src/view/doc-renderers/req.js +10 -2
  311. package/src/view/doc-renderers/user-story.js +10 -5
  312. package/src/view/html-page.js +717 -300
  313. package/src/view/index.js +109 -3
  314. package/src/view/live-client.js +61 -8
  315. package/src/view/needs-work.js +79 -0
  316. package/src/view/page-init.js +2193 -0
  317. package/src/view/product-map.js +751 -0
  318. package/src/view/readiness/phrasebook.js +115 -0
  319. package/src/view/readiness/po-layer.js +288 -0
  320. package/src/view/readiness/question-adapter.js +329 -0
  321. package/src/view/readiness/stage-legend.js +71 -0
  322. package/src/view/readiness.js +505 -0
  323. package/src/view/style.css +2279 -266
  324. package/src/view/test-host/embed-client.js +121 -0
  325. package/src/view/test-host/fixture.js +183 -0
  326. package/src/view/test-host/lints.js +220 -0
  327. package/src/view/view-index.js +323 -0
@@ -0,0 +1,498 @@
1
+ // `rcf define readiness` subcommand handler (REQ-175; proposal
2
+ // 2026-09-22 §2.4, §6.2 v3; spec 2026-10-01 §2.3, §3, §4 for the
3
+ // 0.29.0 PR B additions).
4
+ //
5
+ // Prints the readiness object (§2.4) or its JSON envelope. The 0.29.0
6
+ // train added two verdict lines at the top of the text report (shared
7
+ // with the Readiness tab via `formatVerdictLines`) and two new flags:
8
+ // `--level intent|build` which drives the exit code against
9
+ // `levels.<which>.ok` (stricter than `--check all` on warn-with-ack
10
+ // failures, per spec section 3.2 decision 4; the `[warn]` line still
11
+ // prints), and `--persona productOwner|engineer` which is a display
12
+ // filter and never affects the exit code or JSON content. `--check`
13
+ // behaviour is unchanged. The producer is wrapped with
14
+ // `runWithAdmissibilityGate` (NV-BL-SR-03 addendum) so a chain that
15
+ // refuses admissibility short-circuits with the same refusal envelope
16
+ // every other query verb has.
17
+
18
+ import { parseArgs } from 'node:util';
19
+ import { readFile } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+
22
+ import { resolveTestPointers, walkTree } from '#core/store';
23
+ import { checkCodeNodeResolution } from '#core/store';
24
+ import { findProjectRoot } from '../view/index.js';
25
+ import { loadFreezeRecord } from '../define/freeze-record.js';
26
+ import { loadAllLedgers } from '../define/ledgers.js';
27
+ import {
28
+ STAGE_ALIASES,
29
+ STAGE_GATES,
30
+ STAGE_ORDER,
31
+ STAGE_SHORT_NAMES,
32
+ stagePolicy,
33
+ } from '../query/gates.js';
34
+ import {
35
+ computeReadiness,
36
+ formatTreeLine,
37
+ formatVerdictLines,
38
+ parseLevelFlag,
39
+ parsePersonaFlag,
40
+ } from '../query/readiness.js';
41
+ import { runWithAdmissibilityGate } from '../query/index.js';
42
+
43
+ const OPTION_SPEC = {
44
+ json: { type: 'boolean' },
45
+ check: { type: 'string' },
46
+ level: { type: 'string' },
47
+ persona: { type: 'string' },
48
+ help: { type: 'boolean' },
49
+ };
50
+
51
+ export const HELP = `Usage: rcf define readiness [options]
52
+
53
+ Compute and print the DEFINE readiness view: whether the tree is
54
+ freezeable, which stage gate blocks, what the delta and its fan-out
55
+ look like, and what the CLI recommends as the next action.
56
+
57
+ The compute is pure: it composes the freeze delta, per-id impact,
58
+ eight stage-gate checks (D1..D8), tree coverage and open decisions
59
+ into one object. The viewer's Readiness tab (slice 5) will render the
60
+ same object with no schema translation.
61
+
62
+ The text report prints two verdict lines at the top (shared with the
63
+ Readiness tab via formatVerdictLines): intent-complete (every
64
+ product-owner question answered) and ready-to-build (equals
65
+ freezeable). Blockers are grouped by persona, ordered by the
66
+ profile.md register marker.
67
+
68
+ Options:
69
+ --json Emit the full readiness object as JSON.
70
+ --persona is ignored under --json.
71
+ --check <stage> Narrow the output to one stage. Accepts a
72
+ stage id (D1..D8) or its short name:
73
+ brief | skeleton | shapes | stories |
74
+ crosscut | consistency | decisions |
75
+ freeze. Exits 4 on a blocking-stage
76
+ failure (D1 / D2 / D4 / D7 / D8); exits 0
77
+ with a visible '[warn]' line on an
78
+ unacknowledged warn-with-ack failure
79
+ (D3 / D5 / D6). Use --check all to print
80
+ every stage under this exit-code policy.
81
+ --level <intent|build> Pick which verdict the exit code follows.
82
+ --level intent exits 4 when
83
+ levels.intentComplete.ok is false
84
+ (any failing product-owner check); exits
85
+ 0 otherwise. --level build exits 4 when
86
+ levels.readyToBuild.ok is false, which is
87
+ stricter than --check all on unacked
88
+ warn-with-ack failures (the [warn] line
89
+ still prints). Combined with --check, the
90
+ invocation exits 4 if either policy
91
+ says 4. With neither flag the exit code
92
+ stays 0.
93
+ --persona <po|engineer> Display filter for the text report.
94
+ Values: productOwner | engineer. Collapses
95
+ the opposite-persona block to one line
96
+ with its check count and restricts the
97
+ per-stage detail to matching-persona
98
+ checks. Never affects the exit code or
99
+ the JSON content.
100
+ --help Print this help.
101
+ `;
102
+
103
+ /** Text label per stage state, for the chip line. */
104
+ const STATE_LABEL = {
105
+ passed: 'passed',
106
+ failing: 'failing',
107
+ acknowledged: 'acknowledged',
108
+ notApplicable: 'notApplicable',
109
+ };
110
+
111
+ /**
112
+ * Read `rcf/.identity/profile.md` when it exists; return null on
113
+ * ENOENT. Any other read error surfaces as null so the profile
114
+ * markers just fail to appear (the D1 check treats absence as a
115
+ * finding, not a runtime error).
116
+ *
117
+ * @param {string} projectRoot
118
+ * @returns {Promise<string|null>}
119
+ */
120
+ async function readProfileText(projectRoot) {
121
+ try {
122
+ return await readFile(join(projectRoot, 'rcf', '.identity', 'profile.md'), 'utf8');
123
+ } catch (err) {
124
+ if (/** @type {NodeJS.ErrnoException} */ (err).code === 'ENOENT') return null;
125
+ return null;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Pick the profile register from the text, returning one of
131
+ * `productOwner` | `engineer` | `unstated`. The marker is a bare
132
+ * word match (same convention as `checkD1Brief`); the first marker
133
+ * found in the text wins. Absent or unrecognised yields `unstated`,
134
+ * which the text report orders as PO first (spec section 4).
135
+ *
136
+ * @param {string | null} text
137
+ * @returns {'productOwner' | 'engineer' | 'unstated'}
138
+ */
139
+ function pickRegister(text) {
140
+ if (typeof text !== 'string' || text.length === 0) return 'unstated';
141
+ // Scan in file-order so the first marker in the document wins;
142
+ // this matches how a human reads `profile.md`.
143
+ const markers = ['productOwner', 'engineer', 'unstated'];
144
+ let best = null;
145
+ let bestIdx = Infinity;
146
+ for (const m of markers) {
147
+ const idx = text.indexOf(m);
148
+ if (idx === -1) continue;
149
+ if (idx < bestIdx) {
150
+ bestIdx = idx;
151
+ best = m;
152
+ }
153
+ }
154
+ return /** @type {any} */ (best) ?? 'unstated';
155
+ }
156
+
157
+ /**
158
+ * @param {string[]} argv
159
+ * @param {object} [deps]
160
+ * @returns {Promise<number>}
161
+ */
162
+ export async function main(argv, deps = {}) {
163
+ const stdout = deps.stdout ?? process.stdout;
164
+ const stderr = deps.stderr ?? process.stderr;
165
+ const cwd = deps.cwd ?? process.cwd();
166
+
167
+ let parsed;
168
+ try {
169
+ parsed = parseArgs({ args: argv, options: OPTION_SPEC, allowPositionals: false, strict: true });
170
+ } catch (err) {
171
+ stderr.write(`[error] usage ${err.message}\n`);
172
+ stderr.write(HELP);
173
+ return 2;
174
+ }
175
+ const flags = parsed.values;
176
+ if (flags.help) {
177
+ stdout.write(HELP);
178
+ return 0;
179
+ }
180
+
181
+ const checkArg = flags.check;
182
+ let checkStage = null;
183
+ if (typeof checkArg === 'string') {
184
+ if (checkArg === 'all') {
185
+ checkStage = 'all';
186
+ } else if (STAGE_ALIASES[checkArg]) {
187
+ checkStage = STAGE_ALIASES[checkArg];
188
+ } else {
189
+ stderr.write(`[error] usage readiness: unknown --check ${checkArg} (expected D1..D8, one of ${Object.values(STAGE_SHORT_NAMES).join(' | ')}, or 'all')\n`);
190
+ return 2;
191
+ }
192
+ }
193
+
194
+ /** @type {'intent' | 'build' | null} */
195
+ let level;
196
+ try {
197
+ level = parseLevelFlag(flags.level);
198
+ } catch (err) {
199
+ stderr.write(`[error] usage readiness: ${/** @type {Error} */ (err).message}\n`);
200
+ return 2;
201
+ }
202
+
203
+ /** @type {'productOwner' | 'engineer' | null} */
204
+ let persona;
205
+ try {
206
+ persona = parsePersonaFlag(flags.persona);
207
+ } catch (err) {
208
+ stderr.write(`[error] usage readiness: ${/** @type {Error} */ (err).message}\n`);
209
+ return 2;
210
+ }
211
+
212
+ const projectRoot = await findProjectRoot(cwd);
213
+ if (!projectRoot) {
214
+ stderr.write('[error] usage no project root found (no rcf/manifest.json in this directory or any ancestor). Run `npx rcf init` to create and wire a project.\n');
215
+ return 2;
216
+ }
217
+
218
+ const { tree, errors } = await walkTree({ projectRoot });
219
+ const staleErrors = await checkCodeNodeResolution({ projectRoot, tree });
220
+ const validateErrors = [...errors, ...staleErrors];
221
+
222
+ const [freeze, ledgers, testPointers, profileText] = await Promise.all([
223
+ loadFreezeRecord({ projectRoot }),
224
+ loadAllLedgers({ projectRoot }),
225
+ resolveTestPointers({ projectRoot, tree }),
226
+ readProfileText(projectRoot),
227
+ ]);
228
+
229
+ const startedAt = Date.now();
230
+ const chainRulesetVersion = typeof tree.manifest?.rulesetVersion === 'string'
231
+ ? tree.manifest.rulesetVersion
232
+ : null;
233
+
234
+ // Readiness is a diagnostic: even a chain that refuses admissibility
235
+ // wants to know which stage gate blocks it. The wrap runs first so
236
+ // the ruleset toolScope guard is honoured (NV-BL-SR-03 addendum);
237
+ // on refuse the refusal envelope is threaded through as informational
238
+ // context and the compute still runs (ADR-4123).
239
+ const gated = await runWithAdmissibilityGate({
240
+ tree,
241
+ chainRulesetVersion,
242
+ produce: () => computeReadiness(tree, {
243
+ freeze,
244
+ ledgers,
245
+ profile: undefined,
246
+ profileText,
247
+ testPointers,
248
+ validateErrors,
249
+ }),
250
+ });
251
+
252
+ /** @type {import('../query/readiness.js').ReadinessResult} */
253
+ const result = gated.status === 'refused-admissibility'
254
+ ? computeReadiness(tree, {
255
+ freeze, ledgers, profile: undefined, profileText, testPointers, validateErrors,
256
+ })
257
+ : gated.payload;
258
+ const wallMs = Date.now() - startedAt;
259
+
260
+ if (gated.status === 'refused-admissibility') {
261
+ stderr.write(`[warn] readiness: chain admissibility refused (informational; the readiness compute still ran). ${gated.refusal}\n`);
262
+ }
263
+
264
+ if (flags.json) {
265
+ // JSON emission carries the full object plus the wall-time hint
266
+ // and the invocation level as a stable side-band on `_meta`.
267
+ // `_meta.level` is null when the flag was absent (spec section
268
+ // 3.3): consumers can tell "no --level given" from "--level
269
+ // build" explicitly, which matters for the ticket artefact.
270
+ const envelope = { ...result, _meta: { wallMs, level } };
271
+ stdout.write(`${JSON.stringify(envelope, null, 2)}\n`);
272
+ return decideExitCode(result, checkStage, level, stderr);
273
+ }
274
+
275
+ renderText(stdout, stderr, result, wallMs, checkStage, level, persona, profileText);
276
+ return decideExitCode(result, checkStage, level, stderr);
277
+ }
278
+
279
+ /**
280
+ * Emit the text summary (spec section 4):
281
+ * 1. Tree line.
282
+ * 2. Verdict pair (intent-complete, ready-to-build).
283
+ * 3. Next action, chip line, delta, coverage, decisions, freezeable
284
+ * (today's lines; omitted when --check narrows to one stage).
285
+ * 4. Product-owner block and engineer block, ordered by the
286
+ * profile.md register (PO first by default; engineer first when
287
+ * the register is `engineer`; `unstated`/absent is PO first).
288
+ * With --persona the opposite-persona block collapses to one
289
+ * line; with --check <stage> the persona blocks are limited to
290
+ * that stage.
291
+ * 5. Per-stage detail block (today's output; persona is now inside
292
+ * the parenthesis after `over`). With --persona only the
293
+ * matching-persona checks are rendered.
294
+ *
295
+ * @param {NodeJS.WritableStream} stdout
296
+ * @param {NodeJS.WritableStream} stderr
297
+ * @param {import('../query/readiness.js').ReadinessResult} result
298
+ * @param {number} wallMs
299
+ * @param {string | null} checkStage
300
+ * @param {'intent' | 'build' | null} level
301
+ * @param {'productOwner' | 'engineer' | null} persona
302
+ * @param {string | null} profileText
303
+ */
304
+ function renderText(stdout, stderr, result, wallMs, checkStage, level, persona, profileText) {
305
+ stdout.write(`${formatTreeLine(result)}\n`);
306
+
307
+ const verdicts = formatVerdictLines(result);
308
+ stdout.write(`${verdicts.intentComplete}\n`);
309
+ stdout.write(`${verdicts.readyToBuild}\n`);
310
+
311
+ if (!checkStage || checkStage === 'all') {
312
+ renderNextActions(stdout, result, level);
313
+ stdout.write(`Chips: ${formatChipLine(result)}\n`);
314
+ stdout.write(`Delta: changed ${result.delta.changed.length}, added ${result.delta.added.length}, removed ${result.delta.removed.length}, briefSince ${result.delta.briefSince.length}, impacted ${result.delta.impacted.length}, impactedFbs ${result.delta.impactedFbs.length}.\n`);
315
+ stdout.write(`Coverage: tree ${result.coverage.tree.totals.covered}/${result.coverage.tree.totals.requirements} covered (strict), ${result.coverage.delta.length} REQ ancestor(s) scoped from the delta.\n`);
316
+ stdout.write(`Decisions open: ${result.decisions.length}.\n`);
317
+ stdout.write(`Freezeable: ${result.freezeable ? 'yes' : 'no'}. Compute: ${wallMs} ms.\n`);
318
+ }
319
+
320
+ const register = pickRegister(profileText);
321
+ renderPersonaBlocks(stdout, result, persona, register, checkStage);
322
+
323
+ for (const stage of result.stages) {
324
+ if (checkStage && checkStage !== 'all' && stage.stage !== checkStage) continue;
325
+ stdout.write(`\n${stage.stage} (${stage.gate}): ${STATE_LABEL[stage.state] ?? stage.state}${stage.reason ? ` (${stage.reason})` : ''}\n`);
326
+ for (const c of stage.checks) {
327
+ if (persona && c.persona !== persona) continue;
328
+ const mark = c.ok ? 'ok' : 'FAIL';
329
+ stdout.write(` [${mark}] ${c.name} (${c.over}, ${c.persona}): ${c.pass}/${c.total}\n`);
330
+ for (const f of c.failing.slice(0, 20)) {
331
+ stdout.write(` - ${f.id}: ${f.why}\n`);
332
+ }
333
+ if (c.failing.length > 20) {
334
+ stdout.write(` ... ${c.failing.length - 20} more suppressed\n`);
335
+ }
336
+ }
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Render the per-persona next-action lines (spec section 4). When a
342
+ * `--level` is given the matching persona's line heads the pair; when
343
+ * no `--level` is given the pair follows the register order. Each
344
+ * line is `Next action (<persona>): <stage> / <check>; ids: ...`.
345
+ *
346
+ * @param {NodeJS.WritableStream} stdout
347
+ * @param {import('../query/readiness.js').ReadinessResult} result
348
+ * @param {'intent' | 'build' | null} level
349
+ */
350
+ function renderNextActions(stdout, result, level) {
351
+ const po = result.personas.productOwner.nextAction;
352
+ const eng = result.personas.engineer.nextAction;
353
+ const writeAction = (label, action) => {
354
+ if (!action) {
355
+ stdout.write(`Next action (${label}): none.\n`);
356
+ return;
357
+ }
358
+ const ids = action.ids.length > 0 ? `; ids: ${action.ids.join(', ')}` : '';
359
+ stdout.write(`Next action (${label}): ${action.stage} / ${action.check}${ids}. Run \`${action.command}\` after editing.\n`);
360
+ };
361
+ writeAction('product owner', po);
362
+ writeAction('engineer', eng);
363
+ }
364
+
365
+ /**
366
+ * Render the two persona-grouped blocker blocks (spec section 4).
367
+ * `register` orders the pair; `persona` (the display filter) collapses
368
+ * the opposite block to one count line; `checkStage` (when not null
369
+ * or 'all') restricts both blocks to blockers in that stage.
370
+ *
371
+ * @param {NodeJS.WritableStream} stdout
372
+ * @param {import('../query/readiness.js').ReadinessResult} result
373
+ * @param {'productOwner' | 'engineer' | null} persona
374
+ * @param {'productOwner' | 'engineer' | 'unstated'} register
375
+ * @param {string | null} checkStage
376
+ */
377
+ function renderPersonaBlocks(stdout, result, persona, register, checkStage) {
378
+ const stageFilter = (bs) => (checkStage && checkStage !== 'all'
379
+ ? bs.filter((b) => b.stage === checkStage)
380
+ : bs);
381
+ // L1 blockedBy for the PO list (ignores stage state); L2 blockedBy
382
+ // minus PO entries for the engineer list, matching
383
+ // `personas.engineer.blockers`.
384
+ const poBlockers = stageFilter(result.personas.productOwner.blockers);
385
+ const engineerBlockers = stageFilter(result.personas.engineer.blockers);
386
+
387
+ const order = register === 'engineer'
388
+ ? [['engineer', engineerBlockers], ['productOwner', poBlockers]]
389
+ : [['productOwner', poBlockers], ['engineer', engineerBlockers]];
390
+
391
+ for (const [p, blockers] of order) {
392
+ stdout.write('\n');
393
+ const headerLabel = p === 'productOwner' ? 'Product owner' : 'Engineer';
394
+ const noun = p === 'productOwner' ? 'question' : 'check blocking';
395
+ const nounPlural = p === 'productOwner' ? 'questions' : 'checks blocking';
396
+ if (persona && p !== persona) {
397
+ stdout.write(`${headerLabel}: ${blockers.length} ${blockers.length === 1 ? noun : nounPlural} (hidden; run without --persona)\n`);
398
+ continue;
399
+ }
400
+ if (blockers.length === 0) {
401
+ stdout.write(`${headerLabel}: 0 ${nounPlural}.\n`);
402
+ continue;
403
+ }
404
+ stdout.write(`${headerLabel}: ${blockers.length} ${blockers.length === 1 ? noun : nounPlural}\n`);
405
+ for (const b of blockers) {
406
+ stdout.write(` ${b.stage} ${b.check}: ${b.question} ${b.failingCount}/${b.failingCount}\n`);
407
+ for (const id of b.ids.slice(0, 20)) {
408
+ stdout.write(` - ${id}\n`);
409
+ }
410
+ if (b.failingCount > b.ids.length) {
411
+ stdout.write(` ... ${b.failingCount - b.ids.length} more suppressed\n`);
412
+ }
413
+ }
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Compose the chip line: "D1:passed D2:failing D3:acknowledged ..."
419
+ *
420
+ * @param {import('../query/readiness.js').ReadinessResult} result
421
+ * @returns {string}
422
+ */
423
+ function formatChipLine(result) {
424
+ return result.stages.map((s) => `${s.stage}:${s.state}`).join(' ');
425
+ }
426
+
427
+ /**
428
+ * Decide the exit code for an invocation (spec section 3.2 matrix):
429
+ * - No `--check` and no `--level`: always 0.
430
+ * - `--check` alone: today's stage policy (4 on blocking failure,
431
+ * 0 with `[warn]` on warn-with-ack failure).
432
+ * - `--level intent`: 4 iff `levels.intentComplete.ok === false`.
433
+ * - `--level build`: 4 iff `levels.readyToBuild.ok === false`
434
+ * (stricter than `--check all`; the warn line still prints).
435
+ * - Both: 4 if either policy says 4.
436
+ *
437
+ * Warn lines are emitted whenever a warn-with-ack stage is failing,
438
+ * independent of exit code, so an operator always sees why.
439
+ *
440
+ * @param {import('../query/readiness.js').ReadinessResult} result
441
+ * @param {string | null} checkStage
442
+ * @param {'intent' | 'build' | null} level
443
+ * @param {NodeJS.WritableStream} stderr
444
+ * @returns {number}
445
+ */
446
+ function decideExitCode(result, checkStage, level, stderr) {
447
+ let exitCode = 0;
448
+
449
+ // --check policy (unchanged from PR A).
450
+ if (checkStage) {
451
+ const stages = checkStage === 'all'
452
+ ? result.stages
453
+ : result.stages.filter((s) => s.stage === checkStage);
454
+ for (const s of stages) {
455
+ if (s.state !== 'failing') continue;
456
+ const policy = stagePolicy(s.stage);
457
+ if (policy === 'blocking') {
458
+ exitCode = 4;
459
+ } else {
460
+ stderr.write(`[warn] readiness: ${s.stage} (${s.gate}) is failing without an acknowledgement at the current tree hash. Run \`rcf define freeze --ack ${s.gate} --reason "<text>"\` to acknowledge, or edit the tree to clear the failure.\n`);
461
+ }
462
+ }
463
+ }
464
+
465
+ // --level policy. When explicit, exit 4 if that level says "no".
466
+ // --level build is stricter than --check all: it exits 4 even on an
467
+ // unacknowledged warn-with-ack failure (spec decision 4). The warn
468
+ // lines are still emitted (above when --check all is also set, or
469
+ // here when --level build is given alone).
470
+ if (level === 'intent' && result.levels.intentComplete.ok === false) {
471
+ exitCode = 4;
472
+ } else if (level === 'build' && result.levels.readyToBuild.ok === false) {
473
+ exitCode = 4;
474
+ // When --level build is set without --check all, we have not yet
475
+ // emitted the per-stage warn lines. Emit them here so an operator
476
+ // still sees which warn-with-ack stage drove the "no".
477
+ if (!checkStage || checkStage !== 'all') {
478
+ const seen = new Set();
479
+ if (checkStage) {
480
+ // --level build + --check <stage>: the --check branch already
481
+ // emitted that stage's warn line (if any). Avoid duplicates.
482
+ seen.add(checkStage);
483
+ }
484
+ for (const s of result.stages) {
485
+ if (seen.has(s.stage)) continue;
486
+ if (s.state !== 'failing') continue;
487
+ if (stagePolicy(s.stage) === 'blocking') continue;
488
+ stderr.write(`[warn] readiness: ${s.stage} (${s.gate}) is failing without an acknowledgement at the current tree hash. Run \`rcf define freeze --ack ${s.gate} --reason "<text>"\` to acknowledge, or edit the tree to clear the failure.\n`);
489
+ }
490
+ }
491
+ }
492
+
493
+ return exitCode;
494
+ }
495
+
496
+ // Re-export the gate map so consumers importing this module (help,
497
+ // slice 3) share one seam.
498
+ export { STAGE_GATES, STAGE_ORDER, STAGE_SHORT_NAMES };
package/src/cli/view.js CHANGED
@@ -92,6 +92,13 @@ Options:
92
92
  and CI is unset).
93
93
  --verbose Log each watch event and each SSE broadcast to
94
94
  stderr.
95
+ --test-host Mount the wespa host fixture at /test-host.html
96
+ plus its client script at /test-host.js. Off by
97
+ default; the fixture is a test-suite proof that
98
+ the viewer honours Dex's embedding contract (viewer
99
+ UI refresh PR 9; TAC-4134, ADR-4136), not a shipped
100
+ UI, so wespa's reverse-proxy allow-list is
101
+ unaffected. Can also be set via RCF_VIEW_TEST_HOST=1.
95
102
  --help Print this help and exit.
96
103
 
97
104
  Security posture:
@@ -130,6 +137,7 @@ export function parseArgs(argv) {
130
137
  help: false,
131
138
  noOpen: false,
132
139
  port: null,
140
+ testHost: false,
133
141
  };
134
142
  const errors = [];
135
143
  for (let i = 0; i < argv.length; i += 1) {
@@ -148,6 +156,13 @@ export function parseArgs(argv) {
148
156
  case '-h':
149
157
  opts.help = true;
150
158
  break;
159
+ case '--test-host':
160
+ // Viewer UI refresh PR 9 (TAC-4134, ADR-4136): mount the wespa
161
+ // host fixture at /test-host.html plus its client at
162
+ // /test-host.js. Off by default; the fixture is a test-suite
163
+ // proof, not a shipped UI.
164
+ opts.testHost = true;
165
+ break;
151
166
  case '--port': {
152
167
  const next = argv[i + 1];
153
168
  if (next === undefined || next.startsWith('--')) {
@@ -170,6 +185,19 @@ export function parseArgs(argv) {
170
185
  return { opts, errors };
171
186
  }
172
187
 
188
+ /**
189
+ * Resolve the testHost gate: `--test-host` beats `RCF_VIEW_TEST_HOST=1`
190
+ * env beats default (false). Viewer UI refresh PR 9 (TAC-4134).
191
+ *
192
+ * @param {boolean} flagTestHost
193
+ * @param {NodeJS.ProcessEnv} env
194
+ * @returns {boolean}
195
+ */
196
+ export function resolveTestHost(flagTestHost, env) {
197
+ if (flagTestHost === true) return true;
198
+ return env.RCF_VIEW_TEST_HOST === '1';
199
+ }
200
+
173
201
  /**
174
202
  * Resolve port precedence: --port beats RCF_VIEW_PORT env beats default.
175
203
  *
@@ -294,6 +322,7 @@ export async function main(argv, deps = {}) {
294
322
  projectRoot,
295
323
  port: resolvedPort,
296
324
  log: logSink,
325
+ testHost: resolveTestHost(opts.testHost, env),
297
326
  });
298
327
  } catch (err) {
299
328
  if (/** @type {NodeJS.ErrnoException} */ (err).code === 'EADDRINUSE') {
@@ -200,18 +200,98 @@ export function nextIdForKind(tree, kind, opts = {}) {
200
200
  // one numbering group.
201
201
  const groupNum = Number(normaliseId(match[1]));
202
202
  const groupLabel = String(groupNum);
203
+ // Occupancy is every US id in the tree. Each id is classified as
204
+ // ENCODED (`US-<reqNum><localTwoDigit>` where the reqNum names an
205
+ // existing REQ and local is 01..99) or FLAT (a bare sequential
206
+ // number that carries no parent-encoded suffix, as produced by
207
+ // legacy trees migrated in from WESPA v1). Classification decides
208
+ // the allocation rule:
209
+ // - all-encoded tree (or empty): the historical rule, extend
210
+ // `US-<groupLabel><nextLocal>`.
211
+ // - all-flat tree: extend the flat sequence past the highest
212
+ // existing US number (issue #256 / w-2026-09-29-dave-005).
213
+ // - mixed tree: refuse the mint with an explicit error naming
214
+ // both schemes, so an operator normalises the tree before a
215
+ // new id is issued (Dave disposition 2026-09-30).
216
+ // AC minting is unchanged; #256 was reproduced against USes only.
217
+ // Classification prefers the doc's declared reqId (unambiguous) over
218
+ // the id-only heuristic. Without that, a legacy US-163 filed under
219
+ // REQ-053 would decompose as parent=1/local=63 and look encoded
220
+ // whenever REQ-001 happened to exist, defeating the whole rule.
221
+ const usIds = occupiedIdsOfKind(tree, 'userStory');
222
+ const reqNums = new Set();
223
+ for (const rId of occupiedIdsOfKind(tree, 'req')) {
224
+ const rn = idNumber(rId, 'REQ');
225
+ if (rn !== null) reqNums.add(rn);
226
+ }
227
+ const encoded = [];
228
+ const flat = [];
229
+ const seenUsNums = new Set();
230
+ for (const usId of usIds) {
231
+ const num = idNumber(usId, 'US');
232
+ if (num === null) continue;
233
+ // occupiedIdsOfKind emits both the on-disk id and the doc's
234
+ // declared id field, so the same numeric id appears twice.
235
+ // Dedupe on the numeric value to avoid double-counting.
236
+ if (seenUsNums.has(num)) continue;
237
+ seenUsNums.add(num);
238
+ const localPart = num % 100;
239
+ const parentPart = Math.floor(num / 100);
240
+ const doc = tree.byId.get(usId);
241
+ let declaredReqNum = null;
242
+ if (doc && typeof doc.reqId === 'string') {
243
+ const mReq = /^REQ-(\d+)$/.exec(doc.reqId);
244
+ if (mReq) declaredReqNum = Number(normaliseId(mReq[1]));
245
+ }
246
+ let isEncoded;
247
+ if (declaredReqNum !== null) {
248
+ // Encoded iff the id decomposes as <declaredReqNum><two-digit
249
+ // local in 01..99>. Any other shape is flat.
250
+ isEncoded = (localPart >= 1 && localPart <= 99 && parentPart === declaredReqNum);
251
+ } else {
252
+ // Invalid / unloadable doc: fall back to the id-only heuristic
253
+ // (matches historical behaviour when the parent-part names an
254
+ // existing REQ).
255
+ isEncoded = (localPart >= 1 && localPart <= 99 && reqNums.has(parentPart));
256
+ }
257
+ if (isEncoded) {
258
+ encoded.push({ id: usId, num, parentPart, localPart });
259
+ } else {
260
+ flat.push({ id: usId, num });
261
+ }
262
+ }
263
+
264
+ if (encoded.length > 0 && flat.length > 0) {
265
+ const encodedExample = encoded[0].id;
266
+ const flatExample = flat[0].id;
267
+ throw new TypeError(
268
+ 'nextIdForKind us: refusing to mint - the tree mixes '
269
+ + `encoded US ids (e.g. ${encodedExample}, shape US-<reqNum><localTwoDigit>) `
270
+ + `and flat US ids (e.g. ${flatExample}, shape US-<seq>). `
271
+ + 'Normalise every US id to one scheme (rename the outliers, '
272
+ + 'update every reference) and retry, or ask HQ for a bulk '
273
+ + 're-mint. Auto-mint intentionally refuses on ambiguous trees.',
274
+ );
275
+ }
276
+
277
+ if (flat.length > 0 && encoded.length === 0) {
278
+ let maxFlat = 0;
279
+ for (const f of flat) {
280
+ if (f.num > maxFlat) maxFlat = f.num;
281
+ }
282
+ return `US-${maxFlat + 1}`;
283
+ }
284
+
285
+ // All-encoded (or empty) tree: keep the historical behaviour.
203
286
  // Occupancy is every US id that numerically falls in this group,
204
287
  // whatever `reqId` string it names. Filtering on an exact reqId
205
288
  // string match was the bug: a US filed under `REQ-0001` was
206
289
  // invisible when allocating for `REQ-001`, so US-101 got re-issued
207
290
  // on top of the existing US-101.
208
- const usIds = occupiedIdsOfKind(tree, 'userStory');
209
291
  let maxLocal = 0;
210
- for (const usId of usIds) {
211
- const num = idNumber(usId, 'US');
212
- if (num === null) continue;
213
- const local = num - groupNum * 100;
214
- if (local >= 1 && local <= 99 && local > maxLocal) maxLocal = local;
292
+ for (const e of encoded) {
293
+ if (e.parentPart !== groupNum) continue;
294
+ if (e.localPart > maxLocal) maxLocal = e.localPart;
215
295
  }
216
296
  const nextLocal = maxLocal + 1;
217
297
  return `US-${groupLabel}${String(nextLocal).padStart(2, '0')}`;