universal-dev-standards 6.13.1 → 6.14.0-beta.10

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 (693) hide show
  1. package/README.md +13 -3
  2. package/bin/uds.js +75 -3
  3. package/bundled/ai/options/code-review/pr-review.ai.yaml +20 -1
  4. package/bundled/ai/options/commit-message/traditional-chinese.ai.yaml +69 -67
  5. package/bundled/ai/standards/ai-response-navigation.ai.yaml +43 -3
  6. package/bundled/ai/standards/checkin-standards.ai.yaml +25 -6
  7. package/bundled/ai/standards/code-review.ai.yaml +15 -2
  8. package/bundled/ai/standards/commit-message.ai.yaml +18 -4
  9. package/bundled/ai/standards/developer-memory.ai.yaml +12 -2
  10. package/bundled/ai/standards/full-coverage-testing.ai.yaml +86 -7
  11. package/bundled/ai/standards/open-work-tracking.ai.yaml +254 -4
  12. package/bundled/ai/standards/pipeline-security-gates.ai.yaml +53 -4
  13. package/bundled/ai/standards/project-context-memory.ai.yaml +12 -2
  14. package/bundled/ai/standards/turn-completion-integrity.ai.yaml +14 -7
  15. package/bundled/core/ai-response-navigation.md +128 -12
  16. package/bundled/core/code-review-checklist.md +20 -2
  17. package/bundled/core/commit-message-guide.md +22 -19
  18. package/bundled/core/developer-memory.md +12 -2
  19. package/bundled/core/full-coverage-testing.md +99 -5
  20. package/bundled/core/open-work-tracking.md +251 -8
  21. package/bundled/core/pipeline-security-gates.md +63 -0
  22. package/bundled/core/project-context-memory.md +10 -2
  23. package/bundled/core/turn-completion-integrity.md +58 -11
  24. package/bundled/extensions/frameworks/fat-free-patterns.md +937 -0
  25. package/bundled/extensions/languages/csharp-style.md +464 -0
  26. package/bundled/extensions/languages/php-style.md +700 -0
  27. package/bundled/extensions/locales/zh-cn.md +717 -0
  28. package/bundled/extensions/locales/zh-tw.md +717 -0
  29. package/bundled/hooks/check-turn-completion-agy.mjs +147 -0
  30. package/bundled/hooks/turn-completion/locales/en.mjs +54 -5
  31. package/bundled/hooks/turn-completion/locales/zh-TW.mjs +37 -6
  32. package/bundled/locales/COVERAGE.md +5 -4
  33. package/bundled/locales/zh-CN/CHANGELOG.md +211 -3
  34. package/bundled/locales/zh-CN/README.md +3 -3
  35. package/bundled/locales/zh-CN/SECURITY.md +3 -1
  36. package/bundled/locales/zh-CN/STANDARDS-MAPPING.md +103 -6
  37. package/bundled/locales/zh-CN/adoption/ADOPTION-GUIDE.md +81 -101
  38. package/bundled/locales/zh-CN/adoption/DAILY-WORKFLOW-GUIDE.md +2 -1
  39. package/bundled/locales/zh-CN/adoption/STATIC-DYNAMIC-GUIDE.md +14 -9
  40. package/bundled/locales/zh-CN/adoption/checklists/enterprise.md +88 -81
  41. package/bundled/locales/zh-CN/adoption/checklists/minimal.md +31 -17
  42. package/bundled/locales/zh-CN/adoption/checklists/recommended.md +56 -47
  43. package/bundled/locales/zh-CN/ai/MAINTENANCE.md +44 -9
  44. package/bundled/locales/zh-CN/ai/options/commit-message/traditional-chinese.ai.yaml +63 -55
  45. package/bundled/locales/zh-CN/core/acceptance-criteria-traceability.md +61 -14
  46. package/bundled/locales/zh-CN/core/acceptance-test-driven-development.md +2 -1
  47. package/bundled/locales/zh-CN/core/adr-standards.md +155 -32
  48. package/bundled/locales/zh-CN/core/agent-communication-protocol.md +2 -1
  49. package/bundled/locales/zh-CN/core/agent-dispatch.md +68 -33
  50. package/bundled/locales/zh-CN/core/ai-agreement-standards.md +23 -22
  51. package/bundled/locales/zh-CN/core/ai-command-behavior.md +2 -1
  52. package/bundled/locales/zh-CN/core/ai-instruction-standards.md +71 -49
  53. package/bundled/locales/zh-CN/core/ai-response-navigation.md +111 -12
  54. package/bundled/locales/zh-CN/core/anti-sycophancy-prompting.md +34 -33
  55. package/bundled/locales/zh-CN/core/api-design-standards.md +144 -58
  56. package/bundled/locales/zh-CN/core/behavior-driven-development.md +2 -1
  57. package/bundled/locales/zh-CN/core/branch-completion.md +75 -20
  58. package/bundled/locales/zh-CN/core/capability-declaration.md +44 -94
  59. package/bundled/locales/zh-CN/core/change-batching-standards.md +2 -1
  60. package/bundled/locales/zh-CN/core/checkin-standards.md +176 -116
  61. package/bundled/locales/zh-CN/core/circuit-breaker.md +43 -77
  62. package/bundled/locales/zh-CN/core/code-review-checklist.md +54 -23
  63. package/bundled/locales/zh-CN/core/context-aware-loading.md +103 -29
  64. package/bundled/locales/zh-CN/core/database-standards.md +115 -114
  65. package/bundled/locales/zh-CN/core/developer-memory.md +159 -60
  66. package/bundled/locales/zh-CN/core/documentation-lifecycle.md +20 -16
  67. package/bundled/locales/zh-CN/core/dual-phase-output.md +37 -70
  68. package/bundled/locales/zh-CN/core/execution-history.md +2 -1
  69. package/bundled/locales/zh-CN/core/failure-source-taxonomy.md +71 -84
  70. package/bundled/locales/zh-CN/core/full-coverage-testing.md +103 -9
  71. package/bundled/locales/zh-CN/core/git-workflow.md +148 -262
  72. package/bundled/locales/zh-CN/core/git-worktree.md +59 -26
  73. package/bundled/locales/zh-CN/core/guides/file-placement-guide.md +132 -48
  74. package/bundled/locales/zh-CN/core/guides/performance-guide.md +61 -59
  75. package/bundled/locales/zh-CN/core/guides/security-guide.md +2 -0
  76. package/bundled/locales/zh-CN/core/health-check-standards.md +46 -104
  77. package/bundled/locales/zh-CN/core/immutability-first.md +83 -60
  78. package/bundled/locales/zh-CN/core/knowledge-transfer-standards.md +94 -31
  79. package/bundled/locales/zh-CN/core/pipeline-integration-standards.md +2 -1
  80. package/bundled/locales/zh-CN/core/pipeline-security-gates.md +64 -4
  81. package/bundled/locales/zh-CN/core/project-context-memory.md +5 -0
  82. package/bundled/locales/zh-CN/core/recovery-recipe-registry.md +54 -114
  83. package/bundled/locales/zh-CN/core/refactoring-standards.md +141 -556
  84. package/bundled/locales/zh-CN/core/requirement-engineering.md +7 -6
  85. package/bundled/locales/zh-CN/core/retry-standards.md +46 -101
  86. package/bundled/locales/zh-CN/core/security-decision.md +45 -70
  87. package/bundled/locales/zh-CN/core/skill-standard-alignment-check.md +105 -71
  88. package/bundled/locales/zh-CN/core/standard-admission-criteria.md +25 -31
  89. package/bundled/locales/zh-CN/core/standard-lifecycle-management.md +49 -57
  90. package/bundled/locales/zh-CN/core/structured-task-definition.md +2 -1
  91. package/bundled/locales/zh-CN/core/systematic-debugging.md +87 -42
  92. package/bundled/locales/zh-CN/core/test-completeness-dimensions.md +262 -190
  93. package/bundled/locales/zh-CN/core/test-driven-development.md +21 -1022
  94. package/bundled/locales/zh-CN/core/test-governance.md +94 -43
  95. package/bundled/locales/zh-CN/core/testing-standards.md +83 -37
  96. package/bundled/locales/zh-CN/core/timeout-standards.md +45 -85
  97. package/bundled/locales/zh-CN/core/token-budget.md +44 -80
  98. package/bundled/locales/zh-CN/core/translation-lifecycle-standards.md +48 -36
  99. package/bundled/locales/zh-CN/core/turn-completion-integrity.md +46 -13
  100. package/bundled/locales/zh-CN/core/verification-evidence.md +44 -22
  101. package/bundled/locales/zh-CN/core/virtual-organization-standards.md +30 -29
  102. package/bundled/locales/zh-CN/core/workflow-enforcement.md +9 -8
  103. package/bundled/locales/zh-CN/core/workflow-state-protocol.md +9 -8
  104. package/bundled/locales/zh-CN/docs/AVAILABLE-STANDARDS.md +70 -0
  105. package/bundled/locales/zh-CN/docs/CHEATSHEET.md +11 -2
  106. package/bundled/locales/zh-CN/docs/CLI-FLOW.md +2 -1
  107. package/bundled/locales/zh-CN/docs/CLI-INIT-OPTIONS.md +76 -40
  108. package/bundled/locales/zh-CN/docs/FEATURE-REFERENCE.md +32 -15
  109. package/bundled/locales/zh-CN/docs/STANDARDS-REFERENCE.md +2 -1
  110. package/bundled/locales/zh-CN/docs/USAGE-MODES-COMPARISON.md +139 -138
  111. package/bundled/locales/zh-CN/docs/USER-MANUAL.md +11 -3
  112. package/bundled/locales/zh-CN/docs/WINDOWS-GUIDE.md +12 -3
  113. package/bundled/locales/zh-CN/docs/specs/system/memory-adoption-strategy.md +2 -0
  114. package/bundled/locales/zh-CN/docs/user/FAQ.md +2 -0
  115. package/bundled/locales/zh-CN/docs/user/GETTING-STARTED.md +46 -0
  116. package/bundled/locales/zh-CN/docs/user/GLOSSARY.md +2 -0
  117. package/bundled/locales/zh-CN/docs/user/README.md +4 -2
  118. package/bundled/locales/zh-CN/docs/user/TROUBLESHOOTING.md +2 -0
  119. package/bundled/locales/zh-CN/integrations/codex/AGENTS.md +136 -2
  120. package/bundled/locales/zh-CN/integrations/codex/README.md +62 -10
  121. package/bundled/locales/zh-CN/integrations/gemini-cli/GEMINI.md +59 -1
  122. package/bundled/locales/zh-CN/integrations/gemini-cli/README.md +9 -2
  123. package/bundled/locales/zh-CN/integrations/github-copilot/COPILOT-CHAT-REFERENCE.md +7 -1
  124. package/bundled/locales/zh-CN/integrations/github-copilot/README.md +8 -2
  125. package/bundled/locales/zh-CN/integrations/github-copilot/copilot-instructions.md +146 -12
  126. package/bundled/locales/zh-CN/integrations/github-copilot/skills-mapping.md +7 -1
  127. package/bundled/locales/zh-CN/integrations/google-antigravity/AGENTS.md +110 -3
  128. package/bundled/locales/zh-CN/integrations/google-antigravity/README.md +7 -1
  129. package/bundled/locales/zh-CN/integrations/opencode/AGENTS.md +140 -2
  130. package/bundled/locales/zh-CN/integrations/opencode/README.md +7 -1
  131. package/bundled/locales/zh-CN/integrations/opencode/skills-mapping.md +8 -2
  132. package/bundled/locales/zh-CN/integrations/openspec/AGENTS.md +46 -1
  133. package/bundled/locales/zh-CN/integrations/openspec/README.md +7 -1
  134. package/bundled/locales/zh-CN/integrations/spec-kit/AGENTS.md +20 -2
  135. package/bundled/locales/zh-CN/integrations/spec-kit/README.md +7 -1
  136. package/bundled/locales/zh-CN/options/changelog/auto-generated.md +2 -0
  137. package/bundled/locales/zh-CN/options/changelog/keep-a-changelog.md +2 -0
  138. package/bundled/locales/zh-CN/options/code-review/automated-review.md +2 -0
  139. package/bundled/locales/zh-CN/options/code-review/pair-programming.md +2 -0
  140. package/bundled/locales/zh-CN/options/code-review/pr-review.md +13 -2
  141. package/bundled/locales/zh-CN/options/commit-message/bilingual.md +139 -50
  142. package/bundled/locales/zh-CN/options/commit-message/english.md +159 -42
  143. package/bundled/locales/zh-CN/options/commit-message/traditional-chinese.md +156 -75
  144. package/bundled/locales/zh-CN/options/documentation/api-docs.md +3 -1
  145. package/bundled/locales/zh-CN/options/documentation/markdown-docs.md +2 -0
  146. package/bundled/locales/zh-CN/options/documentation/wiki-style.md +2 -0
  147. package/bundled/locales/zh-CN/options/git-workflow/gitflow.md +105 -77
  148. package/bundled/locales/zh-CN/options/git-workflow/github-flow.md +75 -57
  149. package/bundled/locales/zh-CN/options/git-workflow/merge-commit.md +155 -44
  150. package/bundled/locales/zh-CN/options/git-workflow/rebase-ff.md +168 -53
  151. package/bundled/locales/zh-CN/options/git-workflow/squash-merge.md +122 -37
  152. package/bundled/locales/zh-CN/options/git-workflow/trunk-based.md +108 -61
  153. package/bundled/locales/zh-CN/options/project-structure/dotnet.md +266 -47
  154. package/bundled/locales/zh-CN/options/project-structure/go.md +301 -43
  155. package/bundled/locales/zh-CN/options/project-structure/java.md +268 -48
  156. package/bundled/locales/zh-CN/options/project-structure/kotlin.md +2 -0
  157. package/bundled/locales/zh-CN/options/project-structure/nodejs.md +168 -51
  158. package/bundled/locales/zh-CN/options/project-structure/php.md +2 -0
  159. package/bundled/locales/zh-CN/options/project-structure/python.md +210 -52
  160. package/bundled/locales/zh-CN/options/project-structure/ruby.md +2 -0
  161. package/bundled/locales/zh-CN/options/project-structure/rust.md +2 -0
  162. package/bundled/locales/zh-CN/options/project-structure/swift.md +2 -0
  163. package/bundled/locales/zh-CN/options/testing/contract-testing.md +2 -0
  164. package/bundled/locales/zh-CN/options/testing/e2e-testing.md +227 -66
  165. package/bundled/locales/zh-CN/options/testing/industry-pyramid.md +2 -0
  166. package/bundled/locales/zh-CN/options/testing/integration-testing.md +185 -73
  167. package/bundled/locales/zh-CN/options/testing/istqb-framework.md +2 -0
  168. package/bundled/locales/zh-CN/options/testing/performance-testing.md +2 -0
  169. package/bundled/locales/zh-CN/options/testing/security-testing.md +2 -0
  170. package/bundled/locales/zh-CN/options/testing/system-testing.md +270 -96
  171. package/bundled/locales/zh-CN/options/testing/unit-testing.md +185 -71
  172. package/bundled/locales/zh-CN/skills/CONTRIBUTING.template.md +43 -42
  173. package/bundled/locales/zh-CN/skills/INTEGRATION-GUIDE.md +2 -1
  174. package/bundled/locales/zh-CN/skills/README.md +3 -1
  175. package/bundled/locales/zh-CN/skills/_shared/README.md +2 -1
  176. package/bundled/locales/zh-CN/skills/adr-assistant/guide.md +240 -4
  177. package/bundled/locales/zh-CN/skills/agents/README.md +180 -82
  178. package/bundled/locales/zh-CN/skills/agents/code-architect.md +3 -1
  179. package/bundled/locales/zh-CN/skills/agents/doc-writer.md +3 -1
  180. package/bundled/locales/zh-CN/skills/agents/reviewer.md +4 -2
  181. package/bundled/locales/zh-CN/skills/agents/spec-analyst.md +3 -1
  182. package/bundled/locales/zh-CN/skills/agents/test-specialist.md +3 -1
  183. package/bundled/locales/zh-CN/skills/ai-collaboration-standards/SKILL.md +91 -81
  184. package/bundled/locales/zh-CN/skills/ai-collaboration-standards/anti-hallucination.md +79 -59
  185. package/bundled/locales/zh-CN/skills/ai-collaboration-standards/certainty-labels.md +66 -40
  186. package/bundled/locales/zh-CN/skills/ai-friendly-architecture/SKILL.md +23 -36
  187. package/bundled/locales/zh-CN/skills/api-design-assistant/SKILL.md +13 -2
  188. package/bundled/locales/zh-CN/skills/atdd-assistant/SKILL.md +16 -2
  189. package/bundled/locales/zh-CN/skills/atdd-assistant/acceptance-criteria-guide.md +2 -1
  190. package/bundled/locales/zh-CN/skills/atdd-assistant/atdd-workflow.md +98 -1
  191. package/bundled/locales/zh-CN/skills/audit-assistant/SKILL.md +5 -2
  192. package/bundled/locales/zh-CN/skills/bdd-assistant/SKILL.md +16 -2
  193. package/bundled/locales/zh-CN/skills/bdd-assistant/bdd-workflow.md +2 -1
  194. package/bundled/locales/zh-CN/skills/bdd-assistant/gherkin-guide.md +2 -1
  195. package/bundled/locales/zh-CN/skills/changelog-guide/SKILL.md +9 -2
  196. package/bundled/locales/zh-CN/skills/checkin-assistant/SKILL.md +12 -2
  197. package/bundled/locales/zh-CN/skills/ci-cd-assistant/SKILL.md +14 -2
  198. package/bundled/locales/zh-CN/skills/code-review-assistant/SKILL.md +12 -2
  199. package/bundled/locales/zh-CN/skills/code-review-assistant/checkin-checklist.md +79 -78
  200. package/bundled/locales/zh-CN/skills/code-review-assistant/review-checklist.md +89 -88
  201. package/bundled/locales/zh-CN/skills/commands/ac-coverage.md +43 -1
  202. package/bundled/locales/zh-CN/skills/commands/api-design.md +2 -1
  203. package/bundled/locales/zh-CN/skills/commands/atdd.md +71 -1
  204. package/bundled/locales/zh-CN/skills/commands/audit.md +2 -1
  205. package/bundled/locales/zh-CN/skills/commands/bdd.md +160 -62
  206. package/bundled/locales/zh-CN/skills/commands/changelog.md +36 -1
  207. package/bundled/locales/zh-CN/skills/commands/check.md +53 -1
  208. package/bundled/locales/zh-CN/skills/commands/checkin.md +45 -1
  209. package/bundled/locales/zh-CN/skills/commands/ci-cd.md +3 -2
  210. package/bundled/locales/zh-CN/skills/commands/code-review.md +41 -1
  211. package/bundled/locales/zh-CN/skills/commands/commit.md +56 -1
  212. package/bundled/locales/zh-CN/skills/commands/config.md +50 -1
  213. package/bundled/locales/zh-CN/skills/commands/coverage.md +43 -1
  214. package/bundled/locales/zh-CN/skills/commands/database.md +4 -3
  215. package/bundled/locales/zh-CN/skills/commands/derive-all.md +42 -1
  216. package/bundled/locales/zh-CN/skills/commands/derive-atdd.md +35 -1
  217. package/bundled/locales/zh-CN/skills/commands/derive-bdd.md +41 -1
  218. package/bundled/locales/zh-CN/skills/commands/derive-tdd.md +42 -1
  219. package/bundled/locales/zh-CN/skills/commands/derive.md +60 -4
  220. package/bundled/locales/zh-CN/skills/commands/dev-workflow.md +58 -8
  221. package/bundled/locales/zh-CN/skills/commands/discover.md +41 -1
  222. package/bundled/locales/zh-CN/skills/commands/docgen.md +37 -1
  223. package/bundled/locales/zh-CN/skills/commands/docs.md +136 -5
  224. package/bundled/locales/zh-CN/skills/commands/durable.md +4 -3
  225. package/bundled/locales/zh-CN/skills/commands/e2e.md +85 -1
  226. package/bundled/locales/zh-CN/skills/commands/guide.md +2 -1
  227. package/bundled/locales/zh-CN/skills/commands/incident.md +5 -4
  228. package/bundled/locales/zh-CN/skills/commands/init.md +57 -1
  229. package/bundled/locales/zh-CN/skills/commands/methodology.md +166 -77
  230. package/bundled/locales/zh-CN/skills/commands/metrics.md +3 -2
  231. package/bundled/locales/zh-CN/skills/commands/migrate.md +5 -4
  232. package/bundled/locales/zh-CN/skills/commands/observability.md +48 -3
  233. package/bundled/locales/zh-CN/skills/commands/pr.md +4 -3
  234. package/bundled/locales/zh-CN/skills/commands/refactor.md +76 -38
  235. package/bundled/locales/zh-CN/skills/commands/release.md +82 -1
  236. package/bundled/locales/zh-CN/skills/commands/requirement.md +40 -1
  237. package/bundled/locales/zh-CN/skills/commands/reverse-bdd.md +36 -1
  238. package/bundled/locales/zh-CN/skills/commands/reverse-sdd.md +44 -1
  239. package/bundled/locales/zh-CN/skills/commands/reverse-tdd.md +42 -1
  240. package/bundled/locales/zh-CN/skills/commands/reverse.md +43 -1
  241. package/bundled/locales/zh-CN/skills/commands/runbook.md +50 -3
  242. package/bundled/locales/zh-CN/skills/commands/scan.md +3 -2
  243. package/bundled/locales/zh-CN/skills/commands/sdd-retro.md +50 -1
  244. package/bundled/locales/zh-CN/skills/commands/sdd.md +182 -1
  245. package/bundled/locales/zh-CN/skills/commands/security.md +3 -2
  246. package/bundled/locales/zh-CN/skills/commands/slo.md +51 -3
  247. package/bundled/locales/zh-CN/skills/commands/tdd.md +74 -5
  248. package/bundled/locales/zh-CN/skills/commands/update.md +70 -8
  249. package/bundled/locales/zh-CN/skills/commit-standards/SKILL.md +2 -2
  250. package/bundled/locales/zh-CN/skills/commit-standards/conventional-commits.md +45 -44
  251. package/bundled/locales/zh-CN/skills/commit-standards/language-options.md +50 -47
  252. package/bundled/locales/zh-CN/skills/comprehension-ladder/SKILL.md +289 -0
  253. package/bundled/locales/zh-CN/skills/comprehension-ladder/eval-cases.md +261 -0
  254. package/bundled/locales/zh-CN/skills/contract-test-assistant/guide.md +76 -1
  255. package/bundled/locales/zh-CN/skills/database-assistant/SKILL.md +18 -5
  256. package/bundled/locales/zh-CN/skills/dev-methodology/create-methodology.md +2 -0
  257. package/bundled/locales/zh-CN/skills/dev-methodology/runtime.md +2 -0
  258. package/bundled/locales/zh-CN/skills/docs-generator/SKILL.md +16 -2
  259. package/bundled/locales/zh-CN/skills/documentation-guide/SKILL.md +209 -184
  260. package/bundled/locales/zh-CN/skills/documentation-guide/documentation-structure.md +73 -72
  261. package/bundled/locales/zh-CN/skills/documentation-guide/readme-template.md +37 -36
  262. package/bundled/locales/zh-CN/skills/durable-execution-assistant/SKILL.md +28 -2
  263. package/bundled/locales/zh-CN/skills/e2e-assistant/SKILL.md +21 -6
  264. package/bundled/locales/zh-CN/skills/error-code-guide/SKILL.md +76 -95
  265. package/bundled/locales/zh-CN/skills/git-workflow-guide/SKILL.md +80 -87
  266. package/bundled/locales/zh-CN/skills/git-workflow-guide/branch-naming.md +44 -43
  267. package/bundled/locales/zh-CN/skills/git-workflow-guide/git-workflow.md +66 -65
  268. package/bundled/locales/zh-CN/skills/incident-response-assistant/SKILL.md +31 -13
  269. package/bundled/locales/zh-CN/skills/metrics-dashboard-assistant/SKILL.md +38 -2
  270. package/bundled/locales/zh-CN/skills/observability-assistant/SKILL.md +75 -1
  271. package/bundled/locales/zh-CN/skills/pr-automation-assistant/SKILL.md +32 -6
  272. package/bundled/locales/zh-CN/skills/project-discovery/SKILL.md +8 -2
  273. package/bundled/locales/zh-CN/skills/project-structure-guide/SKILL.md +49 -46
  274. package/bundled/locales/zh-CN/skills/project-structure-guide/language-patterns.md +8 -7
  275. package/bundled/locales/zh-CN/skills/refactoring-assistant/SKILL.md +22 -2
  276. package/bundled/locales/zh-CN/skills/release-standards/SKILL.md +66 -23
  277. package/bundled/locales/zh-CN/skills/release-standards/changelog-format.md +42 -41
  278. package/bundled/locales/zh-CN/skills/release-standards/release-workflow.md +131 -95
  279. package/bundled/locales/zh-CN/skills/release-standards/semantic-versioning.md +62 -61
  280. package/bundled/locales/zh-CN/skills/requirement-assistant/SKILL.md +24 -15
  281. package/bundled/locales/zh-CN/skills/requirement-assistant/requirement-checklist.md +128 -127
  282. package/bundled/locales/zh-CN/skills/requirement-assistant/requirement-writing.md +121 -120
  283. package/bundled/locales/zh-CN/skills/retrospective-assistant/guide.md +206 -2
  284. package/bundled/locales/zh-CN/skills/reverse-engineer/bdd-extraction.md +2 -1
  285. package/bundled/locales/zh-CN/skills/reverse-engineer/tdd-analysis.md +2 -1
  286. package/bundled/locales/zh-CN/skills/reverse-engineer/workflow.md +2 -1
  287. package/bundled/locales/zh-CN/skills/runbook-assistant/SKILL.md +9 -2
  288. package/bundled/locales/zh-CN/skills/security-assistant/SKILL.md +24 -6
  289. package/bundled/locales/zh-CN/skills/security-scan-assistant/SKILL.md +34 -10
  290. package/bundled/locales/zh-CN/skills/slo-assistant/SKILL.md +2 -1
  291. package/bundled/locales/zh-CN/skills/spec-driven-dev/guide.md +38 -6
  292. package/bundled/locales/zh-CN/skills/tdd-assistant/SKILL.md +16 -3
  293. package/bundled/locales/zh-CN/skills/tdd-assistant/language-examples.md +727 -82
  294. package/bundled/locales/zh-CN/skills/tdd-assistant/tdd-workflow.md +396 -214
  295. package/bundled/locales/zh-CN/skills/test-coverage-assistant/SKILL.md +14 -5
  296. package/bundled/locales/zh-CN/skills/testing-guide/testing-pyramid.md +99 -98
  297. package/bundled/locales/zh-CN/skills/testing-guide/testing-theory.md +3 -1
  298. package/bundled/locales/zh-CN/skills/tools/cline/README.md +2 -1
  299. package/bundled/locales/zh-CN/skills/tools/copilot/README.md +65 -18
  300. package/bundled/locales/zh-CN/skills/tools/copilot/copilot-instructions.md +2 -1
  301. package/bundled/locales/zh-CN/skills/tools/cursor/README.md +2 -1
  302. package/bundled/locales/zh-CN/skills/tools/windsurf/README.md +2 -1
  303. package/bundled/locales/zh-CN/skills/workflows/README.md +4 -2
  304. package/bundled/locales/zh-CN/templates/reverse-spec-template.md +50 -1
  305. package/bundled/locales/zh-TW/CHANGELOG.md +211 -3
  306. package/bundled/locales/zh-TW/README.md +3 -3
  307. package/bundled/locales/zh-TW/SECURITY.md +3 -1
  308. package/bundled/locales/zh-TW/STANDARDS-MAPPING.md +103 -6
  309. package/bundled/locales/zh-TW/adoption/ADOPTION-GUIDE.md +59 -97
  310. package/bundled/locales/zh-TW/adoption/DAILY-WORKFLOW-GUIDE.md +2 -1
  311. package/bundled/locales/zh-TW/adoption/STATIC-DYNAMIC-GUIDE.md +10 -2
  312. package/bundled/locales/zh-TW/adoption/checklists/enterprise.md +17 -10
  313. package/bundled/locales/zh-TW/adoption/checklists/minimal.md +19 -5
  314. package/bundled/locales/zh-TW/adoption/checklists/recommended.md +14 -5
  315. package/bundled/locales/zh-TW/ai/MAINTENANCE.md +34 -14
  316. package/bundled/locales/zh-TW/ai/options/commit-message/traditional-chinese.ai.yaml +48 -40
  317. package/bundled/locales/zh-TW/core/acceptance-criteria-traceability.md +56 -10
  318. package/bundled/locales/zh-TW/core/acceptance-test-driven-development.md +2 -1
  319. package/bundled/locales/zh-TW/core/adr-standards.md +2 -1
  320. package/bundled/locales/zh-TW/core/agent-communication-protocol.md +2 -1
  321. package/bundled/locales/zh-TW/core/ai-command-behavior.md +2 -1
  322. package/bundled/locales/zh-TW/core/ai-instruction-standards.md +16 -13
  323. package/bundled/locales/zh-TW/core/ai-response-navigation.md +111 -13
  324. package/bundled/locales/zh-TW/core/anti-sycophancy-prompting.md +2 -1
  325. package/bundled/locales/zh-TW/core/api-design-standards.md +2 -1
  326. package/bundled/locales/zh-TW/core/behavior-driven-development.md +3 -17
  327. package/bundled/locales/zh-TW/core/capability-declaration.md +41 -79
  328. package/bundled/locales/zh-TW/core/change-batching-standards.md +2 -1
  329. package/bundled/locales/zh-TW/core/changelog-standards.md +14 -9
  330. package/bundled/locales/zh-TW/core/checkin-standards.md +84 -26
  331. package/bundled/locales/zh-TW/core/circuit-breaker.md +48 -87
  332. package/bundled/locales/zh-TW/core/code-review-checklist.md +36 -7
  333. package/bundled/locales/zh-TW/core/commit-message-guide.md +218 -87
  334. package/bundled/locales/zh-TW/core/database-standards.md +2 -1
  335. package/bundled/locales/zh-TW/core/developer-memory.md +111 -12
  336. package/bundled/locales/zh-TW/core/documentation-lifecycle.md +2 -1
  337. package/bundled/locales/zh-TW/core/documentation-structure.md +17 -8
  338. package/bundled/locales/zh-TW/core/dual-phase-output.md +28 -90
  339. package/bundled/locales/zh-TW/core/error-code-standards.md +17 -6
  340. package/bundled/locales/zh-TW/core/execution-history.md +2 -1
  341. package/bundled/locales/zh-TW/core/failure-source-taxonomy.md +59 -117
  342. package/bundled/locales/zh-TW/core/frontend-design-standards.md +120 -8
  343. package/bundled/locales/zh-TW/core/full-coverage-testing.md +103 -9
  344. package/bundled/locales/zh-TW/core/git-workflow.md +197 -37
  345. package/bundled/locales/zh-TW/core/git-worktree.md +79 -49
  346. package/bundled/locales/zh-TW/core/guides/file-placement-guide.md +86 -2
  347. package/bundled/locales/zh-TW/core/guides/performance-guide.md +2 -0
  348. package/bundled/locales/zh-TW/core/guides/security-guide.md +2 -0
  349. package/bundled/locales/zh-TW/core/health-check-standards.md +46 -104
  350. package/bundled/locales/zh-TW/core/immutability-first.md +45 -85
  351. package/bundled/locales/zh-TW/core/knowledge-graph-memory.md +2 -1
  352. package/bundled/locales/zh-TW/core/knowledge-transfer-standards.md +103 -40
  353. package/bundled/locales/zh-TW/core/open-work-tracking.md +164 -9
  354. package/bundled/locales/zh-TW/core/pipeline-integration-standards.md +2 -1
  355. package/bundled/locales/zh-TW/core/pipeline-security-gates.md +64 -4
  356. package/bundled/locales/zh-TW/core/privacy-standards.md +153 -46
  357. package/bundled/locales/zh-TW/core/project-context-memory.md +215 -31
  358. package/bundled/locales/zh-TW/core/project-structure.md +240 -19
  359. package/bundled/locales/zh-TW/core/recovery-recipe-registry.md +54 -114
  360. package/bundled/locales/zh-TW/core/refactoring-standards.md +153 -48
  361. package/bundled/locales/zh-TW/core/requirement-engineering.md +8 -37
  362. package/bundled/locales/zh-TW/core/retrospective-standards.md +127 -7
  363. package/bundled/locales/zh-TW/core/retry-standards.md +41 -105
  364. package/bundled/locales/zh-TW/core/reverse-engineering-standards.md +5 -1
  365. package/bundled/locales/zh-TW/core/security-decision.md +43 -84
  366. package/bundled/locales/zh-TW/core/security-standards.md +204 -25
  367. package/bundled/locales/zh-TW/core/self-review-protocol.md +2 -1
  368. package/bundled/locales/zh-TW/core/skill-standard-alignment-check.md +103 -69
  369. package/bundled/locales/zh-TW/core/standard-admission-criteria.md +22 -28
  370. package/bundled/locales/zh-TW/core/standard-lifecycle-management.md +40 -48
  371. package/bundled/locales/zh-TW/core/structured-task-definition.md +2 -1
  372. package/bundled/locales/zh-TW/core/supply-chain-security-standards.md +137 -10
  373. package/bundled/locales/zh-TW/core/systematic-debugging.md +94 -38
  374. package/bundled/locales/zh-TW/core/tech-debt-standards.md +170 -54
  375. package/bundled/locales/zh-TW/core/test-completeness-dimensions.md +101 -12
  376. package/bundled/locales/zh-TW/core/test-data-standards.md +245 -23
  377. package/bundled/locales/zh-TW/core/test-driven-development.md +4 -1
  378. package/bundled/locales/zh-TW/core/test-governance.md +92 -32
  379. package/bundled/locales/zh-TW/core/testing-standards.md +61 -14
  380. package/bundled/locales/zh-TW/core/timeout-standards.md +45 -85
  381. package/bundled/locales/zh-TW/core/token-budget.md +41 -112
  382. package/bundled/locales/zh-TW/core/translation-lifecycle-standards.md +28 -16
  383. package/bundled/locales/zh-TW/core/turn-completion-integrity.md +46 -13
  384. package/bundled/locales/zh-TW/core/verification-evidence.md +2 -1
  385. package/bundled/locales/zh-TW/core/versioning.md +6 -2
  386. package/bundled/locales/zh-TW/core/virtual-organization-standards.md +42 -36
  387. package/bundled/locales/zh-TW/core/workflow-enforcement.md +2 -1
  388. package/bundled/locales/zh-TW/core/workflow-state-protocol.md +2 -1
  389. package/bundled/locales/zh-TW/docs/AVAILABLE-STANDARDS.md +70 -0
  390. package/bundled/locales/zh-TW/docs/CHEATSHEET.md +11 -2
  391. package/bundled/locales/zh-TW/docs/CLI-FLOW.md +2 -1
  392. package/bundled/locales/zh-TW/docs/CLI-INIT-OPTIONS.md +69 -33
  393. package/bundled/locales/zh-TW/docs/DEV-WORKFLOW-MAPPING.md +2 -1
  394. package/bundled/locales/zh-TW/docs/FEATURE-REFERENCE.md +32 -15
  395. package/bundled/locales/zh-TW/docs/STANDARDS-REFERENCE.md +2 -1
  396. package/bundled/locales/zh-TW/docs/USAGE-MODES-COMPARISON.md +8 -7
  397. package/bundled/locales/zh-TW/docs/USER-MANUAL.md +9 -1
  398. package/bundled/locales/zh-TW/docs/WINDOWS-GUIDE.md +11 -2
  399. package/bundled/locales/zh-TW/docs/specs/system/memory-adoption-strategy.md +2 -0
  400. package/bundled/locales/zh-TW/docs/user/FAQ.md +2 -0
  401. package/bundled/locales/zh-TW/docs/user/GETTING-STARTED.md +46 -0
  402. package/bundled/locales/zh-TW/docs/user/GLOSSARY.md +2 -0
  403. package/bundled/locales/zh-TW/docs/user/README.md +2 -0
  404. package/bundled/locales/zh-TW/docs/user/TROUBLESHOOTING.md +2 -0
  405. package/bundled/locales/zh-TW/integrations/claude-code/README.md +2 -1
  406. package/bundled/locales/zh-TW/integrations/codex/AGENTS.md +136 -2
  407. package/bundled/locales/zh-TW/integrations/codex/README.md +7 -1
  408. package/bundled/locales/zh-TW/integrations/gemini-cli/GEMINI.md +59 -1
  409. package/bundled/locales/zh-TW/integrations/gemini-cli/README.md +8 -1
  410. package/bundled/locales/zh-TW/integrations/github-copilot/COPILOT-CHAT-REFERENCE.md +7 -1
  411. package/bundled/locales/zh-TW/integrations/github-copilot/README.md +9 -3
  412. package/bundled/locales/zh-TW/integrations/github-copilot/copilot-instructions.md +146 -12
  413. package/bundled/locales/zh-TW/integrations/github-copilot/skills-mapping.md +7 -1
  414. package/bundled/locales/zh-TW/integrations/google-antigravity/AGENTS.md +110 -3
  415. package/bundled/locales/zh-TW/integrations/google-antigravity/README.md +7 -1
  416. package/bundled/locales/zh-TW/integrations/opencode/AGENTS.md +140 -2
  417. package/bundled/locales/zh-TW/integrations/opencode/README.md +7 -1
  418. package/bundled/locales/zh-TW/integrations/opencode/skills-mapping.md +8 -2
  419. package/bundled/locales/zh-TW/integrations/openspec/AGENTS.md +46 -1
  420. package/bundled/locales/zh-TW/integrations/openspec/README.md +7 -1
  421. package/bundled/locales/zh-TW/integrations/spec-kit/AGENTS.md +20 -2
  422. package/bundled/locales/zh-TW/integrations/spec-kit/README.md +7 -1
  423. package/bundled/locales/zh-TW/options/changelog/auto-generated.md +2 -0
  424. package/bundled/locales/zh-TW/options/changelog/keep-a-changelog.md +2 -0
  425. package/bundled/locales/zh-TW/options/code-review/automated-review.md +2 -0
  426. package/bundled/locales/zh-TW/options/code-review/pair-programming.md +2 -0
  427. package/bundled/locales/zh-TW/options/code-review/pr-review.md +13 -2
  428. package/bundled/locales/zh-TW/options/commit-message/bilingual.md +93 -5
  429. package/bundled/locales/zh-TW/options/commit-message/english.md +118 -1
  430. package/bundled/locales/zh-TW/options/commit-message/traditional-chinese.md +82 -1
  431. package/bundled/locales/zh-TW/options/documentation/api-docs.md +2 -0
  432. package/bundled/locales/zh-TW/options/documentation/markdown-docs.md +2 -0
  433. package/bundled/locales/zh-TW/options/documentation/wiki-style.md +2 -0
  434. package/bundled/locales/zh-TW/options/git-workflow/gitflow.md +99 -71
  435. package/bundled/locales/zh-TW/options/git-workflow/github-flow.md +68 -50
  436. package/bundled/locales/zh-TW/options/git-workflow/merge-commit.md +131 -20
  437. package/bundled/locales/zh-TW/options/git-workflow/rebase-ff.md +142 -27
  438. package/bundled/locales/zh-TW/options/git-workflow/squash-merge.md +100 -15
  439. package/bundled/locales/zh-TW/options/git-workflow/trunk-based.md +103 -56
  440. package/bundled/locales/zh-TW/options/project-structure/dotnet.md +233 -14
  441. package/bundled/locales/zh-TW/options/project-structure/go.md +270 -12
  442. package/bundled/locales/zh-TW/options/project-structure/java.md +235 -15
  443. package/bundled/locales/zh-TW/options/project-structure/kotlin.md +2 -0
  444. package/bundled/locales/zh-TW/options/project-structure/nodejs.md +136 -19
  445. package/bundled/locales/zh-TW/options/project-structure/php.md +2 -0
  446. package/bundled/locales/zh-TW/options/project-structure/python.md +177 -19
  447. package/bundled/locales/zh-TW/options/project-structure/ruby.md +2 -0
  448. package/bundled/locales/zh-TW/options/project-structure/rust.md +2 -0
  449. package/bundled/locales/zh-TW/options/project-structure/swift.md +2 -0
  450. package/bundled/locales/zh-TW/options/testing/contract-testing.md +2 -0
  451. package/bundled/locales/zh-TW/options/testing/e2e-testing.md +182 -21
  452. package/bundled/locales/zh-TW/options/testing/industry-pyramid.md +2 -0
  453. package/bundled/locales/zh-TW/options/testing/integration-testing.md +134 -22
  454. package/bundled/locales/zh-TW/options/testing/istqb-framework.md +2 -0
  455. package/bundled/locales/zh-TW/options/testing/performance-testing.md +2 -0
  456. package/bundled/locales/zh-TW/options/testing/security-testing.md +2 -0
  457. package/bundled/locales/zh-TW/options/testing/system-testing.md +175 -1
  458. package/bundled/locales/zh-TW/options/testing/unit-testing.md +123 -9
  459. package/bundled/locales/zh-TW/skills/CONTRIBUTING.template.md +3 -2
  460. package/bundled/locales/zh-TW/skills/INTEGRATION-GUIDE.md +2 -1
  461. package/bundled/locales/zh-TW/skills/README.md +3 -1
  462. package/bundled/locales/zh-TW/skills/_shared/README.md +2 -1
  463. package/bundled/locales/zh-TW/skills/ac-coverage/SKILL.md +15 -4
  464. package/bundled/locales/zh-TW/skills/adr-assistant/guide.md +123 -3
  465. package/bundled/locales/zh-TW/skills/agents/README.md +99 -1
  466. package/bundled/locales/zh-TW/skills/agents/code-architect.md +2 -0
  467. package/bundled/locales/zh-TW/skills/agents/doc-writer.md +2 -0
  468. package/bundled/locales/zh-TW/skills/agents/reviewer.md +3 -1
  469. package/bundled/locales/zh-TW/skills/agents/spec-analyst.md +2 -0
  470. package/bundled/locales/zh-TW/skills/agents/test-specialist.md +2 -0
  471. package/bundled/locales/zh-TW/skills/ai-collaboration-standards/SKILL.md +48 -37
  472. package/bundled/locales/zh-TW/skills/ai-collaboration-standards/anti-hallucination.md +22 -2
  473. package/bundled/locales/zh-TW/skills/ai-collaboration-standards/certainty-labels.md +29 -3
  474. package/bundled/locales/zh-TW/skills/ai-friendly-architecture/SKILL.md +23 -36
  475. package/bundled/locales/zh-TW/skills/ai-instruction-standards/SKILL.md +12 -36
  476. package/bundled/locales/zh-TW/skills/api-design-assistant/SKILL.md +21 -5
  477. package/bundled/locales/zh-TW/skills/atdd-assistant/SKILL.md +40 -15
  478. package/bundled/locales/zh-TW/skills/atdd-assistant/acceptance-criteria-guide.md +2 -1
  479. package/bundled/locales/zh-TW/skills/atdd-assistant/atdd-workflow.md +98 -1
  480. package/bundled/locales/zh-TW/skills/atdd-assistant/guide.md +24 -8
  481. package/bundled/locales/zh-TW/skills/audit-assistant/SKILL.md +8 -2
  482. package/bundled/locales/zh-TW/skills/bdd-assistant/SKILL.md +29 -6
  483. package/bundled/locales/zh-TW/skills/bdd-assistant/bdd-workflow.md +2 -1
  484. package/bundled/locales/zh-TW/skills/bdd-assistant/gherkin-guide.md +2 -1
  485. package/bundled/locales/zh-TW/skills/bdd-assistant/guide.md +9 -8
  486. package/bundled/locales/zh-TW/skills/changelog-guide/SKILL.md +12 -3
  487. package/bundled/locales/zh-TW/skills/changelog-guide/guide.md +11 -7
  488. package/bundled/locales/zh-TW/skills/checkin-assistant/SKILL.md +19 -3
  489. package/bundled/locales/zh-TW/skills/checkin-assistant/guide.md +5 -3
  490. package/bundled/locales/zh-TW/skills/ci-cd-assistant/SKILL.md +35 -16
  491. package/bundled/locales/zh-TW/skills/code-review-assistant/SKILL.md +19 -2
  492. package/bundled/locales/zh-TW/skills/code-review-assistant/checkin-checklist.md +2 -1
  493. package/bundled/locales/zh-TW/skills/code-review-assistant/guide.md +81 -6
  494. package/bundled/locales/zh-TW/skills/code-review-assistant/review-checklist.md +2 -1
  495. package/bundled/locales/zh-TW/skills/commands/ac-coverage.md +47 -2
  496. package/bundled/locales/zh-TW/skills/commands/api-design.md +3 -2
  497. package/bundled/locales/zh-TW/skills/commands/atdd.md +80 -10
  498. package/bundled/locales/zh-TW/skills/commands/audit.md +3 -2
  499. package/bundled/locales/zh-TW/skills/commands/bdd.md +114 -16
  500. package/bundled/locales/zh-TW/skills/commands/changelog.md +45 -9
  501. package/bundled/locales/zh-TW/skills/commands/check.md +74 -21
  502. package/bundled/locales/zh-TW/skills/commands/checkin.md +56 -11
  503. package/bundled/locales/zh-TW/skills/commands/ci-cd.md +2 -1
  504. package/bundled/locales/zh-TW/skills/commands/code-review.md +43 -2
  505. package/bundled/locales/zh-TW/skills/commands/commit.md +58 -4
  506. package/bundled/locales/zh-TW/skills/commands/config.md +52 -4
  507. package/bundled/locales/zh-TW/skills/commands/coverage.md +45 -4
  508. package/bundled/locales/zh-TW/skills/commands/database.md +3 -2
  509. package/bundled/locales/zh-TW/skills/commands/derive-all.md +44 -2
  510. package/bundled/locales/zh-TW/skills/commands/derive-atdd.md +37 -2
  511. package/bundled/locales/zh-TW/skills/commands/derive-bdd.md +44 -3
  512. package/bundled/locales/zh-TW/skills/commands/derive-tdd.md +45 -3
  513. package/bundled/locales/zh-TW/skills/commands/derive.md +62 -5
  514. package/bundled/locales/zh-TW/skills/commands/dev-workflow.md +60 -9
  515. package/bundled/locales/zh-TW/skills/commands/discover.md +43 -2
  516. package/bundled/locales/zh-TW/skills/commands/docgen.md +39 -2
  517. package/bundled/locales/zh-TW/skills/commands/docs.md +139 -7
  518. package/bundled/locales/zh-TW/skills/commands/durable.md +3 -2
  519. package/bundled/locales/zh-TW/skills/commands/e2e.md +86 -3
  520. package/bundled/locales/zh-TW/skills/commands/guide.md +4 -2
  521. package/bundled/locales/zh-TW/skills/commands/incident.md +3 -2
  522. package/bundled/locales/zh-TW/skills/commands/init.md +72 -15
  523. package/bundled/locales/zh-TW/skills/commands/methodology.md +117 -28
  524. package/bundled/locales/zh-TW/skills/commands/metrics.md +2 -1
  525. package/bundled/locales/zh-TW/skills/commands/migrate.md +2 -1
  526. package/bundled/locales/zh-TW/skills/commands/observability.md +45 -2
  527. package/bundled/locales/zh-TW/skills/commands/pr.md +2 -1
  528. package/bundled/locales/zh-TW/skills/commands/refactor.md +54 -13
  529. package/bundled/locales/zh-TW/skills/commands/release.md +83 -2
  530. package/bundled/locales/zh-TW/skills/commands/requirement.md +41 -2
  531. package/bundled/locales/zh-TW/skills/commands/reverse-bdd.md +37 -2
  532. package/bundled/locales/zh-TW/skills/commands/reverse-sdd.md +45 -2
  533. package/bundled/locales/zh-TW/skills/commands/reverse-tdd.md +43 -2
  534. package/bundled/locales/zh-TW/skills/commands/reverse.md +44 -2
  535. package/bundled/locales/zh-TW/skills/commands/runbook.md +47 -2
  536. package/bundled/locales/zh-TW/skills/commands/scan.md +3 -2
  537. package/bundled/locales/zh-TW/skills/commands/sdd-retro.md +52 -3
  538. package/bundled/locales/zh-TW/skills/commands/sdd.md +209 -28
  539. package/bundled/locales/zh-TW/skills/commands/security.md +3 -2
  540. package/bundled/locales/zh-TW/skills/commands/slo.md +48 -2
  541. package/bundled/locales/zh-TW/skills/commands/tdd.md +71 -2
  542. package/bundled/locales/zh-TW/skills/commands/update.md +64 -2
  543. package/bundled/locales/zh-TW/skills/commit-standards/SKILL.md +2 -2
  544. package/bundled/locales/zh-TW/skills/commit-standards/conventional-commits.md +2 -1
  545. package/bundled/locales/zh-TW/skills/commit-standards/language-options.md +21 -18
  546. package/bundled/locales/zh-TW/skills/comprehension-ladder/SKILL.md +289 -0
  547. package/bundled/locales/zh-TW/skills/comprehension-ladder/eval-cases.md +261 -0
  548. package/bundled/locales/zh-TW/skills/contract-test-assistant/guide.md +81 -1
  549. package/bundled/locales/zh-TW/skills/database-assistant/SKILL.md +21 -5
  550. package/bundled/locales/zh-TW/skills/deploy-assistant/SKILL.md +2 -1
  551. package/bundled/locales/zh-TW/skills/dev-methodology/SKILL.md +4 -1
  552. package/bundled/locales/zh-TW/skills/dev-methodology/create-methodology.md +2 -0
  553. package/bundled/locales/zh-TW/skills/dev-methodology/runtime.md +2 -0
  554. package/bundled/locales/zh-TW/skills/docs-generator/SKILL.md +19 -2
  555. package/bundled/locales/zh-TW/skills/documentation-guide/SKILL.md +67 -42
  556. package/bundled/locales/zh-TW/skills/documentation-guide/documentation-structure.md +2 -1
  557. package/bundled/locales/zh-TW/skills/documentation-guide/readme-template.md +2 -1
  558. package/bundled/locales/zh-TW/skills/durable-execution-assistant/SKILL.md +32 -3
  559. package/bundled/locales/zh-TW/skills/e2e-assistant/SKILL.md +25 -7
  560. package/bundled/locales/zh-TW/skills/error-code-guide/SKILL.md +17 -34
  561. package/bundled/locales/zh-TW/skills/git-workflow-guide/SKILL.md +33 -38
  562. package/bundled/locales/zh-TW/skills/git-workflow-guide/branch-naming.md +2 -1
  563. package/bundled/locales/zh-TW/skills/git-workflow-guide/git-workflow.md +2 -1
  564. package/bundled/locales/zh-TW/skills/incident-response-assistant/SKILL.md +35 -14
  565. package/bundled/locales/zh-TW/skills/journey-test-assistant/SKILL.md +2 -14
  566. package/bundled/locales/zh-TW/skills/knowledge-graph/SKILL.md +6 -2
  567. package/bundled/locales/zh-TW/skills/metrics-dashboard-assistant/SKILL.md +42 -3
  568. package/bundled/locales/zh-TW/skills/pr-automation-assistant/SKILL.md +27 -3
  569. package/bundled/locales/zh-TW/skills/project-discovery/SKILL.md +11 -3
  570. package/bundled/locales/zh-TW/skills/project-discovery/guide.md +5 -3
  571. package/bundled/locales/zh-TW/skills/project-discovery/workflow.md +2 -1
  572. package/bundled/locales/zh-TW/skills/project-structure-guide/SKILL.md +19 -16
  573. package/bundled/locales/zh-TW/skills/project-structure-guide/language-patterns.md +2 -1
  574. package/bundled/locales/zh-TW/skills/refactoring-assistant/SKILL.md +26 -3
  575. package/bundled/locales/zh-TW/skills/refactoring-assistant/guide.md +4 -2
  576. package/bundled/locales/zh-TW/skills/release-standards/changelog-format.md +4 -3
  577. package/bundled/locales/zh-TW/skills/release-standards/guide.md +14 -5
  578. package/bundled/locales/zh-TW/skills/release-standards/release-workflow.md +5 -1
  579. package/bundled/locales/zh-TW/skills/release-standards/semantic-versioning.md +2 -1
  580. package/bundled/locales/zh-TW/skills/requirement-assistant/SKILL.md +15 -6
  581. package/bundled/locales/zh-TW/skills/requirement-assistant/guide.md +18 -8
  582. package/bundled/locales/zh-TW/skills/requirement-assistant/requirement-checklist.md +2 -1
  583. package/bundled/locales/zh-TW/skills/requirement-assistant/requirement-writing.md +2 -1
  584. package/bundled/locales/zh-TW/skills/retrospective-assistant/guide.md +200 -6
  585. package/bundled/locales/zh-TW/skills/reverse-engineer/bdd-extraction.md +2 -1
  586. package/bundled/locales/zh-TW/skills/reverse-engineer/guide.md +161 -36
  587. package/bundled/locales/zh-TW/skills/reverse-engineer/tdd-analysis.md +2 -1
  588. package/bundled/locales/zh-TW/skills/reverse-engineer/workflow.md +2 -1
  589. package/bundled/locales/zh-TW/skills/runbook-assistant/SKILL.md +9 -1
  590. package/bundled/locales/zh-TW/skills/security-assistant/SKILL.md +25 -5
  591. package/bundled/locales/zh-TW/skills/security-scan-assistant/SKILL.md +34 -8
  592. package/bundled/locales/zh-TW/skills/skill-builder/SKILL.md +3 -21
  593. package/bundled/locales/zh-TW/skills/slo-assistant/SKILL.md +3 -1
  594. package/bundled/locales/zh-TW/skills/spec-derivation/SKILL.md +2 -1
  595. package/bundled/locales/zh-TW/skills/spec-driven-dev/guide.md +35 -2
  596. package/bundled/locales/zh-TW/skills/sweep/SKILL.md +2 -1
  597. package/bundled/locales/zh-TW/skills/tdd-assistant/SKILL.md +10 -2
  598. package/bundled/locales/zh-TW/skills/tdd-assistant/guide.md +68 -9
  599. package/bundled/locales/zh-TW/skills/tdd-assistant/tdd-workflow.md +183 -1
  600. package/bundled/locales/zh-TW/skills/test-coverage-assistant/SKILL.md +15 -5
  601. package/bundled/locales/zh-TW/skills/test-coverage-assistant/guide.md +26 -13
  602. package/bundled/locales/zh-TW/skills/testing-guide/testing-pyramid.md +2 -1
  603. package/bundled/locales/zh-TW/skills/testing-guide/testing-theory.md +3 -1
  604. package/bundled/locales/zh-TW/skills/tools/cline/README.md +2 -1
  605. package/bundled/locales/zh-TW/skills/tools/copilot/README.md +65 -18
  606. package/bundled/locales/zh-TW/skills/tools/copilot/copilot-instructions.md +2 -1
  607. package/bundled/locales/zh-TW/skills/tools/cursor/README.md +2 -1
  608. package/bundled/locales/zh-TW/skills/tools/windsurf/README.md +2 -1
  609. package/bundled/locales/zh-TW/skills/workflows/README.md +11 -9
  610. package/bundled/locales/zh-TW/templates/reverse-spec-template.md +50 -1
  611. package/bundled/skills/README.md +1 -0
  612. package/bundled/skills/SKILL_NAMING.md +9 -0
  613. package/bundled/skills/commit-standards/SKILL.md +2 -2
  614. package/bundled/skills/commit-standards/guide.md +3 -2
  615. package/bundled/skills/commit-standards/language-options.md +19 -17
  616. package/bundled/skills/comprehension-ladder/SKILL.md +283 -0
  617. package/bundled/skills/comprehension-ladder/eval-cases.md +255 -0
  618. package/bundled/templates/gates/check-anti-fake-tests.mjs +1291 -0
  619. package/bundled/templates/gates/check-stubs.mjs +644 -0
  620. package/package.json +5 -3
  621. package/src/commands/audit.js +20 -2
  622. package/src/commands/check.js +155 -28
  623. package/src/commands/deps.js +31 -1
  624. package/src/commands/hitl.js +3 -0
  625. package/src/commands/init.js +173 -49
  626. package/src/commands/list.js +12 -3
  627. package/src/commands/mcp.js +2 -3
  628. package/src/commands/open-work.js +123 -0
  629. package/src/commands/quickstart.js +29 -13
  630. package/src/commands/release.js +102 -19
  631. package/src/commands/run-intent.js +10 -0
  632. package/src/commands/simulate.js +20 -8
  633. package/src/commands/skills.js +59 -33
  634. package/src/commands/spec-split.js +30 -17
  635. package/src/commands/spec.js +55 -21
  636. package/src/commands/uninstall.js +146 -32
  637. package/src/commands/update.js +471 -93
  638. package/src/core/install-records.js +192 -0
  639. package/src/core/manifest.js +12 -10
  640. package/src/core/marketplace-sentinel.js +5 -0
  641. package/src/core/open-work-config.js +122 -0
  642. package/src/core/project-config.js +92 -38
  643. package/src/flows/init-flow.js +10 -0
  644. package/src/hitl/manager.js +4 -2
  645. package/src/i18n/messages.js +413 -78
  646. package/src/installers/hooks-installer.js +320 -24
  647. package/src/installers/integration-installer.js +5 -1
  648. package/src/installers/skills-installer.js +3 -1
  649. package/src/installers/standards-installer.js +16 -23
  650. package/src/mcp/__tests__/server.test.js +0 -1
  651. package/src/mcp/server.js +16 -4
  652. package/src/prompts/init.js +148 -13
  653. package/src/reconciler/backup-locations.js +80 -0
  654. package/src/reconciler/backup-manager.js +451 -123
  655. package/src/reconciler/index.js +86 -10
  656. package/src/reconciler/install-roots.js +90 -0
  657. package/src/reconciler/plan-executor.js +37 -15
  658. package/src/uninstallers/hook-uninstaller.js +323 -33
  659. package/src/uninstallers/integration-uninstaller.js +35 -5
  660. package/src/uninstallers/skills-uninstaller.js +95 -16
  661. package/src/uninstallers/standards-uninstaller.js +56 -7
  662. package/src/utils/agents-installer.js +10 -17
  663. package/src/utils/available-standards-report.js +144 -0
  664. package/src/utils/available-standards.js +216 -0
  665. package/src/utils/command-hash-ownership.js +103 -0
  666. package/src/utils/commit-message-judge.js +155 -0
  667. package/src/utils/copier.js +80 -2
  668. package/src/utils/deps-applicability.js +25 -0
  669. package/src/utils/detector.js +46 -1
  670. package/src/utils/friction-detector.js +27 -0
  671. package/src/utils/gate-scripts.js +141 -0
  672. package/src/utils/git-hooks.js +139 -7
  673. package/src/utils/hasher.js +36 -0
  674. package/src/utils/health-scorer.js +10 -7
  675. package/src/utils/installed-names-ownership.js +114 -0
  676. package/src/utils/integration-generator.js +36 -24
  677. package/src/utils/legacy-hook-migration.js +112 -0
  678. package/src/utils/locale.js +19 -0
  679. package/src/utils/open-work-tracking.mjs +1754 -0
  680. package/src/utils/prompt-closed.js +18 -0
  681. package/src/utils/sdd-header.js +66 -0
  682. package/src/utils/skill-frontmatter.js +102 -0
  683. package/src/utils/skill-hash-ownership.js +64 -0
  684. package/src/utils/skill-name-collision.js +169 -0
  685. package/src/utils/skills-install-paths.js +114 -0
  686. package/src/utils/skills-installer.js +75 -106
  687. package/src/utils/standard-validator.js +98 -27
  688. package/src/utils/test-change-check.js +160 -0
  689. package/src/utils/test-policy.js +214 -0
  690. package/src/utils/transient-fs.js +113 -0
  691. package/src/utils/update-summary.js +29 -0
  692. package/src/vibe/micro-spec.js +15 -0
  693. package/standards-registry.json +48 -9
@@ -0,0 +1,1754 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Open-work-tracking reference checks for OWT-017 … OWT-028.
4
+ * open-work-tracking 1.4.0 參考判定程序(OWT-017~028)。
5
+ * // implements DEC-122-L1
6
+ * // implements XSPEC-459
7
+ * // implements XSPEC-460
8
+ * // implements XSPEC-461
9
+ * // implements XSPEC-464
10
+ *
11
+ * ── Where this lives, and why there is exactly one copy ─────────────────────
12
+ * This file is the ONE body of the rules. Two front doors call it and neither
13
+ * holds a copy:
14
+ * uds open-work <next-action|revision|separation|waiting|observations|self-test> ...
15
+ * cli/src/commands/open-work.js, shipped in the npm package (`cli/src`
16
+ * is in package.json `files`), so an adopter can run it without a clone.
17
+ * node scripts/check-open-work-tracking.mjs ...
18
+ * a three-line shim in the UDS repository, kept so the documented repo
19
+ * invocation keeps working.
20
+ * It used to live only in `scripts/`, which the npm package does not contain,
21
+ * and 6.14.0-beta.1 therefore shipped a reference check no adopter could run.
22
+ * A second copy under `cli/` would have fixed that and started a second set of
23
+ * rules that drift from the first; a bundling step (prepack copies) would have
24
+ * left the source tree unable to run it. Living under `cli/src/` costs neither.
25
+ *
26
+ * ── What this is, and what it is not ────────────────────────────────────────
27
+ * core/open-work-tracking.md says UDS ships no gate. This script is NOT a gate
28
+ * and is not wired into pre-release-check.sh: UDS has no open-work carrier of
29
+ * its own for it to check. It is the reference decision procedure the standard
30
+ * offers as OWT-015 evidence — an adopter can run it against their own
31
+ * carriers, or reimplement it. It has been observed to fail against violating
32
+ * samples (see cli/tests/unit/scripts/open-work-tracking-intent-and-next-
33
+ * action.test.js, which mutates this file's source to prove it).
34
+ *
35
+ * Self-contained on purpose (node builtins only): the mutation tests copy this
36
+ * file to a temp directory and edit its text, which only works if it imports
37
+ * nothing relative. The `.mjs` extension is part of that: a copy in a bare temp
38
+ * directory has no package.json, and only `.mjs` is read as an ES module there.
39
+ *
40
+ * ── Five checks ─────────────────────────────────────────────────────────────
41
+ * next-action OWT-019 every "next action" field names a file path, test
42
+ * name, command or requirement identifier.
43
+ * Three outcomes, never one green, and (464) a fourth:
44
+ * named-resolved an object was found (a path exists)
45
+ * named-unresolved an object is named but not found
46
+ * (legitimate when the next action
47
+ * is to create it), or resolution
48
+ * could not apply (command, test
49
+ * name, identifier)
50
+ * unnamed VIOLATION — the only failure
51
+ * waiting-on-reply the row is `asked-awaiting` and `waiting` finds
52
+ * nothing wrong with it (OWT-020, OWT-022: asked-at,
53
+ * what it waits for, what releases it), so its next
54
+ * step IS the reply and OWT-019 is not applied. Not
55
+ * a violation, not "named", not complete; listed
56
+ * apart with its age. Decided by the same function
57
+ * `waiting` runs, never by a second copy.
58
+ * A field is read in three shapes, all through the one
59
+ * VOCAB.nextAction list: a heading section, an inline
60
+ * "Next action: ..." label, and EVERY ROW of a table column whose
61
+ * header is in that list (each report carries the line and the
62
+ * row's first cell, so it can be found).
63
+ * Not evaluated, counted: an empty cell, `-`, `—`, `n/a`, `none`,
64
+ * `done`. OWT-019 is NOT violated by them: it judges a next action
65
+ * that was written; "no next action written" is another failure
66
+ * this check does not decide (a finished item has none either).
67
+ * Undecidable, listed: a table row whose cell count differs from its
68
+ * header (a stray or missing `|`). It is neither judged nor read as
69
+ * empty. A violation elsewhere still exits 1; otherwise the exit is 2,
70
+ * because "no violation found" would then cover only part of the field.
71
+ * revision OWT-018 the acceptance/goal/constraint sections changed
72
+ * between two versions of a carrier; a NEW revision
73
+ * record (change, approver, reason) must exist. No
74
+ * record, or an incomplete one -> violation. A record
75
+ * whose approver is empty, and an edit with no record
76
+ * at all, are LISTED for the hand-back (OWT-007). The
77
+ * listing never changes the exit code (OWT-008).
78
+ * separation OWT-017 no single carrier holds both an intent section and
79
+ * a progress / next-action section.
80
+ * waiting OWT-020 a waiting item says which of two states it is in:
81
+ * not-yet-asked or asked-awaiting. A waiting item that is
82
+ * neither is named one by one, never folded into a total.
83
+ * OWT-021 not-yet-asked names the draft or action (a path, command,
84
+ * test name or identifier; the OWT-019 recognisers).
85
+ * OWT-022 asked-awaiting carries asked-at (a dated day), what it
86
+ * waits for and what event releases it (OWT-002).
87
+ * observations OWT-023 a hand-written row about an external fact the assistant
88
+ * cannot observe carries observed-by, observed-at (a dated
89
+ * day, not in the future) and a value of yes, no or unknown.
90
+ * OWT-024 unknown is counted apart and never complete; a row marked
91
+ * done while unknown is a violation.
92
+ * OWT-025 the age of every observation is shown; one older than the
93
+ * threshold is reported as stale, counted apart, never confirmed.
94
+ * OWT-026 the exception does not reach a subject that version control,
95
+ * a spec marker or a CI result determines (OWT-003 stands).
96
+ * Time is injected (`--now`, `--stale-after`), never read inside a rule.
97
+ *
98
+ * ── What none of them can decide (stated, not implied) ──────────────────────
99
+ * - Whether a revision record honestly describes the diff (OWT-014: that is
100
+ * a claim about meaning, not a relation over artefacts). The check decides
101
+ * that the intent changed, that a new record exists, that it is complete,
102
+ * and whether its approver is filled in — nothing more.
103
+ * - Whether a named object is the RIGHT object.
104
+ * - Recognising "this string is a path / command / test name / identifier"
105
+ * is pattern matching, so its coverage is UNKNOWN (OWT-011). An unrecognised
106
+ * format is reported as unnamed, and a clean pass never means "every next
107
+ * action is specific".
108
+ * - Prose revision notes ("2026-09-29 amended R1") are not structural records.
109
+ * Only table rows and list items inside a section whose heading is a
110
+ * revision heading are read.
111
+ * - Whether an observation is TRUE, or still true now (OWT-014). `observations`
112
+ * decides that the fields exist, are well formed and how old the stamp is. A
113
+ * stamp says who saw it and when, never that it still holds.
114
+ * - A waiting item written in words VOCAB_STATE does not hold is read as "other",
115
+ * not as waiting; a table with neither an observed-by nor an observed-at column
116
+ * is not an observation carrier. A clean pass covers only what was recognised.
117
+ *
118
+ * ── UNCALIBRATED (OWT-016) ──────────────────────────────────────────────────
119
+ * Everything in VOCAB, VOCAB_STATE, DEFAULT_STALE_AFTER_DAYS, COMMANDS, EXTENSIONS,
120
+ * DEFAULT_ID_PATTERN and ID_PREFIX_DENYLIST is an initial judgment. None of it was measured against
121
+ * real usage. Adopters should pass their own identifier pattern
122
+ * (--id-pattern) and read the heading vocabulary as a starting point.
123
+ *
124
+ * Exit codes: 0 no violation · 1 violation · 2 cannot decide (no structure
125
+ * found, a next-action table row could not be read, git failed, or this
126
+ * script's own self-test arms failed). 2 is NOT a pass.
127
+ *
128
+ * Usage (`uds` from the npm package, or the repo shim; same arguments):
129
+ * uds open-work next-action <file...> [--root DIR] [--id-pattern RE] [--next-action-word WORD ...] [--command-word WORD ...] [--now YYYY-MM-DD] [--stale-after DAYS]
130
+ * uds open-work revision --file PATH --base GIT_REV
131
+ * uds open-work revision --before FILE --after FILE
132
+ * uds open-work separation <file...> [--next-action-word WORD ...]
133
+ * uds open-work waiting <file...> [--root DIR] [--root NAME=DIR ...] [--id-pattern RE] [--now YYYY-MM-DD] [--asked-at-word WORD ...] [--waiting-for-word WORD ...]
134
+ * uds open-work observations <file...> [--now YYYY-MM-DD] [--stale-after DAYS]
135
+ * uds open-work self-test
136
+ * node scripts/check-open-work-tracking.mjs next-action <file...> ... (repo clone)
137
+ * node scripts/check-open-work-tracking.mjs --self-test
138
+ */
139
+
140
+ import { readFileSync, existsSync, realpathSync, statSync } from 'node:fs';
141
+ import { execFileSync, spawnSync } from 'node:child_process';
142
+ import { resolve, dirname, join, isAbsolute, basename } from 'node:path';
143
+ import { fileURLToPath } from 'node:url';
144
+
145
+ // ── Vocabulary (UNCALIBRATED, OWT-016) ───────────────────────────────────────
146
+
147
+ // ONE list of "next action" words (461 R1). It is read three ways and there is no second copy:
148
+ // a heading (classifyHeading), a table column header (extractNextActions) and an inline
149
+ // label ("Next action: ...", built from the same source). Each entry is [regex source, text shown to a
150
+ // reader who asks which words are recognised]. Keep the sources free of capture groups: the
151
+ // label regex embeds them and reads its own group 1.
152
+ //
153
+ // 回來要做什麼 ("what to do when you come back") is the header the dev-platform worklog's
154
+ // main table actually uses (DEC-122 H2 baseline carrier); that file describes the column as
155
+ // 下一動 in prose but the header text drifted. Added because a header outside this list is
156
+ // invisible to the check, which is the failure DEC-122 measured. 下一個動作, 下一個步驟 and
157
+ // 接下來要做什麼 (461 R1) mean "next action" and nothing wider.
158
+ //
159
+ // What is deliberately NOT here, and is pinned by a regression test: 待辦, 後續, Next, TODO,
160
+ // Action, and a bare 接下來. They also head columns that are not the next action (a backlog, a
161
+ // follow-up list, a "next release"), and reading those as next actions would let a violation hide
162
+ // behind a column that was never one. An adopter whose carrier uses one of them declares it
163
+ // (--next-action-word, or open_work.next_action_words in uds.project.yaml).
164
+ //
165
+ // Adopter-specific and UNCALIBRATED (OWT-016).
166
+ export const NEXT_ACTION_WORDS = [
167
+ ['next[\\s-]?(?:action|step)s?', 'next action, next step (also "next-action", "next steps")'],
168
+ ['下一步', '下一步'],
169
+ ['下一動', '下一動'],
170
+ ['回來要做什麼', '回來要做什麼'],
171
+ ['下一個動作', '下一個動作'],
172
+ ['下一個步驟', '下一個步驟'],
173
+ ['接下來要做什麼', '接下來要做什麼'],
174
+ ];
175
+
176
+ export const VOCAB = {
177
+ revision: /revision|change[\s-]?log|amendment|history|修訂|變更紀錄|變更記錄|修改紀錄|修改記錄|異動/i,
178
+ nextAction: new RegExp(NEXT_ACTION_WORDS.map(([source]) => source).join('|'), 'i'),
179
+ progress: /\bprogress\b|\bstate\b|\bblockers?\b|\bblocked\b|進度|現況|卡在/i,
180
+ intent: /acceptance|criteria|\brequirements?\b|\bgoals?\b|objectives?|constraints?|驗收|需求|目標|限制/i,
181
+ // revision-table columns / labelled list fields
182
+ colChange: /what|change|改了什麼|修改|變更|內容/i,
183
+ colApprover: /approv|核可|核准|批准|同意|確認者/i,
184
+ colReason: /reason|why|理由|原因|為什麼/i,
185
+ };
186
+
187
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
188
+
189
+ /**
190
+ * Words an adopter declares (461 R2), as plain text: not a regular expression (a `.` or `(` in a word is
191
+ * that character), case-insensitive, matched as a substring like the built-in ones. A blank word is
192
+ * REFUSED, never dropped: an empty alternative matches every header and would turn the check green.
193
+ * @returns {{words:string[], error:string|null}}
194
+ */
195
+ export function normaliseDeclaredWords(raw = []) {
196
+ const words = [];
197
+ for (const w of raw) {
198
+ const word = typeof w === 'string' ? w.replace(/\s+/g, ' ').trim() : '';
199
+ if (!word) return { words: [], error: 'a declared next-action word is empty or blank; it would match every header, so it is refused (give the exact word, for example --next-action-word 待辦)' }; // [mutation-anchor:blank-word-refused]
200
+ if (!words.some((x) => x.toLowerCase() === word.toLowerCase())) words.push(word);
201
+ }
202
+ return { words, error: null };
203
+ }
204
+
205
+ /**
206
+ * Field words an adopter declares for the waiting checks (XSPEC-475 R3): the words that head the asked-at column and the
207
+ * "what is it waiting for" column in THIS project's carriers. Same rules as the next-action words: plain text, never a
208
+ * pattern, case-insensitive, and a blank one is refused (an empty alternative would match every header).
209
+ * @param {string[]} raw
210
+ * @param {string} flag - the option name, for the message (for example `--asked-at-word`)
211
+ * @param {string} example - a word to show in the message
212
+ * @returns {{words:string[], error:string|null}}
213
+ */
214
+ export function normaliseDeclaredFieldWords(raw = [], flag = '--asked-at-word', example = '何時問') {
215
+ const words = [];
216
+ for (const w of raw) {
217
+ const word = typeof w === 'string' ? w.replace(/\s+/g, ' ').trim() : '';
218
+ if (!word) return { words: [], error: `a declared ${flag} is empty or blank; it would match every header, so it is refused (give the exact word, for example ${flag} ${example})` }; // [mutation-anchor:blank-field-word-refused]
219
+ if (!words.some((x) => x.toLowerCase() === word.toLowerCase())) words.push(word);
220
+ }
221
+ return { words, error: null };
222
+ }
223
+
224
+ /** `--asked-at-word` and `--waiting-for-word`, validated: `{ words: { askedAt, awaiting }, error }`. */
225
+ function declaredRoleWords(flagAll) {
226
+ const askedAt = normaliseDeclaredFieldWords(flagAll('--asked-at-word'), '--asked-at-word', '何時問');
227
+ if (askedAt.error) return { words: {}, error: askedAt.error };
228
+ const awaiting = normaliseDeclaredFieldWords(flagAll('--waiting-for-word'), '--waiting-for-word', '問什麼');
229
+ if (awaiting.error) return { words: {}, error: awaiting.error };
230
+ return { words: { askedAt: askedAt.words, awaiting: awaiting.words }, error: null };
231
+ }
232
+
233
+ /**
234
+ * Program names an adopter declares (461 R5), under the same rules as the next-action words: plain text, never a
235
+ * pattern, and a blank one is refused. A command is one program name, so a word with a space in it could never
236
+ * match the first word of a command and is refused as well, with the reason, instead of being accepted and inert.
237
+ * @returns {{words:string[], error:string|null}}
238
+ */
239
+ export function normaliseDeclaredCommands(raw = []) {
240
+ const words = [];
241
+ for (const w of raw) {
242
+ const word = typeof w === 'string' ? w.trim() : '';
243
+ if (!word) return { words: [], error: 'a declared command word is empty or blank; it would read every sentence as a command, so it is refused (give the program name, for example --command-word kubectl)' }; // [mutation-anchor:blank-command-refused]
244
+ if (/\s/.test(word)) return { words: [], error: `a declared command word is one program name, and "${word}" has a space in it, so it could never match; give the program name alone (for example --command-word kubectl)` };
245
+ if (!words.includes(word) && !COMMANDS.includes(word)) words.push(word);
246
+ }
247
+ return { words, error: null };
248
+ }
249
+
250
+ /** The one recognition pattern: the built-in list, plus the declared words when there are any. */
251
+ export function nextActionRegExp(words = []) {
252
+ if (!words.length) return VOCAB.nextAction;
253
+ return new RegExp(`${VOCAB.nextAction.source}|${words.map(escapeRegExp).join('|')}`, 'i'); // [mutation-anchor:declared-merged]
254
+ }
255
+
256
+ const LABELS = [
257
+ ['change', /(?:what(?:\s+changed)?|changed?|改了什麼|修改|變更)\s*[::]/gi],
258
+ ['approver', /(?:approved\s+by|approver|approval|核可者|核可|核准|批准)\s*[::]/gi],
259
+ ['reason', /(?:reason|why|理由|原因|為什麼)\s*[::]/gi],
260
+ ];
261
+
262
+ const NO_APPROVER = /^(?:|-+|—|–|n\/?a|none|tbd|pending|unknown|\?+|無|未核可|待定|待核可|尚未)$/i;
263
+ const EMPTY_FIELD = /^(?:|-+|—|–|n\/?a|none|無|done|完成|已完成|✅)$/i;
264
+
265
+ // Words that make `word arg` read as a command in prose. Deliberately excludes
266
+ // common English words (go, make, sh): "go through the list" is not a command.
267
+ // glab and dotnet (461 R5) are here because a user's carriers named them (`glab mr merge 486`, a .NET
268
+ // project); every other tool is declared by the adopter (--command-word, or open_work.command_words).
269
+ // A command is matched as an exact program name, case-sensitively, as the built-in ones are.
270
+ export const COMMANDS = [
271
+ 'npm', 'npx', 'pnpm', 'yarn', 'node', 'tsx', 'git', 'gh', 'glab', 'bash', 'python', 'python3',
272
+ 'pytest', 'vitest', 'docker', 'cargo', 'dotnet', 'uds', 'egr',
273
+ ];
274
+
275
+ export const EXTENSIONS = [
276
+ 'md', 'mdx', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'sh', 'bash', 'zsh', 'yaml', 'yml',
277
+ 'json', 'jsonc', 'tsv', 'csv', 'toml', 'sql', 'css', 'scss', 'html', 'txt', 'rb', 'go', 'rs',
278
+ 'java', 'kt', 'swift', 'lock', 'env', 'conf', 'ini', 'xml', 'svg', 'plist',
279
+ ];
280
+
281
+ export const DEFAULT_ID_PATTERN = '\\b[A-Z][A-Z0-9]{1,9}-\\d{1,6}\\b|\\b(?:R|OQ|AC)\\d{1,3}\\b';
282
+ export const ID_PREFIX_DENYLIST = ['UTF', 'SHA', 'ISO', 'GPT', 'RFC', 'CRC', 'AES', 'RSA', 'TLS', 'MD', 'HTTP'];
283
+
284
+ // ── Markdown structure walk ──────────────────────────────────────────────────
285
+
286
+ /** @returns {string|null} */
287
+ function classifyHeading(h, nextRe = VOCAB.nextAction) {
288
+ if (VOCAB.revision.test(h)) return 'revision';
289
+ if (nextRe.test(h)) return 'nextAction';
290
+ if (VOCAB.progress.test(h)) return 'progress';
291
+ if (VOCAB.intent.test(h)) return 'intent';
292
+ return null;
293
+ }
294
+
295
+ /**
296
+ * Annotate every line with the class of its innermost classified ancestor
297
+ * heading. Front matter and fenced blocks keep their text but are flagged.
298
+ */
299
+ export function parseDoc(md, nextRe = VOCAB.nextAction) {
300
+ const raw = md.split(/\r?\n/);
301
+ const lines = [];
302
+ const stack = [];
303
+ let inFence = false;
304
+ let fenceMark = '';
305
+ let i = 0;
306
+ let inFront = false;
307
+ if (raw[0] && raw[0].trim() === '---') {
308
+ inFront = true;
309
+ i = 1;
310
+ lines.push({ text: raw[0], cls: null, owner: null, front: true });
311
+ }
312
+ for (; i < raw.length; i++) {
313
+ const text = raw[i];
314
+ if (inFront) {
315
+ lines.push({ text, cls: null, owner: null, front: true });
316
+ if (text.trim() === '---') inFront = false;
317
+ continue;
318
+ }
319
+ const fence = /^\s*(```|~~~)/.exec(text);
320
+ if (fence) {
321
+ if (!inFence) { inFence = true; fenceMark = fence[1]; } else if (fence[1] === fenceMark) { inFence = false; }
322
+ const own = innermost(stack);
323
+ lines.push({ text, cls: own ? own.cls : null, owner: own, fence: true });
324
+ continue;
325
+ }
326
+ if (!inFence) {
327
+ const h = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(text);
328
+ if (h) {
329
+ const level = h[1].length;
330
+ while (stack.length && stack[stack.length - 1].level >= level) stack.pop();
331
+ const entry = { level, heading: h[2], cls: classifyHeading(h[2], nextRe) };
332
+ stack.push(entry);
333
+ const own = innermost(stack);
334
+ lines.push({ text, cls: own ? own.cls : null, owner: own, heading: entry });
335
+ continue;
336
+ }
337
+ }
338
+ const own = innermost(stack);
339
+ lines.push({ text, cls: own ? own.cls : null, owner: own, inFence });
340
+ }
341
+ return lines;
342
+ }
343
+
344
+ function innermost(stack) {
345
+ for (let k = stack.length - 1; k >= 0; k--) if (stack[k].cls) return stack[k];
346
+ return null;
347
+ }
348
+
349
+ const norm = (s) => s.replace(/\s+/g, ' ').trim();
350
+
351
+ /** A table line may sit inside a Markdown blockquote ("> | a | b |"): drop the quote marker. */
352
+ const unquote = (line) => line.replace(/^\s*(?:>\s?)+/, '');
353
+
354
+ /** Index of the closing backtick run of exactly `n` backticks at or after `from`, or -1. */
355
+ function closingRun(t, from, n) {
356
+ let j = from;
357
+ while (j < t.length) {
358
+ if (t[j] !== '`') { j++; continue; }
359
+ let m = 0;
360
+ while (t[j + m] === '`') m++;
361
+ if (m === n) return j;
362
+ j += m;
363
+ }
364
+ return -1;
365
+ }
366
+
367
+ /**
368
+ * Split one table row into cells. A `|` does NOT split a cell when it is escaped (`\|`) or
369
+ * sits inside a code span that closes on the same line. The second rule is deliberately
370
+ * looser than GFM (which splits inside code unless escaped): a hand-written note such as
371
+ * `tar -tzf \| grep` or `a|b` in backticks means one cell, and splitting it would shift
372
+ * every later column and misread the next-action cell. An unclosed backtick is literal.
373
+ */
374
+ function splitRow(line) {
375
+ let t = unquote(line).trim();
376
+ if (t.startsWith('|')) t = t.slice(1);
377
+ const cells = [];
378
+ let cur = '';
379
+ let lastDelim = false;
380
+ let i = 0;
381
+ while (i < t.length) {
382
+ const ch = t[i];
383
+ lastDelim = false;
384
+ if (ch === '\\' && t[i + 1] === '|') { cur += '|'; i += 2; continue; }
385
+ if (ch === '`') {
386
+ let n = 0;
387
+ while (t[i + n] === '`') n++;
388
+ const close = closingRun(t, i + n, n);
389
+ if (close !== -1) { cur += t.slice(i, close + n).replace(/\\\|/g, '|'); i = close + n; continue; }
390
+ cur += '`'.repeat(n);
391
+ i += n;
392
+ continue;
393
+ }
394
+ if (ch === '|') { cells.push(cur); cur = ''; lastDelim = true; i++; continue; }
395
+ cur += ch;
396
+ i++;
397
+ }
398
+ if (!lastDelim) cells.push(cur); // a trailing unescaped `|` closes the row; it opens no cell
399
+ return cells.map(norm);
400
+ }
401
+
402
+ const isSepRow = (line) => /^\s*\|?[\s:|-]+\|?\s*$/.test(unquote(line)) && /-/.test(line);
403
+
404
+ /** Tables among annotated lines: [{header, rows:[{cells, idx}]}] */
405
+ function findTables(lines) {
406
+ const tables = [];
407
+ let k = 0;
408
+ while (k < lines.length) {
409
+ const l = lines[k];
410
+ if (!l.inFence && !l.fence && !l.front && unquote(l.text).trim().startsWith('|') && k + 1 < lines.length
411
+ && isSepRow(lines[k + 1].text) && unquote(lines[k + 1].text).trim().startsWith('|')) {
412
+ const header = splitRow(l.text);
413
+ const rows = [];
414
+ let j = k + 2;
415
+ while (j < lines.length && unquote(lines[j].text).trim().startsWith('|')) {
416
+ rows.push({ cells: splitRow(lines[j].text), idx: j });
417
+ j++;
418
+ }
419
+ tables.push({ header, rows, headerIdx: k });
420
+ k = j;
421
+ } else {
422
+ k++;
423
+ }
424
+ }
425
+ return tables;
426
+ }
427
+
428
+ // ── OWT-018: intent sections and revision records ────────────────────────────
429
+
430
+ /** Map "<heading>#<n>" -> normalised body, for sections classed as intent. */
431
+ export function intentSections(md) {
432
+ const map = new Map();
433
+ const seen = new Map();
434
+ const bodies = new Map();
435
+ for (const l of parseDoc(md)) {
436
+ if (l.cls !== 'intent' || !l.owner || l.heading === l.owner) continue;
437
+ if (!bodies.has(l.owner)) {
438
+ const n = (seen.get(l.owner.heading) || 0) + 1;
439
+ seen.set(l.owner.heading, n);
440
+ bodies.set(l.owner, `${l.owner.heading}#${n}`);
441
+ map.set(bodies.get(l.owner), []);
442
+ }
443
+ const t = norm(l.text);
444
+ if (t) map.get(bodies.get(l.owner)).push(t);
445
+ }
446
+ // An intent heading with no body lines still exists as a (empty) section.
447
+ for (const l of parseDoc(md)) {
448
+ if (l.heading && l.heading.cls === 'intent' && !bodies.has(l.heading)) {
449
+ const n = (seen.get(l.heading.heading) || 0) + 1;
450
+ seen.set(l.heading.heading, n);
451
+ bodies.set(l.heading, `${l.heading.heading}#${n}`);
452
+ map.set(bodies.get(l.heading), []);
453
+ }
454
+ }
455
+ const out = new Map();
456
+ for (const [k, v] of map) out.set(k, v.join('\n'));
457
+ return out;
458
+ }
459
+
460
+ function parseLabelled(text) {
461
+ const t = text.replace(/\*\*|__/g, '');
462
+ const hits = [];
463
+ for (const [kind, re] of LABELS) {
464
+ re.lastIndex = 0;
465
+ let m;
466
+ while ((m = re.exec(t)) !== null) hits.push({ kind, start: m.index, end: m.index + m[0].length });
467
+ }
468
+ hits.sort((a, b) => a.start - b.start);
469
+ const out = { change: '', approver: '', reason: '' };
470
+ if (!hits.length) { out.change = norm(t); return out; }
471
+ for (let h = 0; h < hits.length; h++) {
472
+ const next = hits[h + 1] ? hits[h + 1].start : t.length;
473
+ const val = norm(t.slice(hits[h].end, next)).replace(/[;;,,|]+$/, '').trim();
474
+ if (!out[hits[h].kind]) out[hits[h].kind] = val;
475
+ }
476
+ return out;
477
+ }
478
+
479
+ /** Revision records: table rows and list items inside revision-class sections. */
480
+ export function revisionEntries(md) {
481
+ const lines = parseDoc(md);
482
+ const entries = [];
483
+ const revLines = lines.map((l) => l.cls === 'revision' && !l.heading && !l.front);
484
+ // tables
485
+ const tableLineIdx = new Set();
486
+ for (const t of findTables(lines)) {
487
+ if (!revLines[t.headerIdx]) continue;
488
+ const ci = t.header.findIndex((c) => VOCAB.colChange.test(c));
489
+ const ai = t.header.findIndex((c) => VOCAB.colApprover.test(c));
490
+ const ri = t.header.findIndex((c) => VOCAB.colReason.test(c));
491
+ tableLineIdx.add(t.headerIdx); tableLineIdx.add(t.headerIdx + 1);
492
+ for (const r of t.rows) {
493
+ tableLineIdx.add(r.idx);
494
+ const others = r.cells.filter((_, n) => n !== ai && n !== ri);
495
+ entries.push({
496
+ key: norm(r.cells.join('|')).toLowerCase(),
497
+ change: ci >= 0 ? (r.cells[ci] || '') : norm(others.join(' ')),
498
+ approver: ai >= 0 ? (r.cells[ai] || '') : '',
499
+ reason: ri >= 0 ? (r.cells[ri] || '') : '',
500
+ });
501
+ }
502
+ }
503
+ // list items
504
+ let cur = null;
505
+ const flush = () => {
506
+ if (cur !== null) {
507
+ const f = parseLabelled(cur);
508
+ entries.push({ key: norm(cur).toLowerCase(), ...f });
509
+ }
510
+ cur = null;
511
+ };
512
+ lines.forEach((l, idx) => {
513
+ if (!revLines[idx] || l.inFence || l.fence || tableLineIdx.has(idx)) { if (!revLines[idx]) flush(); return; }
514
+ const li = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/.exec(l.text);
515
+ if (li) { flush(); cur = li[1]; } else if (cur !== null && /^\s+\S/.test(l.text)) { cur += ' ' + l.text.trim(); } else { flush(); }
516
+ });
517
+ flush();
518
+ return entries;
519
+ }
520
+
521
+ /**
522
+ * OWT-018. before === null means the carrier did not exist in the baseline.
523
+ * @returns {{status:string, changedSections:string[], newEntries:object[], violations:object[], handBack:object[]}}
524
+ */
525
+ export function checkIntentRevision({ before, after, path = '(carrier)' }) {
526
+ const res = { status: '', path, changedSections: [], newEntries: [], violations: [], handBack: [] };
527
+ const a = intentSections(after);
528
+ if (before === null) { res.status = 'no-baseline'; return res; }
529
+ const b = intentSections(before);
530
+ if (a.size === 0 && b.size === 0) { res.status = 'undecidable'; return res; }
531
+ const keys = new Set([...a.keys(), ...b.keys()]);
532
+ for (const k of keys) if (a.get(k) !== b.get(k)) res.changedSections.push(k.replace(/#\d+$/, ''));
533
+ res.changedSections = [...new Set(res.changedSections)];
534
+ const intentChanged = res.changedSections.length > 0; // [mutation-anchor:intent-changed]
535
+ if (!intentChanged) { res.status = 'unchanged'; return res; }
536
+ const beforeKeys = new Set(revisionEntries(before).map((e) => e.key));
537
+ res.newEntries = revisionEntries(after).filter((e) => !beforeKeys.has(e.key));
538
+ if (res.newEntries.length === 0) {
539
+ res.status = 'changed-no-record';
540
+ res.violations.push({ rule: 'OWT-018', why: 'intent changed and no new revision record exists', sections: res.changedSections });
541
+ res.handBack.push({ rule: 'OWT-018', why: 'no approver: there is no revision record at all', sections: res.changedSections });
542
+ return res;
543
+ }
544
+ res.status = 'changed-recorded';
545
+ for (const e of res.newEntries) {
546
+ if (!e.change || !e.reason) {
547
+ res.violations.push({ rule: 'OWT-018', why: 'revision record is incomplete (needs what changed and why)', entry: e.key });
548
+ }
549
+ const hasApprover = !NO_APPROVER.test(e.approver.trim()); // [mutation-anchor:has-approver]
550
+ if (!hasApprover) {
551
+ res.handBack.push({ rule: 'OWT-018', why: 'revision record has no approver', sections: res.changedSections, entry: e.key });
552
+ }
553
+ }
554
+ return res;
555
+ }
556
+
557
+ // ── OWT-017: carrier separation ──────────────────────────────────────────────
558
+
559
+ export function checkSeparation(carriers, opts = {}) {
560
+ const res = { walked: carriers.length, recognised: 0, violations: [] };
561
+ const nextRe = nextActionRegExp(opts.words);
562
+ for (const c of carriers) {
563
+ const lines = parseDoc(c.content, nextRe);
564
+ const intent = new Set();
565
+ const progress = new Set();
566
+ for (const l of lines) {
567
+ if (!l.heading) continue;
568
+ if (l.heading.cls === 'intent') intent.add(l.heading.heading);
569
+ if (l.heading.cls === 'progress' || l.heading.cls === 'nextAction') progress.add(l.heading.heading);
570
+ }
571
+ if (intent.size || progress.size) res.recognised++;
572
+ const both = intent.size > 0 && progress.size > 0; // [mutation-anchor:separation-both]
573
+ if (both) {
574
+ res.violations.push({ rule: 'OWT-017', path: c.path, intent: [...intent], progress: [...progress] });
575
+ }
576
+ }
577
+ return res;
578
+ }
579
+
580
+ // ── OWT-019: next-action naming ──────────────────────────────────────────────
581
+
582
+ const stripPunct = (s) => s.replace(/^[("'「『“]+|[)"'」』”.,;:!?、。,;:)]+$/g, '');
583
+
584
+ // A slash command (`/work`, `/sdd`): one leading slash and one word, no extension. It names an action to run, not a file.
585
+ // XSPEC-475 R5(b): it used to be read as the absolute path `/work` and reported path-missing.
586
+ const SLASH_COMMAND = /^\/[A-Za-z][\w-]*$/;
587
+
588
+ function pathLike(tok, inCode) {
589
+ const t = stripPunct(tok).replace(/:\d+(?::\d+)?$/, '');
590
+ if (!t || /\s/.test(t) || /^[a-z][a-z0-9+.-]*:\/\//i.test(t)) return null;
591
+ if (SLASH_COMMAND.test(t)) return null; // [mutation-anchor:slash-command-not-path]
592
+ const segs = t.split('/');
593
+ const last = segs[segs.length - 1];
594
+ const ext = /\.([A-Za-z0-9]+)$/.exec(last);
595
+ const hasExt = !!ext && EXTENSIONS.includes(ext[1].toLowerCase()) && last.length > ext[0].length;
596
+ const slashes = segs.length - 1;
597
+ const leading = /^(?:\.{1,2}\/|~\/|\/)./.test(t);
598
+ if (inCode) return (slashes >= 1 || hasExt) && /^[\w@./~-]+$/.test(t) ? t : null;
599
+ if (/^[\w@./~-]+$/.test(t) && (hasExt || leading || slashes >= 2)) return t;
600
+ return null;
601
+ }
602
+
603
+ /**
604
+ * @returns {{status:string, kinds:{kind:string,value:string}[], resolution:string}}
605
+ */
606
+ export function classifyNextAction(text, opts = {}) {
607
+ const idRe = new RegExp(opts.idPattern || DEFAULT_ID_PATTERN, 'g');
608
+ const commands = [...COMMANDS, ...(opts.extraCommands || [])]; // [mutation-anchor:extra-commands]
609
+ const kinds = [];
610
+ const push = (kind, value) => { if (!kinds.some((k) => k.kind === kind && k.value === value)) kinds.push({ kind, value }); };
611
+ const idOk = (v) => !ID_PREFIX_DENYLIST.includes(v.split('-')[0]);
612
+
613
+ // 1) inline code spans: the author marked these as literal names
614
+ const prose = text.replace(/`([^`]+)`/g, (_, c) => {
615
+ const code = c.trim();
616
+ const first = code.split(/\s+/)[0].replace(/^\$\s*/, '');
617
+ if (/^\/[A-Za-z][\w-]*(?:\s|$)/.test(code)) push('command', code); // a slash command, with or without arguments (XSPEC-475 R5(b))
618
+ else if (pathLike(code, true)) push('path', pathLike(code, true)); // [mutation-anchor:kind-path]
619
+ else if (commands.includes(first) || /^\.{1,2}\//.test(first)) push('command', code); // [mutation-anchor:kind-command]
620
+ else if (/\.(?:test|spec)\.[cm]?[jt]sx?|(?:^|[\s/])test_\w+|::/.test(code)) push('test', code); // [mutation-anchor:kind-test]
621
+ else {
622
+ idRe.lastIndex = 0;
623
+ const m = idRe.exec(code);
624
+ if (m && idOk(m[0])) push('id', m[0]);
625
+ }
626
+ return ' ';
627
+ });
628
+
629
+ // 2) prose
630
+ for (const tok of prose.split(/\s+/)) {
631
+ const p = pathLike(tok, false);
632
+ if (p) push('path', p);
633
+ else if (SLASH_COMMAND.test(stripPunct(tok))) push('command', stripPunct(tok));
634
+ }
635
+ const cmdRe = new RegExp(`(?:^|[^\\w-])(${commands.map(escapeRegExp).join('|')})\\s+([-@\\w./:]+)`, 'g');
636
+ let m;
637
+ while ((m = cmdRe.exec(prose)) !== null) push('command', `${m[1]} ${m[2]}`);
638
+ const testRe = /(?:test|測試)\s*[「"“']([^」"”']{6,})[」"”']/gi;
639
+ while ((m = testRe.exec(prose)) !== null) push('test', m[1]);
640
+ idRe.lastIndex = 0;
641
+ while ((m = idRe.exec(prose)) !== null) if (idOk(m[0])) push('id', m[0]); // [mutation-anchor:kind-id]
642
+
643
+ const named = kinds.length > 0; // [mutation-anchor:named]
644
+ if (!named) return { status: 'unnamed', kinds, resolution: 'n/a' };
645
+ const root = opts.root;
646
+ let resolved = false;
647
+ if (root) {
648
+ for (const k of kinds) {
649
+ if (k.kind !== 'path') continue;
650
+ const rel = k.value.replace(/^\.\//, '');
651
+ if (existsSync(isAbsolute(rel) ? rel : join(root, rel))) resolved = true;
652
+ }
653
+ }
654
+ // Only a PATH is ever looked up. A command, a test name or a requirement identifier is checked for being NAMED and
655
+ // can never be resolved, so a named-unresolved row is one of two different things (461 R6): a path that was looked
656
+ // up and is not there, or something that is never looked up. The status stays named-unresolved for both.
657
+ const lookedUp = !!root && kinds.some((k) => k.kind === 'path');
658
+ return {
659
+ status: resolved ? 'named-resolved' : 'named-unresolved',
660
+ kinds,
661
+ resolution: root ? 'attempted (paths only)' : 'not attempted (no --root)',
662
+ unresolved: resolved ? null : (lookedUp ? 'path-missing' : 'not-resolvable'), // [mutation-anchor:unresolved-split]
663
+ };
664
+ }
665
+
666
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n)}…` : s);
667
+
668
+ /**
669
+ * Find "next action" fields in a carrier. Three shapes are read, all through the ONE
670
+ * vocabulary VOCAB.nextAction: a heading section, an inline label, and a table column whose
671
+ * HEADER is in that vocabulary (every row of that column is one field).
672
+ *
673
+ * A table row whose cell count differs from the header's is returned in `ragged`, not in
674
+ * `items`: after a stray or missing `|` the next-action cell cannot be told from its
675
+ * neighbour, and reading an absent cell as "empty" would turn a broken row into a quiet
676
+ * "no next action written". It is neither judged nor dropped: the caller counts and lists it.
677
+ * @returns {{fields:number, items:{text:string,where:string,idx?:number}[], ragged:{where:string,cells:number,expected:number}[]}}
678
+ * `idx` is the 0-based line of a table row or an inline label; a heading section has none (464: that is how a next-action item
679
+ * is joined to the record `waiting` read on the same line).
680
+ */
681
+ export function extractNextActions(md, words = []) {
682
+ const nextRe = nextActionRegExp(words);
683
+ const lines = parseDoc(md, nextRe);
684
+ const items = [];
685
+ const ragged = [];
686
+ let fields = 0;
687
+ const tableIdx = new Set();
688
+ const headerIdx = new Set();
689
+ const tables = findTables(lines);
690
+
691
+ for (const t of tables) {
692
+ // every header cell in the shared vocabulary is a next-action column (usually exactly one)
693
+ const cols = t.header.map((c, n) => (nextRe.test(c) ? n : -1)).filter((n) => n >= 0); // [mutation-anchor:table-header]
694
+ const hasCol = cols.length > 0;
695
+ tableIdx.add(t.headerIdx); tableIdx.add(t.headerIdx + 1); headerIdx.add(t.headerIdx);
696
+ t.rows.forEach((r) => tableIdx.add(r.idx));
697
+ if (hasCol) {
698
+ for (const r of t.rows) {
699
+ const who = `row "${clip(r.cells[0].replace(/\*\*|__/g, ''), 40)}"`;
700
+ if (r.cells.length !== t.header.length) {
701
+ ragged.push({ idx: r.idx, where: `table row (line ${r.idx + 1}, ${who})`, cells: r.cells.length, expected: t.header.length });
702
+ continue;
703
+ }
704
+ for (const col of cols) {
705
+ fields++;
706
+ items.push({ text: r.cells[col], idx: r.idx, where: `table column "${t.header[col]}" (line ${r.idx + 1}, ${who})` });
707
+ }
708
+ }
709
+ }
710
+ // rows inside a nextAction-class section are handled by the section walk below
711
+ t.hasNextActionColumn = hasCol;
712
+ }
713
+
714
+ // inline labelled "**Next action**: ..." (outside tables that have their own column)
715
+ const labelRe = new RegExp(`(?:\\*\\*|__)?(?:${nextRe.source})(?:\\*\\*|__)?\\s*[::]\\s*(.+)$`, 'i');
716
+ const colTableRows = new Set();
717
+ // Only rows read through the column are exempt from the label scan. A ragged row was not
718
+ // read, so an inline "Next action: ..." inside it must still be seen (else it goes dark).
719
+ const raggedIdx = new Set(ragged.map((g) => g.idx));
720
+ for (const t of tables) if (t.hasNextActionColumn) t.rows.forEach((r) => { if (!raggedIdx.has(r.idx)) colTableRows.add(r.idx); });
721
+ lines.forEach((l, idx) => {
722
+ if (l.front || l.fence || l.inFence || l.heading || l.cls === 'nextAction' || colTableRows.has(idx)) return;
723
+ // a label inside a table row reads to the end of the row, not into its closing pipe
724
+ const m = labelRe.exec(unquote(l.text).trim().startsWith('|') ? l.text.replace(/\s*\|\s*$/, '') : l.text);
725
+ if (m && !/^\s*$/.test(m[1])) { fields++; items.push({ text: m[1], idx, where: `label (line ${idx + 1})` }); }
726
+ });
727
+
728
+ // heading sections classed nextAction
729
+ const byOwner = new Map();
730
+ lines.forEach((l, idx) => {
731
+ if (l.front || l.cls !== 'nextAction' || !l.owner || l.owner.cls !== 'nextAction') return;
732
+ if (l.heading) { if (!byOwner.has(l.owner)) byOwner.set(l.owner, []); return; }
733
+ if (!byOwner.has(l.owner)) byOwner.set(l.owner, []);
734
+ byOwner.get(l.owner).push({ l, idx });
735
+ });
736
+ for (const [owner, body] of byOwner) {
737
+ const sec = [];
738
+ let cur = null;
739
+ let fenceBuf = false;
740
+ const flush = () => { if (cur !== null && norm(cur)) sec.push(norm(cur)); cur = null; };
741
+ for (const { l, idx } of body) {
742
+ if (l.fence) { fenceBuf = !fenceBuf; continue; }
743
+ if (l.inFence) { if (norm(l.text)) cur = (cur ?? '') + ` \`${norm(l.text)}\``; continue; }
744
+ if (tableIdx.has(idx)) {
745
+ if (isSepRow(l.text) || headerIdx.has(idx) || colTableRows.has(idx)) continue;
746
+ sec.push(norm(splitRow(l.text).join(' ')));
747
+ continue;
748
+ }
749
+ const li = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/.exec(l.text);
750
+ if (li) { flush(); cur = li[1]; } else if (!norm(l.text)) { flush(); } else { cur = (cur === null ? '' : cur + ' ') + l.text.trim(); }
751
+ }
752
+ flush();
753
+ // a section whose only content is a table that has its own next-action column
754
+ // was already counted through that column; it is not an empty field
755
+ if (sec.length === 0 && body.some(({ idx }) => colTableRows.has(idx))) continue;
756
+ fields++;
757
+ if (sec.length === 0) items.push({ text: '', where: `section "${owner.heading}" (empty)` });
758
+ for (const s of sec) items.push({ text: s, where: `section "${owner.heading}"` });
759
+ }
760
+ return { fields, items, ragged };
761
+ }
762
+
763
+ /**
764
+ * OWT-019, and (464) its fourth outcome. Before a next action is judged, the row it belongs to is read by `checkWaiting`, the
765
+ * very function `uds open-work waiting` runs, with the same date. A row that is `asked-awaiting` and that OWT-020 and OWT-022
766
+ * raise nothing against is `waiting-on-reply`: its next step is the reply, which OWT-022 already described (when it was asked,
767
+ * what is waited for, what releases it), so OWT-019 is not applied. It is counted apart, never as named, never as complete, and
768
+ * listed with its age (`waitingOnReply`). A row `waiting` fails is judged exactly as before. A heading section has no row, so it
769
+ * is never waived; a carrier with no status field behaves exactly as it always did.
770
+ */
771
+ export function checkNextActions(carriers, opts = {}) {
772
+ const now = opts.now ?? todayUtc();
773
+ const staleAfter = opts.staleAfterDays ?? DEFAULT_STALE_AFTER_DAYS;
774
+ const res = { walked: 0, empty: 0, counts: { 'named-resolved': 0, 'named-unresolved': 0, unnamed: 0, 'waiting-on-reply': 0 }, unresolvedSplit: { 'path-missing': 0, 'not-resolvable': 0 }, violations: [], detail: [], noFieldCarriers: [], undecidable: [], waitingOnReply: [], staleAfter };
775
+ // No project is declared, so no other project is looked up: this call reads the carriers' own rows and nothing else.
776
+ const rows = checkWaiting(carriers, { now, root: opts.root, idPattern: opts.idPattern, extraCommands: opts.extraCommands, roleWords: opts.roleWords, projects: new Map() }).records;
777
+ for (const c of carriers) {
778
+ const { fields, items, ragged } = extractNextActions(c.content, opts.words);
779
+ for (const g of ragged) res.undecidable.push({ path: c.path, ...g });
780
+ if (fields === 0 && ragged.length === 0) { res.noFieldCarriers.push(c.path); continue; }
781
+ for (const it of items) {
782
+ const text = it.text.replace(/\*\*|__/g, '').trim();
783
+ if (EMPTY_FIELD.test(text)) { res.empty++; continue; }
784
+ res.walked++;
785
+ const reply = it.idx === undefined ? undefined : rows.find((w) => w.path === c.path && w.waitingOnReply && it.idx >= w.lineStart && it.idx <= w.lineEnd); // [mutation-anchor:next-action-join]
786
+ if (reply) { // [mutation-anchor:next-action-exempt]
787
+ res.counts['waiting-on-reply']++;
788
+ res.detail.push({ path: c.path, where: it.where, text, status: 'waiting-on-reply', kinds: [], resolution: 'n/a' });
789
+ res.waitingOnReply.push({ path: c.path, where: it.where, askedDay: reply.askedDay, age: reply.age, awaiting: reply.awaiting, release: reply.release, stale: reply.age !== null && reply.age > staleAfter }); // [mutation-anchor:stale-marked]
790
+ continue;
791
+ }
792
+ const r = classifyNextAction(text, opts);
793
+ res.counts[r.status]++;
794
+ if (r.unresolved) res.unresolvedSplit[r.unresolved]++;
795
+ res.detail.push({ path: c.path, where: it.where, text, ...r });
796
+ if (r.status === 'unnamed') res.violations.push({ rule: 'OWT-019', path: c.path, where: it.where, text });
797
+ }
798
+ }
799
+ return res;
800
+ }
801
+
802
+ // ── 461 R6: say what "resolved" resolved ─────────────────────────────────────
803
+ // `named-resolved`, `named-unresolved` and `unnamed` do not say against WHAT a path was looked up, and
804
+ // `named-unresolved` reads as a failure although it also holds every command, test name and requirement
805
+ // identifier, which are never looked up at all. These lines are ADDED after the counts line; nothing 1.1.0
806
+ // printed is changed or moved (the frozen capture is compared with these lines taken out).
807
+
808
+ /** Is this file inside a git working tree? Asked of git, never worked out from the path. */
809
+ function insideGitRepo(file) {
810
+ try {
811
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dirname(resolve(file)), stdio: ['ignore', 'pipe', 'ignore'] });
812
+ return true;
813
+ } catch { return false; }
814
+ }
815
+
816
+ /** The one sentence that says where a lookup starts and where that came from, for a path (next-action) and for a project (waiting) alike. */
817
+ export function lookupSentence(what, dir, source) {
818
+ return `${what} is looked up under ${resolve(dir)} (${source})`;
819
+ }
820
+
821
+ /**
822
+ * @param {{root:string, rootGiven:boolean, carriers:{path:string}[], split:{'path-missing':number,'not-resolvable':number}, unresolved:number, commands:string[]}} a
823
+ * @returns {string[]} lines, without the `[owt] ` prefix
824
+ */
825
+ export function explainResolution({ root, rootGiven, carriers, split, unresolved, commands = [] }) {
826
+ const out = [];
827
+ out.push(` of the named-unresolved (${unresolved}): path-missing=${split['path-missing']} not-resolvable=${split['not-resolvable']}`);
828
+ out.push(`RESOLUTION: ${lookupSentence('a path', root, rootGiven ? 'from --root' : 'the current directory: no --root was given')}. Only a PATH is looked up. A command, a test name or a requirement identifier is checked for being named and is never looked up, so it counts as not-resolvable, not as a missing path. path-missing is a path that was looked up and is not there.`); // [mutation-anchor:resolution-line]
829
+ if (!rootGiven) {
830
+ for (const c of carriers) {
831
+ if (!insideGitRepo(c.path)) { out.push(`RESOLUTION: ${c.path} is outside any git repository, so its paths are resolved against ${resolve(root)}, not against where the file is; pass --root to say where its paths start`); break; } // [mutation-anchor:outside-repo]
832
+ }
833
+ }
834
+ if (commands.length) out.push(`RESOLUTION: read as commands in addition to the built-in list: ${commands.join(', ')}`);
835
+ return out;
836
+ }
837
+
838
+ // ── 461 R3: when no carrier has a next-action field, say what each one showed ─
839
+ // Exit 2 ("cannot decide") says nothing about WHY. A reader cannot tell "this carrier writes the
840
+ // column in words the list does not hold" from "this carrier has no next-action field at all", and
841
+ // those two call for opposite actions (declare a word; or nothing). This reads the same structure the
842
+ // check read (headings and table headers) and says what it saw.
843
+
844
+ /** How many headings and table headers are listed per carrier before "and N more". About 20, on purpose. */
845
+ export const DIAGNOSTIC_LIST_LIMIT = 20;
846
+
847
+ /** The headings and table headers a carrier shows, each distinct text once with how many times it occurs. */
848
+ export function describeCarrier(md) {
849
+ const lines = parseDoc(md);
850
+ const count = (list) => {
851
+ const seen = new Map();
852
+ for (const t of list) { const k = norm(t); if (k) seen.set(k, (seen.get(k) || 0) + 1); }
853
+ return [...seen].map(([text, n]) => ({ text, n }));
854
+ };
855
+ const tables = findTables(lines);
856
+ return {
857
+ tables: tables.length,
858
+ headers: count(tables.flatMap((t) => t.header)),
859
+ headings: count(lines.filter((l) => l.heading).map((l) => l.heading.heading)),
860
+ };
861
+ }
862
+
863
+ /**
864
+ * The lines printed after "no next-action field found". Pure: carriers and declared words in, text out.
865
+ * `rowsUnreadable` lists the paths whose next-action column was found but whose rows could not be read.
866
+ * @returns {string[]}
867
+ */
868
+ export function explainNoNextActionField(carriers, words = [], rowsUnreadable = []) {
869
+ const out = [];
870
+ const quoted = (list) => list.map((x) => `"${x.text}"${x.n > 1 ? ` (x${x.n})` : ''}`).join(', ');
871
+ out.push('WHY: no carrier had a next-action field. What each one showed:');
872
+ for (const c of carriers) {
873
+ const d = describeCarrier(c.content);
874
+ const unreadable = rowsUnreadable.includes(c.path);
875
+ let verdict;
876
+ if (unreadable) verdict = 'has a next-action column, but its table rows could not be read (see UNDECIDABLE above)';
877
+ else if (d.tables > 0) verdict = `has ${d.tables} table(s), but no table header matches a recognised word; if one of them is your next-action column, declare its word`;
878
+ else if (d.headings.length > 0) verdict = 'has no table, and no heading matches a recognised word; if one of these headings is your next-action section, declare its word';
879
+ else verdict = 'has no table and no heading to read; this carrier may have no next-action field at all, and no word would change that';
880
+ out.push(` ${c.path}: ${verdict}`);
881
+ let budget = DIAGNOSTIC_LIST_LIMIT;
882
+ const show = (label, list) => {
883
+ if (!list.length) return;
884
+ const shown = list.slice(0, Math.max(budget, 0));
885
+ budget -= shown.length;
886
+ out.push(` ${label} (${list.length} distinct): ${quoted(shown)}${list.length > shown.length ? `, and ${list.length - shown.length} more` : ''}`); // [mutation-anchor:diagnostic-list]
887
+ };
888
+ show('table headers', d.headers);
889
+ show('headings', d.headings);
890
+ }
891
+ out.push(`WORDS RECOGNISED (a heading, a table header or an inline "word: ..." label that contains one of these, any case): built in: ${NEXT_ACTION_WORDS.map(([, shown]) => shown).join(' | ')}`);
892
+ out.push(words.length ? ` declared by you: ${words.join(' | ')}` : ' declared by you: none');
893
+ out.push('TO ADD A WORD: pass --next-action-word <word> (repeat it for several), or list it under open_work: next_action_words: in uds.project.yaml. It is plain text, not a pattern, and it is added to the same list for headings, table headers and labels.');
894
+ return out;
895
+ }
896
+
897
+ // ── OWT-020 … OWT-026: two states before a reply, and observed facts ─────────
898
+ // open-work-tracking 1.2.0 (dev-platform XSPEC-459). Everything here is UNCALIBRATED (OWT-016):
899
+ // the state words, the field names and the "derivable subject" list are initial judgments in
900
+ // English and Chinese. A carrier whose words differ is not read, which is reported (coverage
901
+ // unknown, OWT-011), never read as clean.
902
+
903
+ export const VOCAB_STATE = {
904
+ // header / label vocabulary: which structural field is which
905
+ roles: {
906
+ status: /\bstatus\b|\bstate\b|狀態/i,
907
+ askedAt: /asked[\s-]?(?:at|on|date)|(?:詢問|發問|送出|寄出|已問)(?:時間|日期)|問於/i,
908
+ awaiting: /\bwait(?:ing)?[\s-]?(?:for|on)\b|\bawaiting\b|\bblocked[\s-]?on\b|等什麼|等待(?:對象|什麼|內容)|等誰/i,
909
+ release: /\brelease\b|\bunblock|解除|放行/i,
910
+ draft: /\bdraft\b|\bto[\s-]?send\b|草稿|待送出|待問/i,
911
+ observedBy: /observed[\s-]?by|seen[\s-]?by|觀察者|誰看到|觀察人/i,
912
+ observedAt: /observed[\s-]?(?:at|on|date)|seen[\s-]?(?:at|on)|觀察(?:時間|日期)|何時看到/i,
913
+ value: /^(?:value|observed[\s-]?value|result|觀察值|觀察結果|值|結果)$/i,
914
+ subject: /^(?:fact|subject|observation|observed[\s-]?fact|事實|觀察項目|觀察對象|事項)$/i,
915
+ },
916
+ notYetAsked: /not[\s-]*(?:yet[\s-]*)?(?:asked|sent)|\bunasked\b|\bunsent\b|還沒問|尚未(?:詢問|送出|提問|發問|問)|未(?:詢問|送出|提問|問)|還沒送出|待問|待送出/i,
917
+ askedAwaiting: /\b(?:asked|sent)[\s,;&—–-]*(?:and[\s-]*)?(?:awaiting|waiting)\b|已(?:問|詢問|送出|寄出|發問)/i,
918
+ waiting: /\b(?:waiting|awaiting|blocked[\s-]*on|on[\s-]*hold|pending)\b|等待|等候|待回覆|待回應|卡在/i,
919
+ // The WHOLE cell must be a done word: "done except X" and "尚未完成" are not done.
920
+ done: /^[\s\p{P}\p{S}]*(?:done|completed?|closed|resolved|已完成|已結案|完成|結案|✅)[\s\p{P}\p{S}]*$/iu,
921
+ // The value domain of an observed fact. `unknown` is a real value, never a blank.
922
+ yes: /^(?:yes|y|true|是|有)$/i,
923
+ no: /^(?:no|n|false|否|沒有)$/i,
924
+ unknown: /^(?:unknown|\?|未知|不明|看不到|無法確認|unobserved)$/i,
925
+ // Subjects that version control, a spec marker or a CI result already determine (OWT-003 stands).
926
+ derivable: /\b(?:merged|pushed|committed|tagged)\b|\bci\b|\bcontinuous integration\b|\b(?:tests?|build)\s+(?:pass(?:ed|ing)?|green)\b|\bspec\s+(?:status|marker)\b|已合併|已推送|已提交|CI\s*(?:通過|綠|狀態)|測試通過|建置通過|規格(?:狀態|標記)/i,
927
+ };
928
+
929
+ /** Default age (days) past which an observation is reported as stale. An initial judgment, UNCALIBRATED (OWT-016). */
930
+ export const DEFAULT_STALE_AFTER_DAYS = 7;
931
+
932
+ const BLANK_FIELD = /^(?:|-+|—|–|n\/?a|none|tbd|\?+|無|待定|未知|unknown)$/i;
933
+ const stripMd = (s) => s.replace(/\*\*|__|`/g, '').trim();
934
+
935
+ /** A regex for words the adopter declared for one role, or null when there are none. Plain text, any case. */
936
+ const plainAlternation = (words) => words.map((w) => escapeRegExp(w)).join('|');
937
+ const declaredRoleRegExp = (words = []) => (words.length ? new RegExp(plainAlternation(words), 'i') : null);
938
+
939
+ /**
940
+ * The roles a header (or label) plays: the built-in vocabulary, plus the words the adopter declared for `askedAt` and
941
+ * `awaiting` (XSPEC-475 R3). `roleWords` is `{ askedAt: string[], awaiting: string[] }`.
942
+ */
943
+ const rolesOf = (header, roleWords = {}) => {
944
+ const roles = Object.entries(VOCAB_STATE.roles).filter(([, re]) => re.test(header)).map(([role]) => role);
945
+ for (const role of ['askedAt', 'awaiting']) {
946
+ if (!roles.includes(role) && declaredRoleRegExp(roleWords[role])?.test(header)) roles.push(role); // [mutation-anchor:declared-role-word]
947
+ }
948
+ return roles;
949
+ };
950
+
951
+ /** The words that are read as these roles out of the box, for a message that says what is accepted. */
952
+ const ACCEPTED_ROLE_WORDS = {
953
+ askedAt: 'asked-at, asked on, asked date, 詢問時間, 詢問日期, 發問時間, 發問日期, 送出時間, 送出日期, 寄出時間, 寄出日期, 已問時間, 已問日期, 問於',
954
+ awaiting: 'waiting for, waiting on, awaiting, blocked on, 等什麼, 等待對象, 等待什麼, 等待內容, 等誰',
955
+ release: 'release, unblock, 解除, 放行',
956
+ };
957
+
958
+ // inline labels in a list item: "status: not-yet-asked; draft: drafts/q.md"
959
+ const LABEL_WORDS = [
960
+ ['status', /(?:status|state|狀態)/],
961
+ ['askedAt', /(?:asked[\s-]?(?:at|on)|(?:詢問|發問|送出|寄出)(?:時間|日期))/],
962
+ ['awaiting', /(?:waiting[\s-]?(?:for|on)|awaiting|等什麼|等待對象|等誰)/],
963
+ ['release', /(?:release|unblock(?:ed)?[\s-]?(?:by|when)|解除條件|解除)/],
964
+ ['draft', /(?:draft|to[\s-]?send|草稿|待送出)/],
965
+ ['observedBy', /(?:observed[\s-]?by|seen[\s-]?by|觀察者)/],
966
+ ['observedAt', /(?:observed[\s-]?(?:at|on)|seen[\s-]?(?:at|on)|觀察時間|觀察日期)/],
967
+ ['value', /(?:observed[\s-]?value|value|觀察值|觀察結果)/],
968
+ ['subject', /(?:fact|subject|事實|觀察項目)/],
969
+ // 464: a boundary and nothing else. A "Next action: ..." label ends the value of the label before it (a blank `release:` must not read
970
+ // as filled by the next-action line below it) and is never itself a field of the record. Without it a row lacking its release was
971
+ // read as complete in a list, and OWT-022 passed a row it should have failed. It is the built-in list only: a word an adopter declares
972
+ // is not known to `waiting`, which reads these records for `next-action` too, so the two read a declared word's line the same way.
973
+ ['nextAction', VOCAB.nextAction],
974
+ ];
975
+
976
+ function parseRoleLabels(text, roleWords = {}) {
977
+ const hits = [];
978
+ const declaredLabels = ['askedAt', 'awaiting'].filter((role) => (roleWords[role] || []).length).map((role) => [role, { source: plainAlternation(roleWords[role]) }]);
979
+ for (const [role, word] of [...LABEL_WORDS, ...declaredLabels]) {
980
+ const re = new RegExp(`(?:^|[;;,,|((]\\s*|\\s)(${word.source})[\\w\\s-]{0,12}[::]`, 'gi');
981
+ let m;
982
+ while ((m = re.exec(text)) !== null) {
983
+ const start = m.index + m[0].indexOf(m[1]);
984
+ hits.push({ role, start, end: m.index + m[0].length });
985
+ }
986
+ }
987
+ hits.sort((a, b) => a.start - b.start);
988
+ const kept = [];
989
+ for (const h of hits) if (!kept.length || h.start >= kept[kept.length - 1].end) kept.push(h);
990
+ const f = {};
991
+ const fr = {}; // the same values with their Markdown kept: a `code span` is how a command or a test name is told from prose
992
+ kept.forEach((h, i) => {
993
+ if (h.role === 'nextAction') return; // a boundary, not a field (see LABEL_WORDS)
994
+ const next = kept[i + 1] ? kept[i + 1].start : text.length;
995
+ const val = stripMd(text.slice(h.end, next)).replace(/[;;,,|]+$/, '').trim();
996
+ if (f[h.role] === undefined) { f[h.role] = val; fr[h.role] = text.slice(h.end, next).replace(/[;;,,|]+$/, '').trim(); }
997
+ });
998
+ const firstField = kept.find((h) => h.role !== 'nextAction');
999
+ const title = stripMd(text.slice(0, firstField ? firstField.start : text.length)).replace(/[\s;;,,|—–::-]+$/, '').trim();
1000
+ return { f, fr, title };
1001
+ }
1002
+
1003
+ /**
1004
+ * The structural records a carrier holds for these checks: every row of a table that has a
1005
+ * recognised field column, and every top-level list item (with its indented lines) that carries
1006
+ * recognised labels. A table row whose cell count differs from its header is returned in
1007
+ * `ragged`, never read as empty (same rule as the next-action table).
1008
+ * @returns {{records:object[], ragged:object[]}}
1009
+ */
1010
+ export function extractRecords(md, roleWords = {}) {
1011
+ const lines = parseDoc(md);
1012
+ const records = [];
1013
+ const ragged = [];
1014
+ const inTable = new Set();
1015
+ for (const t of findTables(lines)) {
1016
+ inTable.add(t.headerIdx); inTable.add(t.headerIdx + 1);
1017
+ t.rows.forEach((r) => inTable.add(r.idx));
1018
+ const roles = t.header.map((h) => rolesOf(h, roleWords));
1019
+ const columns = new Set(roles.flat());
1020
+ if (!columns.size) continue;
1021
+ for (const r of t.rows) {
1022
+ const title = stripMd(r.cells[0] || '');
1023
+ const where = `table row (line ${r.idx + 1}, row "${clip(title, 40)}")`;
1024
+ if (r.cells.length !== t.header.length) { ragged.push({ idx: r.idx, where, cells: r.cells.length, expected: t.header.length, columns }); continue; }
1025
+ const f = {};
1026
+ const fr = {};
1027
+ roles.forEach((rs, n) => rs.forEach((role) => { if (f[role] === undefined) { f[role] = stripMd(r.cells[n]); fr[role] = r.cells[n]; } }));
1028
+ records.push({ where, title, f, fr, columns, headers: t.header.map(stripMd), lineStart: r.idx, lineEnd: r.idx });
1029
+ }
1030
+ }
1031
+ let cur = null;
1032
+ const flush = () => {
1033
+ if (cur) {
1034
+ const text = cur.parts.join(' ; ');
1035
+ const { f, fr, title } = parseRoleLabels(text, roleWords);
1036
+ if (Object.keys(f).length) {
1037
+ records.push({ where: `list item (line ${cur.idx + 1}, "${clip(title || stripMd(cur.parts[0]), 40)}")`, title: title || stripMd(cur.parts[0]), f, fr, columns: new Set(Object.keys(f)), headers: null, lineStart: cur.idx, lineEnd: cur.end });
1038
+ }
1039
+ }
1040
+ cur = null;
1041
+ };
1042
+ lines.forEach((l, idx) => {
1043
+ if (l.front || l.fence || l.inFence || l.heading || inTable.has(idx)) { flush(); return; }
1044
+ const li = /^(\s*)(?:[-*+]|\d+[.)])\s+(.*)$/.exec(l.text);
1045
+ if (li && li[1].length === 0) { flush(); cur = { idx, end: idx, parts: [li[2]] }; } else if (cur && /^\s+\S/.test(l.text)) { cur.parts.push(l.text.trim().replace(/^(?:[-*+]|\d+[.)])\s+/, '')); cur.end = idx; } else flush();
1046
+ });
1047
+ flush();
1048
+ return { records, ragged };
1049
+ }
1050
+
1051
+ const DATE_IN_TEXT = /(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})/;
1052
+
1053
+ /** A calendar day (UTC ms) from the first date in the text, or null. The year is required; the time of day is ignored. */
1054
+ export function parseDay(text) {
1055
+ const m = DATE_IN_TEXT.exec(text || '');
1056
+ if (!m) return null;
1057
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
1058
+ const t = Date.UTC(y, mo - 1, d);
1059
+ const back = new Date(t);
1060
+ if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d) return null;
1061
+ return t;
1062
+ }
1063
+
1064
+ const DAY_MS = 86400000;
1065
+ const dayString = (t) => new Date(t).toISOString().slice(0, 10);
1066
+ export const todayUtc = () => { const n = new Date(); return Date.UTC(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate()); };
1067
+
1068
+ /** The structural state of a record's status field. */
1069
+ export function classifyState(statusText) {
1070
+ const t = stripMd(statusText || '');
1071
+ if (VOCAB_STATE.done.test(t)) return 'done';
1072
+ if (VOCAB_STATE.notYetAsked.test(t)) return 'not-yet-asked';
1073
+ if (VOCAB_STATE.askedAwaiting.test(t)) return 'asked-awaiting';
1074
+ if (VOCAB_STATE.waiting.test(t)) return 'waiting-unspecified';
1075
+ return 'other';
1076
+ }
1077
+
1078
+ /** `{value:'yes'|'no'|'unknown'}` or `{value:null}` for anything outside the domain, including blank. */
1079
+ export function classifyValue(text) {
1080
+ const t = stripMd(text || '').replace(/[.。]+$/, '');
1081
+ if (VOCAB_STATE.yes.test(t)) return 'yes';
1082
+ if (VOCAB_STATE.no.test(t)) return 'no';
1083
+ if (VOCAB_STATE.unknown.test(t)) return 'unknown';
1084
+ return null;
1085
+ }
1086
+
1087
+ const ageDays = (now, day) => Math.floor((now - day) / DAY_MS);
1088
+
1089
+ // ── OWT-027 / OWT-028: a release condition that names an object in another project ──
1090
+ // open-work-tracking 1.3.0 (dev-platform XSPEC-460). Local only: it reads files and git tags on THIS
1091
+ // machine and opens no network connection. The names, the machine-specific path prefixes and the
1092
+ // kinds it can resolve are an initial judgment (OWT-016).
1093
+ //
1094
+ // A project is named by a LOGICAL name (`uds`, `vibeops`), never by a directory: a directory is
1095
+ // machine-specific (it leaks a user name and is wrong on the next machine), and two readers of one
1096
+ // carrier must mean the same project by one name. Where a name lives on this machine is supplied
1097
+ // outside the carrier (`--root NAME=DIR`, or `open_work.projects` in uds.project.yaml).
1098
+
1099
+ export const PROJECT_NAME = /^[a-z][a-z0-9_-]{1,31}$/;
1100
+ const URL_SCHEMES = new Set(['http', 'https', 'ftp', 'file', 'ssh', 'git', 'mailto', 'tel', 'data', 'javascript', 'ws', 'wss']);
1101
+ // <name>:<object>. The name is lower-case and at least two characters (so `C:\` is never a project); the
1102
+ // object is one token, or a `code span` for a command or a test name. Not inside a word, a path or a URL.
1103
+ const REF_RE = /(?<![\w./@:\\-])([a-z][a-z0-9_-]{1,31}):(?!\/\/)(`[^`\n]+`|[^\s`|;,,;、()()[\]{}<>"']+)/g;
1104
+ // A machine-specific absolute path: a home or volume prefix, a drive letter, `~/`, a UNC share, a file: URL.
1105
+ const MACHINE_PATH = /(?:^|[\s"'`(=:])(?:\/(?:Users|home|root|Volumes|mnt|private|var|opt|srv|tmp|etc)\/|[A-Za-z]:[\\/]|~[\\/]|\\\\[\w.$-]+\\)|file:\/\//i;
1106
+ const TAG_NAME = /^[A-Za-z0-9][\w.+-]*$/;
1107
+
1108
+ const isAbsoluteObject = (o) => /^(?:\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(o);
1109
+ const leavesProject = (o) => /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(o);
1110
+
1111
+ /** @returns {{kind:'path'|'tag'|'id'|'command'|'test'|'object'|'absolute'|'outside', value:string}} */
1112
+ export function classifyObject(raw, idPattern = DEFAULT_ID_PATTERN, extraCommands = []) {
1113
+ const code = raw.startsWith('`');
1114
+ let obj = code ? raw.slice(1, -1).trim() : raw.replace(/[.:!?]+$/, '');
1115
+ if (!obj) return { kind: 'object', value: raw };
1116
+ if (isAbsoluteObject(obj)) return { kind: 'absolute', value: obj };
1117
+ if (leavesProject(obj)) return { kind: 'outside', value: obj };
1118
+ const idFull = new RegExp(`^(?:${idPattern})$`);
1119
+ const idOk = (v) => idFull.test(v) && !ID_PREFIX_DENYLIST.includes(v.split('-')[0]);
1120
+ if (code) {
1121
+ const first = obj.split(/\s+/)[0].replace(/^\$\s*/, '');
1122
+ if (pathLike(obj, true)) return { kind: 'path', value: obj };
1123
+ if (COMMANDS.includes(first) || extraCommands.includes(first)) return { kind: 'command', value: obj };
1124
+ if (/\.(?:test|spec)\.[cm]?[jt]sx?|(?:^|[\s/])test_\w+|::/.test(obj)) return { kind: 'test', value: obj };
1125
+ if (idOk(obj)) return { kind: 'id', value: obj };
1126
+ return { kind: 'object', value: obj };
1127
+ }
1128
+ if (pathLike(obj, true)) return { kind: 'path', value: obj };
1129
+ if (idOk(obj)) return { kind: 'id', value: obj };
1130
+ if (TAG_NAME.test(obj)) return { kind: 'tag', value: obj };
1131
+ return { kind: 'object', value: obj };
1132
+ }
1133
+
1134
+ /** Every `<project>:<object>` in a piece of text. */
1135
+ export function findReferences(text, idPattern, extraCommands = []) {
1136
+ const refs = [];
1137
+ REF_RE.lastIndex = 0;
1138
+ let m;
1139
+ while ((m = REF_RE.exec(text || '')) !== null) {
1140
+ if (URL_SCHEMES.has(m[1])) continue;
1141
+ const obj = classifyObject(m[2], idPattern, extraCommands);
1142
+ if (!refs.some((r) => r.name === m[1] && r.value === obj.value)) refs.push({ name: m[1], ...obj });
1143
+ }
1144
+ return refs;
1145
+ }
1146
+
1147
+ /**
1148
+ * `--root` values for `waiting`. A value that looks like NAME=DIR (a name, then `=`, with no path separator
1149
+ * before the `=`) says where project NAME lives; any other value is the single directory relative paths are
1150
+ * resolved against, exactly as before. Directories are resolved against the current directory.
1151
+ * @returns {{plain:string|undefined, named:Map<string,string>, error:string|null}}
1152
+ */
1153
+ export function parseRootOptions(values) {
1154
+ const named = new Map();
1155
+ let plain;
1156
+ for (const v of values) {
1157
+ if (typeof v !== 'string' || v === '') return { plain: undefined, named, error: '--root needs a directory, or NAME=DIR' };
1158
+ const m = /^([^\s/\\=]+)=(.*)$/s.exec(v);
1159
+ if (!m) {
1160
+ if (plain !== undefined) return { plain: undefined, named, error: `--root DIR was given more than once ("${plain}" and "${v}"); give one directory, and NAME=DIR for each other project` };
1161
+ plain = v;
1162
+ continue;
1163
+ }
1164
+ if (!PROJECT_NAME.test(m[1])) return { plain: undefined, named, error: `--root ${v}: the project name "${m[1]}" is not a logical name (lower-case letters, digits, "-" and "_", starting with a letter, 2 to 32 characters)` };
1165
+ if (m[2].trim() === '') return { plain: undefined, named, error: `--root ${m[1]}=: the directory is empty` };
1166
+ const dir = resolve(m[2]);
1167
+ if (named.has(m[1]) && named.get(m[1]) !== dir) return { plain: undefined, named, error: `--root names project "${m[1]}" twice with different directories` };
1168
+ named.set(m[1], dir);
1169
+ }
1170
+ return { plain, named, error: null };
1171
+ }
1172
+
1173
+ /** What can be observed on this machine. Injected in the self-test, so a rule never reads the disk by itself. */
1174
+ export const REAL_ENV = {
1175
+ dirExists: (d) => { try { return statSync(d).isDirectory(); } catch { return false; } },
1176
+ pathExists: (p) => existsSync(p),
1177
+ // 'present' | 'absent' | 'unreadable' (not a git repository, git missing, or git failed): never a guess
1178
+ tagState: (dir, tag) => {
1179
+ const env = { ...process.env };
1180
+ for (const k of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_PREFIX', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES']) delete env[k];
1181
+ const r = spawnSync('git', ['-C', dir, 'show-ref', '--verify', '--quiet', `refs/tags/${tag}`], { stdio: 'ignore', env });
1182
+ if (r.error || r.status === null) return 'unreadable';
1183
+ if (r.status === 0) return 'present';
1184
+ if (r.status === 1) return 'absent';
1185
+ return 'unreadable';
1186
+ },
1187
+ };
1188
+
1189
+ const OBSERVABLE = { path: 'machine-observable', tag: 'machine-observable' };
1190
+
1191
+ /**
1192
+ * OWT-028: where does the other project stand? Four answers, never folded into one:
1193
+ * released the object exists there now (a path on disk, a version-control tag)
1194
+ * not-yet-released the project is visible and the object is not there
1195
+ * not-visible this machine cannot see the project, so nothing is known — NOT released, NOT zero
1196
+ * needs-a-person the project is visible but this kind of object (a test name, a command, a spec or
1197
+ * requirement identifier) has nothing here that can be read; a person confirms it
1198
+ * @param {Map<string,string>} projects logical name -> directory on this machine
1199
+ */
1200
+ export function resolveReference(ref, projects, env = REAL_ENV) {
1201
+ const dir = projects.get(ref.name);
1202
+ if (dir === undefined) return { status: 'not-visible', why: `no directory on this machine is declared for project "${ref.name}" (--root ${ref.name}=DIR)` }; // [mutation-anchor:not-visible]
1203
+ if (!env.dirExists(dir)) return { status: 'not-visible', why: `the directory declared for project "${ref.name}" does not exist on this machine` };
1204
+ if (ref.kind === 'path') return env.pathExists(join(dir, ref.value.replace(/^\.\//, ''))) ? { status: 'released', why: 'the path exists there' } : { status: 'not-yet-released', why: 'the path does not exist there'}; // [mutation-anchor:path-exists]
1205
+ if (ref.kind === 'tag') {
1206
+ const t = env.tagState(dir, ref.value);
1207
+ if (t === 'unreadable') return { status: 'not-visible', why: `the tags of project "${ref.name}" cannot be read here (not a git repository, or git failed)` };
1208
+ return t === 'present' ? { status: 'released', why: 'the tag exists there' } : { status: 'not-yet-released', why: 'the tag does not exist there' }; // [mutation-anchor:tag-present]
1209
+ }
1210
+ return { status: 'needs-a-person', why: `a ${ref.kind === 'id' ? 'requirement or specification identifier' : ref.kind === 'object' ? 'free-form object' : ref.kind} in another project has nothing this check can read` }; // [mutation-anchor:needs-a-person]
1211
+ }
1212
+
1213
+ /** The option and uds.project.yaml key that declare a word for each role (XSPEC-475 R3). `release` has none: it is not declarable. */
1214
+ const ROLE_DECLARE = {
1215
+ askedAt: { label: 'asked-at', flag: '--asked-at-word', key: 'open_work.asked_at_words' },
1216
+ awaiting: { label: 'what it waits for', flag: '--waiting-for-word', key: 'open_work.waiting_for_words' },
1217
+ release: { label: 'release', flag: null, key: null },
1218
+ };
1219
+
1220
+ /**
1221
+ * Appended to a violation when the record has NO field read as `role` at all (as opposed to a field that is empty or wrong):
1222
+ * says what was looked for, what the record showed, and how to declare the project's own word. XSPEC-475 R3.
1223
+ */
1224
+ function fieldNotFound(record, role, roleWords = {}) {
1225
+ const d = ROLE_DECLARE[role];
1226
+ const seen = record.headers ? `headers seen: ${record.headers.map((h) => `"${clip(h, 30)}"`).join(', ')}` : `labels seen: ${[...record.columns].join(', ')}`;
1227
+ const declared = (roleWords[role] || []).length ? `; declared by you: ${roleWords[role].join(', ')}` : '';
1228
+ const how = d.flag ? ` To declare your own word: ${d.flag} <word>, or ${d.key} in uds.project.yaml.` : '';
1229
+ return `. No column or label of this record is read as ${d.label} (${seen}). Accepted: ${ACCEPTED_ROLE_WORDS[role]}${declared}.${how}`;
1230
+ }
1231
+
1232
+ /**
1233
+ * OWT-020 / OWT-021 / OWT-022. Reads every record that has a status field (OWT-010: a structural
1234
+ * field, never prose). `now` is a UTC day (ms); inject it, never read the clock inside a rule.
1235
+ */
1236
+ export function checkWaiting(carriers, opts = {}) {
1237
+ const now = opts.now ?? todayUtc();
1238
+ const projects = opts.projects ?? new Map();
1239
+ const env = opts.env ?? REAL_ENV;
1240
+ const res = {
1241
+ walked: 0, counts: { 'not-yet-asked': 0, 'asked-awaiting': 0, 'waiting-unspecified': 0, 'waiting-cross-project': 0, done: 0, other: 0 },
1242
+ cross: { found: 0, counts: { released: 0, 'not-yet-released': 0, 'not-visible': 0, 'needs-a-person': 0 }, items: [] },
1243
+ violations: [], detail: [], ragged: [], noStateCarriers: [],
1244
+ // 464: one entry per record read, with the lines it covers and whether it is `waiting-on-reply`. `next-action` reads THIS
1245
+ // list to decide which rows OWT-019 does not apply to, so the two commands cannot disagree about a row (R2 by construction).
1246
+ records: [],
1247
+ };
1248
+ const roleWords = opts.roleWords ?? {}; // XSPEC-475 R3: the asked-at / waiting-for words the project declared
1249
+ for (const c of carriers) {
1250
+ const { records, ragged } = extractRecords(c.content, roleWords);
1251
+ for (const g of ragged) if (g.columns.has('status')) res.ragged.push({ path: c.path, ...g });
1252
+ const withStatus = records.filter((r) => r.f.status !== undefined);
1253
+ if (!withStatus.length) { res.noStateCarriers.push(c.path); continue; }
1254
+ for (const r of withStatus) {
1255
+ res.walked++;
1256
+ let state = classifyState(r.f.status);
1257
+ const at = { path: c.path, where: r.where };
1258
+ const raised = [];
1259
+ const bad = (rule, why) => { raised.push(rule); res.violations.push({ rule, ...at, why }); };
1260
+ const note = [];
1261
+ let askedDay = null;
1262
+ // OWT-027 / OWT-028: a release condition (or what it waits for) that names an object in another project
1263
+ const waitingNow = state === 'not-yet-asked' || state === 'asked-awaiting' || state === 'waiting-unspecified';
1264
+ const conditionText = [r.fr.release, r.fr.awaiting].filter((x) => x !== undefined && x !== '').join(' ; ');
1265
+ const refs = waitingNow ? findReferences(conditionText, opts.idPattern, opts.extraCommands) : [];
1266
+ if (waitingNow && (MACHINE_PATH.test(conditionText) || refs.some((x) => x.kind === 'absolute'))) { // [mutation-anchor:machine-path]
1267
+ bad('OWT-027', `names a machine-specific absolute path in what it waits for or its release ("${clip(conditionText, 60)}"): name the other project by its logical name, <name>:<path inside it>, and keep the directory out of the carrier`);
1268
+ }
1269
+ for (const x of refs) {
1270
+ if (x.kind === 'outside') { bad('OWT-027', `names "${x.name}:${x.value}", a path that leaves project "${x.name}"; give a path inside it`); continue; }
1271
+ if (x.kind === 'absolute') continue; // already a violation above
1272
+ const got = resolveReference(x, projects, env);
1273
+ res.cross.found++;
1274
+ res.cross.counts[got.status]++;
1275
+ res.cross.items.push({ ...at, name: x.name, object: x.value, kind: x.kind, observable: OBSERVABLE[x.kind] ?? 'needs a person', ...got });
1276
+ }
1277
+ // An item that waits for an observable event in another project has no request to have "asked":
1278
+ // OWT-020's two states are about a reply, and this is not one. It is counted on its own line.
1279
+ if (state === 'waiting-unspecified' && refs.some((x) => x.kind !== 'absolute' && x.kind !== 'outside')) state = 'waiting-cross-project'; // [mutation-anchor:cross-project-exempt]
1280
+ res.counts[state]++;
1281
+ const unspecified = state === 'waiting-unspecified'; // [mutation-anchor:waiting-unspecified]
1282
+ if (unspecified) bad('OWT-020', 'is waiting but does not say whether it has been asked (neither not-yet-asked nor asked-awaiting)');
1283
+ if (state === 'not-yet-asked') {
1284
+ const named = classifyNextAction(`${r.f.draft ?? ''} ${r.f.status}`, { root: opts.root, idPattern: opts.idPattern, extraCommands: opts.extraCommands }).status !== 'unnamed'; // [mutation-anchor:not-yet-asked-names]
1285
+ if (!named) bad('OWT-021', 'is not-yet-asked but names no draft or action: no file path, command, test name or requirement identifier');
1286
+ }
1287
+ if (state === 'asked-awaiting') {
1288
+ const day = parseDay(r.f.askedAt);
1289
+ // XSPEC-475 R3: three different faults, three different messages. A field that was not FOUND is a vocabulary problem (the
1290
+ // project may call the column something else, and can declare it); a field that is blank or not a date is a value problem.
1291
+ if (day === null) bad('OWT-022', r.f.askedAt === undefined ? `is asked-awaiting but has no asked-at${fieldNotFound(r, 'askedAt', roleWords)}` : BLANK_FIELD.test(r.f.askedAt) ? 'is asked-awaiting but has no asked-at' : `has an asked-at that is not a date with a year: "${clip(r.f.askedAt, 40)}"`); // [mutation-anchor:asked-at-required]
1292
+ else if (day > now) bad('OWT-022', `has an asked-at (${dayString(day)}) later than today (${dayString(now)})`);
1293
+ else { note.push(`asked ${ageDays(now, day)}d ago`); askedDay = day; }
1294
+ const hasWhat = r.f.awaiting !== undefined && !BLANK_FIELD.test(r.f.awaiting);
1295
+ const hasRelease = r.f.release !== undefined && !BLANK_FIELD.test(r.f.release);
1296
+ const notFound = (!hasWhat && r.f.awaiting === undefined ? fieldNotFound(r, 'awaiting', roleWords) : '') + (!hasRelease && r.f.release === undefined ? fieldNotFound(r, 'release', roleWords) : '');
1297
+ if (!(hasWhat && hasRelease)) bad('OWT-022', `is asked-awaiting but does not state ${!hasWhat && !hasRelease ? 'what it waits for and what event releases it' : !hasWhat ? 'what it waits for' : 'what event releases it'} (OWT-002)${notFound}`); // [mutation-anchor:asked-release-required]
1298
+ }
1299
+ res.detail.push({ ...at, state, text: r.title, note: note.join(', ') });
1300
+ // 464 R1: `asked-awaiting` and nothing OWT-020 or OWT-022 objects to. Both rules are read from what THIS function just raised
1301
+ // for this record, never recomputed, so a row `waiting` fails is never one `next-action` waives.
1302
+ const waitingOnReply = state === 'asked-awaiting' && !raised.some((rule) => rule === 'OWT-020' || rule === 'OWT-022'); // [mutation-anchor:waiting-on-reply]
1303
+ res.records.push({ ...at, state, waitingOnReply, lineStart: r.lineStart, lineEnd: r.lineEnd, askedDay, age: askedDay === null ? null : ageDays(now, askedDay), awaiting: r.f.awaiting ?? '', release: r.f.release ?? '' });
1304
+ }
1305
+ }
1306
+ return res;
1307
+ }
1308
+
1309
+ /**
1310
+ * OWT-023 / OWT-024 / OWT-025 / OWT-026. Reads every record of a table or list item that carries an
1311
+ * observed-by or observed-at field. It decides that the fields exist, are well formed, and how old
1312
+ * the stamp is. It cannot decide that the observation is true, or that it still is (OWT-014).
1313
+ */
1314
+ export function checkObservations(carriers, opts = {}) {
1315
+ const now = opts.now ?? todayUtc();
1316
+ const staleAfter = opts.staleAfterDays ?? DEFAULT_STALE_AFTER_DAYS;
1317
+ const res = {
1318
+ walked: 0, now, staleAfter, counts: { yes: 0, no: 0, unknown: 0, invalid: 0 }, stale: [], unknown: [], confirmed: 0,
1319
+ violations: [], detail: [], ragged: [], noObservationCarriers: [],
1320
+ };
1321
+ for (const c of carriers) {
1322
+ const { records, ragged } = extractRecords(c.content);
1323
+ for (const g of ragged) if (g.columns.has('observedBy') || g.columns.has('observedAt')) res.ragged.push({ path: c.path, ...g });
1324
+ const obs = records.filter((r) => r.columns.has('observedBy') || r.columns.has('observedAt'));
1325
+ if (!obs.length) { res.noObservationCarriers.push(c.path); continue; }
1326
+ for (const r of obs) {
1327
+ res.walked++;
1328
+ const at = { path: c.path, where: r.where };
1329
+ const bad = (rule, why) => res.violations.push({ rule, ...at, why });
1330
+ let wellFormed = true;
1331
+ const fail = (rule, why) => { wellFormed = false; bad(rule, why); };
1332
+ const by = r.f.observedBy;
1333
+ if (by === undefined || BLANK_FIELD.test(by)) fail('OWT-023', 'has no observed-by: who or what saw this is not recorded'); // [mutation-anchor:observed-by-required]
1334
+ const day = parseDay(r.f.observedAt);
1335
+ let age = null;
1336
+ if (day === null) fail('OWT-023', r.f.observedAt === undefined || BLANK_FIELD.test(r.f.observedAt) ? 'has no observed-at: when it was seen is not recorded' : `has an observed-at that is not a date with a year: "${clip(r.f.observedAt, 40)}"`); // [mutation-anchor:observed-at-required]
1337
+ else if (day > now) fail('OWT-023', `has an observed-at (${dayString(day)}) later than today (${dayString(now)})`);
1338
+ else age = ageDays(now, day);
1339
+ const value = classifyValue(r.f.value);
1340
+ if (value === null) fail('OWT-023', `has no value of yes, no or unknown${r.f.value ? ` (found "${clip(r.f.value, 30)}")` : ''}`); // [mutation-anchor:value-domain]
1341
+ const subject = r.f.subject ?? r.title;
1342
+ if (VOCAB_STATE.derivable.test(subject)) fail('OWT-026', `is a hand-written observation of "${clip(subject, 50)}", which version control, a spec marker or a CI result determines (OWT-003 stands)`); // [mutation-anchor:derivable]
1343
+ if (value === null) res.counts.invalid++; else res.counts[value]++;
1344
+ const isStale = age !== null && age > staleAfter; // [mutation-anchor:stale]
1345
+ const claimsDone = r.f.status !== undefined && classifyState(r.f.status) === 'done';
1346
+ if (value === 'unknown') {
1347
+ res.unknown.push({ ...at, text: r.title });
1348
+ if (claimsDone) bad('OWT-024', 'is marked done while its observation is unknown: unknown never counts as complete'); // [mutation-anchor:unknown-not-done]
1349
+ }
1350
+ if (isStale) res.stale.push({ ...at, text: r.title, age, claimsDone });
1351
+ const confirmed = wellFormed && value === 'yes' && !isStale; // [mutation-anchor:confirmed]
1352
+ if (confirmed) res.confirmed++;
1353
+ res.detail.push({ ...at, text: r.title, value: value ?? '?', age, by: by ?? '', observedAt: r.f.observedAt ?? '' });
1354
+ }
1355
+ }
1356
+ return res;
1357
+ }
1358
+
1359
+ // ── Self-test arms (the main path runs these first; a broken checker is exit 2) ─
1360
+
1361
+ /** The shape every caller has always had: `{ ok, failures }`. `selfTestArms` is the same run with the names of the arms that were evaluated. */
1362
+ export function runSelfTest() {
1363
+ const { ok, failures } = selfTestArms();
1364
+ return { ok, failures };
1365
+ }
1366
+
1367
+ export function selfTestArms() {
1368
+ const failures = [];
1369
+ const ran = []; // every arm that was evaluated, passed or not, so a test can tell "passed" from "never ran"
1370
+ const expect = (name, cond) => { ran.push(name); if (!cond) failures.push(name); };
1371
+
1372
+ // OWT-019
1373
+ expect('D2 violating: verb-only is unnamed', classifyNextAction('Continue implementation', {}).status === 'unnamed');
1374
+ expect('D2 violating: vague sentence is unnamed', classifyNextAction('handle the rest of the items and clean up', {}).status === 'unnamed');
1375
+ expect('D2 clean: path', classifyNextAction('edit scripts/foo.mjs', {}).status !== 'unnamed');
1376
+ expect('D2 clean: command', classifyNextAction('run `npm test` again', {}).status !== 'unnamed');
1377
+ expect('D2 clean: identifier', classifyNextAction('finish XSPEC-436 R1', {}).status !== 'unnamed');
1378
+ expect('D2 clean: test name', classifyNextAction('make the test "a next action that names nothing is reported" pass', {}).status !== 'unnamed');
1379
+
1380
+ // OWT-019, table columns: the header decides which column is read, never the position
1381
+ const tbl = extractNextActions('| item | state | Next action |\n|---|---|---|\n| a | open | keep going |\n');
1382
+ expect('D2 clean: only the header-named column is a next-action field', tbl.fields === 1 && tbl.items[0].text === 'keep going');
1383
+ expect('D2 clean: a table without such a header has no next-action field', extractNextActions('| item | state |\n|---|---|\n| a | open |\n').fields === 0);
1384
+
1385
+ // OWT-018
1386
+ const spec = (ac, rev) => `# S\n\n## Acceptance criteria\n\n${ac}\n\n## Revisions\n\n${rev}\n`;
1387
+ const table = (rows) => `| Change | Approver | Reason |\n|---|---|---|\n${rows}`;
1388
+ const r0 = checkIntentRevision({ before: spec('- A', table('')), after: spec('- A\n- B', table('')) });
1389
+ expect('D1 violating: changed, no record -> violation', r0.violations.length === 1 && r0.handBack.length === 1);
1390
+ const r1 = checkIntentRevision({ before: spec('- A', table('')), after: spec('- A\n- B', table('| added B | | scope grew |\n')) });
1391
+ expect('D1 violating: record without approver -> hand-back only', r1.violations.length === 0 && r1.handBack.length === 1);
1392
+ const r2 = checkIntentRevision({ before: spec('- A', table('')), after: spec('- A\n- B', table('| added B | albert | scope grew |\n')) });
1393
+ expect('D1 clean: recorded and approved', r2.violations.length === 0 && r2.handBack.length === 0 && r2.status === 'changed-recorded');
1394
+ const r3 = checkIntentRevision({ before: spec('- A', table('')), after: spec('- A', table('')) });
1395
+ expect('D1 clean: unchanged', r3.status === 'unchanged');
1396
+
1397
+ // OWT-017
1398
+ const both = checkSeparation([{ path: 'x.md', content: '# X\n## Acceptance criteria\n- a\n## Next action\n- b\n' }]);
1399
+ expect('D1 violating: one carrier holds both', both.violations.length === 1);
1400
+ const apart = checkSeparation([
1401
+ { path: 'spec.md', content: '# X\n## Acceptance criteria\n- a\n' },
1402
+ { path: 'log.md', content: '# L\n## Next action\n- b\n' },
1403
+ ]);
1404
+ expect('D1 clean: carriers apart', apart.violations.length === 0 && apart.recognised === 2);
1405
+
1406
+ // OWT-020 … OWT-026 (1.2.0): every check has a sample built to violate it and one built to satisfy it.
1407
+ const NOW = Date.UTC(2026, 9, 7);
1408
+ const wtab = (rows) => `| item | status | draft | asked-at | waiting for | release |\n|---|---|---|---|---|---|\n${rows}`;
1409
+ const waiting = (rows) => checkWaiting([{ path: 'w.md', content: wtab(rows) }], { now: NOW });
1410
+ const ruleOf = (res, rule) => res.violations.filter((v) => v.rule === rule).length;
1411
+ const w0 = waiting('| ask legal | waiting | | | | |\n');
1412
+ expect('OWT-020 violating: a waiting item that does not say whether it was asked', ruleOf(w0, 'OWT-020') === 1 && w0.counts['waiting-unspecified'] === 1);
1413
+ const w1 = waiting('| ask legal | not-yet-asked | drafts/legal.md | | | |\n| ask vendor | 已問、等回覆 | | 2026-10-01 | the quote | the reply arrives |\n');
1414
+ expect('OWT-020 clean: both named states, in English and in Chinese', w1.violations.length === 0 && w1.counts['not-yet-asked'] === 1 && w1.counts['asked-awaiting'] === 1);
1415
+ expect('OWT-021 violating: not-yet-asked names no draft or action', ruleOf(waiting('| ask legal | not-yet-asked | an email | | | |\n'), 'OWT-021') === 1);
1416
+ expect('OWT-021 clean: not-yet-asked names a path', ruleOf(waiting('| ask legal | not-yet-asked | `drafts/legal.md` | | | |\n'), 'OWT-021') === 0);
1417
+ expect('OWT-022 violating: asked-awaiting has no asked-at', ruleOf(waiting('| q | asked-awaiting | | | the quote | the reply arrives |\n'), 'OWT-022') === 1);
1418
+ expect('OWT-022 violating: asked-awaiting does not say what releases it (OWT-002)', ruleOf(waiting('| q | asked-awaiting | | 2026-10-01 | the quote | |\n'), 'OWT-022') === 1);
1419
+ expect('OWT-022 clean: asked-awaiting with asked-at, what it waits for and its release', ruleOf(waiting('| q | asked-awaiting | | 2026-10-01 | the quote | the reply arrives |\n'), 'OWT-022') === 0);
1420
+ expect('OWT-020 clean: a done item is not waiting', waiting('| q | done | | | | |\n').violations.length === 0);
1421
+ // XSPEC-475 R3: the words the not-found message lists as accepted are the words the vocabulary reads (one list said twice would drift), and a declared header is read.
1422
+ expect('XSPEC-475 R3 clean: every word the not-found message lists as accepted is read by the vocabulary', Object.entries(ACCEPTED_ROLE_WORDS).every(([role, list]) => list.split(', ').every((w) => VOCAB_STATE.roles[role].test(w))));
1423
+ const declaredTab = '| item | status | 何時問 | 問什麼 | release |\n|---|---|---|---|---|\n| q | asked-awaiting | 2026-10-01 | the quote | the reply arrives |\n';
1424
+ expect('XSPEC-475 R3 violating: a header the vocabulary does not hold is not read as asked-at until it is declared', ruleOf(checkWaiting([{ path: 'd.md', content: declaredTab }], { now: NOW }), 'OWT-022') >= 1);
1425
+ expect('XSPEC-475 R3 clean: the same header, declared, is read as asked-at and as what it waits for', ruleOf(checkWaiting([{ path: 'd.md', content: declaredTab }], { now: NOW, roleWords: { askedAt: ['何時問'], awaiting: ['問什麼'] } }), 'OWT-022') === 0);
1426
+
1427
+ const otab = (rows) => `| fact | status | observed-by | observed-at | value |\n|---|---|---|---|---|\n${rows}`;
1428
+ const obs = (rows, o = {}) => checkObservations([{ path: 'o.md', content: otab(rows) }], { now: NOW, ...o });
1429
+ expect('OWT-023 violating: an observation with no observed-by', ruleOf(obs('| mail sent | open | | 2026-10-05 | yes |\n'), 'OWT-023') === 1);
1430
+ expect('OWT-023 violating: an observation with no observed-at', ruleOf(obs('| mail sent | open | albert | | yes |\n'), 'OWT-023') === 1);
1431
+ expect('OWT-023 violating: a value outside yes, no, unknown', ruleOf(obs('| mail sent | open | albert | 2026-10-05 | maybe |\n'), 'OWT-023') === 1);
1432
+ const o1 = obs('| mail sent | open | albert | 2026-10-05 | yes |\n');
1433
+ expect('OWT-023 clean: observed-by, observed-at and a value; its age is computed', o1.violations.length === 0 && o1.detail[0].age === 2 && o1.confirmed === 1);
1434
+ const o2 = obs('| approved | done | albert | 2026-10-05 | unknown |\n');
1435
+ expect('OWT-024 violating: unknown marked done', ruleOf(o2, 'OWT-024') === 1);
1436
+ expect('OWT-024 violating: unknown is counted apart and never confirmed', o2.counts.unknown === 1 && o2.unknown.length === 1 && o2.confirmed === 0);
1437
+ expect('OWT-024 clean: unknown not marked done is listed, not a violation', ruleOf(obs('| approved | open | albert | 2026-10-05 | unknown |\n'), 'OWT-024') === 0);
1438
+ const o3 = obs('| mail sent | open | albert | 2026-09-01 | yes |\n');
1439
+ expect('OWT-025 violating: an observation older than the threshold is stale and not confirmed', o3.stale.length === 1 && o3.confirmed === 0);
1440
+ expect('OWT-025 clean: a fresh observation is not stale', o1.stale.length === 0);
1441
+ expect('OWT-025 clean: the threshold is injectable', obs('| mail sent | open | albert | 2026-09-01 | yes |\n', { staleAfterDays: 60 }).stale.length === 0);
1442
+ expect('OWT-026 violating: a hand-written observation of something version control determines', ruleOf(obs('| PR merged | open | albert | 2026-10-05 | yes |\n'), 'OWT-026') === 1);
1443
+ expect('OWT-026 clean: an external fact the assistant cannot see', ruleOf(obs('| legal replied | open | albert | 2026-10-05 | yes |\n'), 'OWT-026') === 0);
1444
+
1445
+ // OWT-027 / OWT-028 (1.3.0): a release condition naming an object in another project. The disk and git are
1446
+ // replaced by a fake environment, so the arms never touch either (the checker runs them before every command).
1447
+ const FAKE_DIR = join('/fake', 'other');
1448
+ const fakeEnv = {
1449
+ dirExists: (d) => d === FAKE_DIR,
1450
+ pathExists: (p) => p === join(FAKE_DIR, 'docs', 'a.md'),
1451
+ tagState: (_d, tag) => (tag === 'v1.0.0' ? 'present' : 'absent'),
1452
+ };
1453
+ const known = new Map([['other', FAKE_DIR]]);
1454
+ const cross = (release, projects = known, extra = '') => checkWaiting([{ path: 'x.md', content: wtab(`| wait for other | waiting | | | ${extra} | ${release} |\n`) }], { now: NOW, projects, env: fakeEnv });
1455
+ expect('OWT-027 violating: a release condition holding a machine-specific absolute path', ruleOf(cross('/Users/someone/work/other/docs/a.md'), 'OWT-027') === 1);
1456
+ expect('OWT-027 violating: an object that leaves the other project', ruleOf(cross('other:../secret.md'), 'OWT-027') === 1);
1457
+ expect('OWT-027 clean: a logical project name and an object inside it', ruleOf(cross('other:v1.0.0'), 'OWT-027') === 0);
1458
+ expect('OWT-027 violating: a drive letter is an absolute path, not a project name', ruleOf(cross('C:\\work\\other\\a.md'), 'OWT-027') === 1 && cross('C:\\work\\other\\a.md').cross.found === 0);
1459
+ expect('OWT-027 clean: a URL is not a project reference', cross('see https://example.com/a').cross.found === 0 && ruleOf(cross('see https://example.com/a'), 'OWT-027') === 0);
1460
+ expect('OWT-028 clean: a tag that exists there is released, in a project this machine can see', cross('other:v1.0.0').cross.counts.released === 1);
1461
+ expect('OWT-028 clean: a path that exists there is released', cross('other:docs/a.md').cross.counts.released === 1);
1462
+ expect('OWT-028 violating: a tag that is not there is not released', cross('other:v2.0.0').cross.counts['not-yet-released'] === 1 && cross('other:v2.0.0').cross.counts.released === 0);
1463
+ expect('OWT-028 violating: a path that is not there is not released', cross('other:docs/b.md').cross.counts['not-yet-released'] === 1);
1464
+ const unseen = cross('stranger:v1.0.0');
1465
+ expect('OWT-028 violating: a project this machine cannot see is counted apart, never released and never zero', unseen.cross.counts['not-visible'] === 1 && unseen.cross.counts.released === 0 && unseen.cross.found === 1);
1466
+ const person = cross('other:XSPEC-123');
1467
+ expect('OWT-028 violating: an identifier in another project needs a person and is never released', person.cross.counts['needs-a-person'] === 1 && person.cross.counts.released === 0);
1468
+ expect('OWT-028 clean: an unseen project is still listed with its reason', unseen.cross.items[0].status === 'not-visible' && /stranger/.test(unseen.cross.items[0].why));
1469
+ expect('OWT-020 clean: a waiting item that waits for another project is not asked about a reply', cross('other:v1.0.0').violations.length === 0 && cross('other:v1.0.0').counts['waiting-cross-project'] === 1);
1470
+ expect('OWT-020 violating: a plain waiting item is still named', ruleOf(waiting('| ask board | waiting | | | | |\n'), 'OWT-020') === 1);
1471
+ expect('OWT-027 clean: --root NAME=DIR and a plain --root are told apart', (() => { const r = parseRootOptions(['other=/fake/other', '/somewhere']); return r.error === null && r.plain === '/somewhere' && r.named.get('other') === resolve('/fake/other'); })());
1472
+ expect('OWT-027 violating: a project name that is not a logical name is refused', parseRootOptions(['Other=/x']).error !== null && parseRootOptions(['a', 'b']).error !== null);
1473
+
1474
+ // 461 R5 (1.3.0): a command the adopter declares is read by next-action AND by waiting; glab and dotnet are built in.
1475
+ expect('461 R5 clean: glab and dotnet are built-in commands', classifyNextAction('run `glab mr merge 486`', {}).status !== 'unnamed' && classifyNextAction('run `dotnet test X.csproj`', {}).status !== 'unnamed');
1476
+ expect('461 R5 violating: a program that was not declared is not a command', classifyNextAction('run `kubectl apply -f x.yaml`', {}).status === 'unnamed' && classifyNextAction('then go build it, make test, sh run', {}).status === 'unnamed');
1477
+ expect('461 R5 clean: a declared command is read by next-action', classifyNextAction('run `kubectl apply -f x.yaml`', { extraCommands: ['kubectl'] }).status !== 'unnamed');
1478
+ const kubeRow = '| ask ops | not-yet-asked | kubectl rollout restart | | | |\n';
1479
+ expect('461 R5 violating: waiting does not know an undeclared command, so the draft names nothing', ruleOf(waiting(kubeRow), 'OWT-021') === 1);
1480
+ expect('461 R5 clean: the same row under waiting names a draft once the command is declared', ruleOf(checkWaiting([{ path: 'k.md', content: wtab(kubeRow) }], { now: NOW, extraCommands: ['kubectl'] }), 'OWT-021') === 0);
1481
+ expect('461 R5 violating: a blank or spaced command word is refused', normaliseDeclaredCommands(['']).error !== null && normaliseDeclaredCommands(['git lfs']).error !== null && normaliseDeclaredCommands(['kubectl']).error === null);
1482
+ expect('461 R5 clean: a declared command is plain text, not a pattern', classifyNextAction('run `a.b x`', { extraCommands: ['a.b'] }).status !== 'unnamed' && classifyNextAction('run aXb now', { extraCommands: ['a.b'] }).status === 'unnamed');
1483
+
1484
+ // 461 R6 (1.3.0): named-unresolved says whether a path was looked up and missing, or nothing was looked up
1485
+ const split = checkNextActions([{ path: 'n.md', content: '| item | Next action |\n|---|---|\n| a | `glab mr merge 486` |\n| b | edit src/none.js |\n| c | finish XSPEC-12 |\n' }], { root: '/fake/root' });
1486
+ expect('461 R6 clean: a command and an identifier are not-resolvable, a path that is not there is path-missing, and they sum to named-unresolved', split.unresolvedSplit['not-resolvable'] === 2 && split.unresolvedSplit['path-missing'] === 1 && split.counts['named-unresolved'] === 3);
1487
+ expect('461 R6 violating: without a root nothing is looked up, so a path is not-resolvable too', checkNextActions([{ path: 'n.md', content: '| item | Next action |\n|---|---|\n| b | edit src/none.js |\n' }], {}).unresolvedSplit['not-resolvable'] === 1);
1488
+ const explained = explainResolution({ root: '/fake/root', rootGiven: false, carriers: [], split: { 'path-missing': 1, 'not-resolvable': 2 }, unresolved: 3 }).join('\n');
1489
+ expect('461 R6 clean: the resolution lines say the root, where it came from, and that only a path is looked up', explained.includes(`looked up under ${resolve('/fake/root')} (the current directory: no --root was given)`) && /Only a PATH is looked up/.test(explained) && /path-missing=1 not-resolvable=2/.test(explained) && /from --root/.test(explainResolution({ root: '/r', rootGiven: true, carriers: [], split, unresolved: 3 }).join('\n')));
1490
+
1491
+ // 461 (1.3.0): the one next-action list, the words an adopter declares, and the exit-2 explanation.
1492
+ const table461 = (h) => `| item | state | ${h} |\n|---|---|---|\n| a | open | edit scripts/foo.mjs |\n`;
1493
+ expect('461 R1 clean: 下一個動作, 下一個步驟 and 接下來要做什麼 are read by default', ['下一個動作', '下一個步驟', '接下來要做什麼'].every((h) => extractNextActions(table461(h)).fields === 1));
1494
+ expect('461 R1 violating: 待辦 is not read unless declared (the list is not widened)', extractNextActions(table461('待辦')).fields === 0 && extractNextActions(table461('Next')).fields === 0 && extractNextActions(table461('接下來')).fields === 0);
1495
+ expect('461 R2 clean: a declared word is read as a table header, a heading and an inline label, from one list', extractNextActions(table461('待辦'), ['待辦']).fields === 1 && extractNextActions('## 待辦\n- edit scripts/foo.mjs\n', ['待辦']).fields === 1 && extractNextActions('待辦: edit scripts/foo.mjs\n', ['待辦']).fields === 1);
1496
+ expect('461 R2 violating: the same carrier without the declaration is not read', extractNextActions('## 待辦\n- edit scripts/foo.mjs\n').fields === 0);
1497
+ expect('461 R2 clean: a declared word is plain text, any case, never a pattern', extractNextActions(table461('To.Do'), ['to.do']).fields === 1 && extractNextActions(table461('ToXDo'), ['to.do']).fields === 0);
1498
+ expect('461 R2 violating: a blank declared word is refused, not dropped', normaliseDeclaredWords(['']).error !== null && normaliseDeclaredWords([' ']).error !== null && normaliseDeclaredWords(['待辦']).error === null);
1499
+ const why = explainNoNextActionField([{ path: 'w.md', content: table461('待辦') }], ['後續']).join('\n');
1500
+ expect('461 R3 clean: exit-2 text names the headers the carrier showed, the words recognised and how to add one', /"待辦"/.test(why) && /"state"/.test(why) && /built in:/.test(why) && /declared by you: 後續/.test(why) && /--next-action-word/.test(why));
1501
+ expect('461 R3 clean: a carrier with a table and one with nothing to read are told apart', /has 1 table\(s\), but no table header matches/.test(why) && /no table and no heading to read/.test(explainNoNextActionField([{ path: 'n.md', content: 'just words\n' }]).join('\n')));
1502
+
1503
+ // 464 (1.4.0): an `asked-awaiting` row that OWT-022 is satisfied by is `waiting-on-reply` for next-action, and every row
1504
+ // `waiting` fails is still judged by OWT-019. Every arm here builds its carrier from text and reads no path.
1505
+ const reply = (rows, o = {}) => checkNextActions([{ path: 'w.md', content: `| item | status | asked-at | waiting for | release | Next action |\n|---|---|---|---|---|---|\n${rows}` }], { now: NOW, ...o });
1506
+ const REPLY_ROW = (status, askedAt, awaiting, release) => `| vendor quote | ${status} | ${askedAt} | ${awaiting} | ${release} | wait for the vendor reply |\n`;
1507
+ const FULL = REPLY_ROW('asked-awaiting', '2026-10-05', 'the quote', 'the quote arrives');
1508
+ const onlyReply = (res) => res.counts['waiting-on-reply'] === 1 && res.counts.unnamed === 0 && res.violations.length === 0 && res.counts['named-resolved'] + res.counts['named-unresolved'] === 0;
1509
+ const stillUnnamed = (res) => res.counts.unnamed === 1 && res.counts['waiting-on-reply'] === 0 && res.violations.length === 1;
1510
+ expect('OWT-019 clean: an asked-awaiting row with asked-at, what it waits for and its release is waiting-on-reply, not a violation and not named (XSPEC-464 R1)', onlyReply(reply(FULL)));
1511
+ expect('OWT-019 clean: the Chinese state word and the Chinese field names are read the same way (XSPEC-464 R1)', onlyReply(checkNextActions([{ path: 'w.md', content: '| 事情 | 狀態 | 詢問日期 | 等什麼 | 解除條件 | 下一步 |\n|---|---|---|---|---|---|\n| 廠商報價 | 已問、等回覆 | 2026-10-05 | 廠商回信 | 收到報價單 | 等對方回信 |\n' }], { now: NOW })));
1512
+ expect('OWT-019 violating: an asked-awaiting row with no asked-at is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('asked-awaiting', '', 'the quote', 'the quote arrives'))));
1513
+ expect('OWT-019 violating: an asked-awaiting row whose asked-at is in the future is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('asked-awaiting', '2026-10-09', 'the quote', 'the quote arrives'))));
1514
+ expect('OWT-019 violating: an asked-awaiting row that says nothing about what it waits for is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('asked-awaiting', '2026-10-05', '', 'the quote arrives'))));
1515
+ expect('OWT-019 violating: an asked-awaiting row that says nothing about its release is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('asked-awaiting', '2026-10-05', 'the quote', ''))));
1516
+ expect('OWT-019 violating: a not-yet-asked row is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('not-yet-asked', '', '', ''))));
1517
+ expect('OWT-019 violating: a row in any other state is still unnamed (XSPEC-464 R3)', stillUnnamed(reply(REPLY_ROW('in progress', '2026-10-05', 'the quote', 'the quote arrives'))));
1518
+ expect('OWT-019 violating: a table with no status column is read exactly as before (XSPEC-464 R3)', stillUnnamed(checkNextActions([{ path: 'n.md', content: '| item | Next action |\n|---|---|\n| vendor quote | wait for the vendor reply |\n' }], { now: NOW })));
1519
+ const LISTED = (label) => '- vendor quote\n - status: asked-awaiting\n - asked-at: 2026-10-05\n - waiting for: the quote\n - release: the quote arrives\n - Next action: wait for the vendor reply\n'.replace(label[0], label[1]);
1520
+ const asList = (label) => checkNextActions([{ path: 'l.md', content: LISTED(label) }], { now: NOW });
1521
+ expect('OWT-019 clean: a list item with every field is waiting-on-reply too (XSPEC-464 R1)', onlyReply(asList([' - Next action', ' - Next action'])));
1522
+ expect('OWT-019 violating: a list item whose release is blank is not read as filled by the Next action line under it, so it is still unnamed (XSPEC-464 R3)', stillUnnamed(asList(['release: the quote arrives', 'release:'])));
1523
+ expect('OWT-019 violating: a list item whose what-it-waits-for is blank is not read as filled by the lines under it, so it is still unnamed (XSPEC-464 R3)', stillUnnamed(asList(['waiting for: the quote', 'waiting for:'])));
1524
+ expect('OWT-019 violating: a next action that is a heading section is never waived (XSPEC-464 R3)', checkNextActions([{ path: 'n.md', content: '## Next action\n\n- wait for the vendor reply\n' }], { now: NOW }).counts.unnamed === 1);
1525
+ const oldAsk = reply(REPLY_ROW('asked-awaiting', '2026-08-01', 'the quote', 'the quote arrives'));
1526
+ expect('OWT-025 clean: a waiting-on-reply row shows its age and is marked stale past the threshold, still not a violation (XSPEC-464 R1)', onlyReply(oldAsk) && oldAsk.waitingOnReply[0]?.age === 67 && oldAsk.waitingOnReply[0]?.stale === true && reply(FULL).waitingOnReply[0]?.age === 2 && reply(FULL).waitingOnReply[0]?.stale === false);
1527
+ expect('OWT-025 clean: the stale threshold of a waiting-on-reply row is injectable (XSPEC-464 R1)', reply(FULL, { staleAfterDays: 1 }).waitingOnReply[0]?.stale === true && oldAsk.waitingOnReply.length === 1 && reply(REPLY_ROW('asked-awaiting', '2026-08-01', 'the quote', 'the quote arrives'), { staleAfterDays: 100 }).waitingOnReply[0]?.stale === false);
1528
+ const MATRIX = [FULL, REPLY_ROW('asked-awaiting', '', 'the quote', 'the quote arrives'), REPLY_ROW('asked-awaiting', '2026-10-09', 'the quote', 'the quote arrives'), REPLY_ROW('asked-awaiting', '2026-10-05', '', 'the quote arrives'), REPLY_ROW('asked-awaiting', '2026-10-05', 'the quote', ''), REPLY_ROW('asked-awaiting', 'last week', 'the quote', 'the quote arrives'), REPLY_ROW('not-yet-asked', '', '', ''), REPLY_ROW('waiting', '', '', ''), REPLY_ROW('in progress', '2026-10-05', 'the quote', 'the quote arrives'), REPLY_ROW('done', '2026-10-05', 'the quote', 'the quote arrives')];
1529
+ const agree = (row) => {
1530
+ const text = `| item | status | asked-at | waiting for | release | Next action |\n|---|---|---|---|---|---|\n${row}`;
1531
+ const w = checkWaiting([{ path: 'w.md', content: text }], { now: NOW });
1532
+ const n = checkNextActions([{ path: 'w.md', content: text }], { now: NOW });
1533
+ const waitingPasses = w.counts['asked-awaiting'] === 1 && !w.violations.some((v) => v.rule === 'OWT-020' || v.rule === 'OWT-022');
1534
+ return waitingPasses === (n.counts['waiting-on-reply'] === 1) && !(waitingPasses && n.violations.length > 0) && !(w.violations.some((v) => v.rule === 'OWT-022') && n.counts['waiting-on-reply'] > 0);
1535
+ };
1536
+ expect('OWT-019 clean: waiting and next-action never give opposite answers about the same row (XSPEC-464 R2)', MATRIX.every(agree) && MATRIX.length === 10);
1537
+
1538
+ return { ok: failures.length === 0, failures, ran };
1539
+ }
1540
+
1541
+ // ── CLI ──────────────────────────────────────────────────────────────────────
1542
+
1543
+ const COVERAGE_NOTE = 'COVERAGE UNKNOWN (OWT-011): recognising a path/command/test name/identifier is pattern matching; an unrecognised format is reported as unnamed. A clean pass does not mean every next action is specific.';
1544
+ const UNCALIBRATED_NOTE = 'UNCALIBRATED (OWT-016): heading vocabulary, command list, extension list and identifier pattern are initial judgments.';
1545
+ const UNCALIBRATED_STATE_NOTE = 'UNCALIBRATED (OWT-016): the state words, field names (English and Chinese), the derivable-subject word list and the stale-after threshold are initial judgments, none measured against real usage.';
1546
+
1547
+ function readCarrier(p) {
1548
+ return { path: p, content: readFileSync(p, 'utf8') };
1549
+ }
1550
+
1551
+ function gitShowBase(file, rev) {
1552
+ const abs = resolve(file);
1553
+ const git = (args, cwd) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
1554
+ const top = git(['rev-parse', '--show-toplevel'], dirname(abs)).trim();
1555
+ git(['rev-parse', '--verify', `${rev}^{commit}`], top);
1556
+ // Ask git for the path, never compute it from two filesystem paths: on Windows the
1557
+ // temp directory can carry an 8.3 short name (RUNNER~1) that realpathSync does not
1558
+ // expand while git reports the long name, so relative() walks out of the repo and
1559
+ // `git show` fails, which this tool reports as "undecidable" (exit 2) rather than a
1560
+ // verdict. git computes the prefix from the same cwd it will read from.
1561
+ const prefix = git(['rev-parse', '--show-prefix'], dirname(abs)).trim();
1562
+ const rel = `${prefix}${basename(abs)}`;
1563
+ const listed = git(['ls-tree', rev, '--', rel], top).trim();
1564
+ if (!listed) return null; // absent at that revision: a new file, not an error
1565
+ return git(['show', `${rev}:${rel}`], top);
1566
+ }
1567
+
1568
+ export function main(argv, io = { log: console.log, err: console.error }) {
1569
+ const out = [];
1570
+ const say = (s) => out.push(s);
1571
+ const args = [...argv];
1572
+ const flag = (name) => {
1573
+ const i = args.indexOf(name);
1574
+ if (i === -1) return undefined;
1575
+ const v = args[i + 1];
1576
+ args.splice(i, 2);
1577
+ return v;
1578
+ };
1579
+ // every occurrence of a repeatable option, in order; a missing value is kept as undefined so the caller can refuse it
1580
+ const flagAll = (name) => {
1581
+ const values = [];
1582
+ let i;
1583
+ while ((i = args.indexOf(name)) !== -1) { values.push(args[i + 1]); args.splice(i, 2); }
1584
+ return values;
1585
+ };
1586
+ const finish = (code) => { for (const l of out) (code === 2 ? io.err : io.log)(l); return code; };
1587
+
1588
+ const selfTest = runSelfTest();
1589
+ if (args[0] === '--self-test') {
1590
+ say(selfTest.ok ? '[owt] self-test: OK' : `[owt] self-test FAILED: ${selfTest.failures.join('; ')}`);
1591
+ return finish(selfTest.ok ? 0 : 2);
1592
+ }
1593
+ if (!selfTest.ok) {
1594
+ say(`[owt] CANNOT DECIDE: this checker's own self-test arms failed (${selfTest.failures.join('; ')}). A checker that fails its own arms is not evidence of anything. Exit 2 is not a pass.`);
1595
+ return finish(2);
1596
+ }
1597
+
1598
+ const cmd = args.shift();
1599
+ try {
1600
+ if (cmd === 'next-action') {
1601
+ const rootArg = flag('--root');
1602
+ const root = rootArg ?? process.cwd();
1603
+ const idPattern = flag('--id-pattern');
1604
+ const declared = normaliseDeclaredWords(flagAll('--next-action-word'));
1605
+ if (declared.error) { say(`[owt] next-action: ${declared.error}`); return finish(2); }
1606
+ const commandsDeclared = normaliseDeclaredCommands(flagAll('--command-word'));
1607
+ if (commandsDeclared.error) { say(`[owt] next-action: ${commandsDeclared.error}`); return finish(2); }
1608
+ const roleWords = declaredRoleWords(flagAll);
1609
+ if (roleWords.error) { say(`[owt] next-action: ${roleWords.error}`); return finish(2); }
1610
+ // 464: today and the stale threshold are injected, as they are for `waiting` and `observations`, never read inside a rule.
1611
+ const nowArg = flag('--now');
1612
+ const now = nowArg === undefined ? todayUtc() : parseDay(nowArg);
1613
+ if (now === null) { say(`[owt] next-action: --now must be a date with a year (YYYY-MM-DD), got "${nowArg}"`); return finish(2); }
1614
+ const staleArg = flag('--stale-after');
1615
+ const staleAfterDays = staleArg === undefined ? undefined : Number(staleArg);
1616
+ if (staleAfterDays !== undefined && (!Number.isFinite(staleAfterDays) || staleAfterDays < 0)) { say(`[owt] next-action: --stale-after must be a number of days, got "${staleArg}"`); return finish(2); }
1617
+ const files = args;
1618
+ if (!files.length) { say('[owt] next-action: no files given'); return finish(2); }
1619
+ const carriers = files.map(readCarrier);
1620
+ const res = checkNextActions(carriers, { root, idPattern, words: declared.words, extraCommands: commandsDeclared.words, roleWords: roleWords.words, now, staleAfterDays });
1621
+ say(`[owt] OWT-019 walked ${res.walked} next-action field(s) in ${files.length} carrier(s); ${res.empty} empty/done field(s) not evaluated; ${res.noFieldCarriers.length} carrier(s) had no next-action field`);
1622
+ // `waiting-on-reply=N` is appended only when N is not 0, as `waiting-cross-project` is: a carrier with no such row prints what it always printed.
1623
+ say(`[owt] named-resolved=${res.counts['named-resolved']} named-unresolved=${res.counts['named-unresolved']} unnamed=${res.counts.unnamed} undecidable-table-rows=${res.undecidable.length}${res.counts['waiting-on-reply'] ? ` waiting-on-reply=${res.counts['waiting-on-reply']}` : ''}`);
1624
+ // 461 R6: the lines below are additions; every line above and below them is what 1.1.0 printed.
1625
+ for (const l of explainResolution({ root, rootGiven: rootArg !== undefined, carriers, split: res.unresolvedSplit, unresolved: res.counts['named-unresolved'], commands: commandsDeclared.words })) say(`[owt] ${l}`);
1626
+ for (const d of res.detail) say(`[owt] ${d.status.padEnd(16)} ${d.path} ${d.where}: ${d.text.slice(0, 80)}${d.kinds.length ? ' <- ' + d.kinds.map((k) => `${k.kind}:${k.value}`).join(', ') : ''}`);
1627
+ if (res.waitingOnReply.length) {
1628
+ const stale = res.waitingOnReply.filter((x) => x.stale).length;
1629
+ say(`[owt] WAITING-ON-REPLY ${res.waitingOnReply.length} row(s) are asked-awaiting and carry everything OWT-022 asks for, so OWT-019 is not applied to them (counted apart: not named, not resolved, not complete; ${stale} older than ${res.staleAfter} day(s), UNCALIBRATED):`);
1630
+ for (const x of res.waitingOnReply) say(`[owt] ${x.path} ${x.where}: asked ${x.age}d ago (${dayString(x.askedDay)})${x.stale ? ` STALE (older than ${res.staleAfter}d)` : ''}; waiting for: ${clip(x.awaiting, 60)}; released by: ${clip(x.release, 60)}`);
1631
+ say('[owt] WAITING-ON-REPLY LIMIT: the check decides that asked-at, what is waited for and the release event are present and well formed (OWT-022). It cannot decide that the request was really sent or that it is still unanswered (OWT-014, as for OWT-023). A row without all of them is judged by OWT-019 as before.');
1632
+ }
1633
+ for (const v of res.violations) say(`[owt] VIOLATION OWT-019: ${v.path} ${v.where} names no file path, test name, command or requirement identifier: "${v.text.slice(0, 80)}"`);
1634
+ for (const u of res.undecidable) say(`[owt] UNDECIDABLE: ${u.path} ${u.where} has ${u.cells} cell(s) but its header has ${u.expected}; the next-action cell cannot be located, so the row is neither judged nor counted as empty`);
1635
+ say(`[owt] ${COVERAGE_NOTE}`);
1636
+ say(`[owt] ${UNCALIBRATED_NOTE}`);
1637
+ if (res.walked + res.empty === 0) {
1638
+ say('[owt] CANNOT DECIDE: no next-action field found in any carrier (walked 0). Exit 2 is not a pass.');
1639
+ for (const l of explainNoNextActionField(carriers, declared.words, res.undecidable.map((u) => u.path))) say(`[owt] ${l}`);
1640
+ return finish(2);
1641
+ }
1642
+ // A violation is a definite answer whatever else is unreadable. Absent one, a row we could
1643
+ // not read means "no violation found" is not "no violation": exit 2, never a green 0.
1644
+ if (!res.violations.length && res.undecidable.length) { say(`[owt] CANNOT DECIDE: ${res.undecidable.length} table row(s) could not be read (see UNDECIDABLE above), so a clean result would cover only part of the field. Exit 2 is not a pass.`); return finish(2); }
1645
+ return finish(res.violations.length ? 1 : 0);
1646
+ }
1647
+ if (cmd === 'revision') {
1648
+ const file = flag('--file');
1649
+ const base = flag('--base');
1650
+ const beforeF = flag('--before');
1651
+ const afterF = flag('--after');
1652
+ let before; let after; let path;
1653
+ if (file && base) { path = file; after = readFileSync(file, 'utf8'); before = gitShowBase(file, base); } else if (beforeF && afterF) { path = afterF; before = readFileSync(beforeF, 'utf8'); after = readFileSync(afterF, 'utf8'); } else { say('[owt] revision: give --file PATH --base REV, or --before FILE --after FILE'); return finish(2); }
1654
+ const r = checkIntentRevision({ before, after, path });
1655
+ say(`[owt] OWT-018 ${path}: ${r.status}${r.changedSections.length ? ` (changed: ${r.changedSections.join(', ')})` : ''}`);
1656
+ if (r.status === 'no-baseline') say('[owt] the carrier did not exist in the baseline; there is nothing to compare');
1657
+ if (r.status === 'undecidable') { say('[owt] CANNOT DECIDE: no acceptance/goal/constraint section found in either version, so the check cannot see the intent. Exit 2 is not a pass.'); say(`[owt] ${UNCALIBRATED_NOTE}`); return finish(2); }
1658
+ for (const v of r.violations) say(`[owt] VIOLATION ${v.rule}: ${v.why}${v.sections ? ` [${v.sections.join(', ')}]` : ''}${v.entry ? ` <${v.entry.slice(0, 60)}>` : ''}`);
1659
+ if (r.handBack.length) {
1660
+ say('[owt] HAND-BACK (OWT-018 -> OWT-007) — list these when control returns to a human; this listing never blocks (OWT-008):');
1661
+ for (const h of r.handBack) say(`[owt] edit to ${h.sections ? h.sections.join(', ') : 'intent'} in ${path}: ${h.why}`);
1662
+ }
1663
+ say('[owt] LIMIT: the check decides that intent changed, that a NEW record exists, that it is complete and whether an approver is filled in. It cannot decide that the record describes the change honestly (OWT-014).');
1664
+ say(`[owt] ${UNCALIBRATED_NOTE}`);
1665
+ return finish(r.violations.length ? 1 : 0);
1666
+ }
1667
+ if (cmd === 'separation') {
1668
+ const declared = normaliseDeclaredWords(flagAll('--next-action-word'));
1669
+ if (declared.error) { say(`[owt] separation: ${declared.error}`); return finish(2); }
1670
+ const files = args;
1671
+ if (!files.length) { say('[owt] separation: no files given'); return finish(2); }
1672
+ const r = checkSeparation(files.map(readCarrier), { words: declared.words });
1673
+ say(`[owt] OWT-017 walked ${r.walked} carrier(s); ${r.recognised} had a recognised intent or progress section`);
1674
+ for (const v of r.violations) say(`[owt] VIOLATION OWT-017: ${v.path} holds intent (${v.intent.join(', ')}) and progress (${v.progress.join(', ')}) in one carrier`);
1675
+ say(`[owt] ${UNCALIBRATED_NOTE}`);
1676
+ if (r.recognised === 0) { say('[owt] CANNOT DECIDE: no carrier had a recognised intent or progress heading. Exit 2 is not a pass.'); return finish(2); }
1677
+ return finish(r.violations.length ? 1 : 0);
1678
+ }
1679
+ if (cmd === 'waiting' || cmd === 'observations') {
1680
+ const nowArg = flag('--now');
1681
+ const now = nowArg === undefined ? todayUtc() : parseDay(nowArg);
1682
+ if (now === null) { say(`[owt] ${cmd}: --now must be a date with a year (YYYY-MM-DD), got "${nowArg}"`); return finish(2); }
1683
+ const staleArg = cmd === 'observations' ? flag('--stale-after') : undefined;
1684
+ const staleAfterDays = staleArg === undefined ? undefined : Number(staleArg);
1685
+ if (staleAfterDays !== undefined && (!Number.isFinite(staleAfterDays) || staleAfterDays < 0)) { say(`[owt] observations: --stale-after must be a number of days, got "${staleArg}"`); return finish(2); }
1686
+ let root;
1687
+ const projects = new Map();
1688
+ if (cmd === 'waiting') {
1689
+ // `--root DIR` (one, as before) says what relative paths are resolved against; `--root NAME=DIR`
1690
+ // (repeatable) says where another project lives on this machine (OWT-027 / OWT-028).
1691
+ const given = parseRootOptions(flagAll('--root'));
1692
+ if (given.error) { say(`[owt] waiting: ${given.error}`); return finish(2); }
1693
+ root = given.plain ?? process.cwd();
1694
+ for (const [name, dir] of given.named) projects.set(name, dir);
1695
+ }
1696
+ const idPattern = cmd === 'waiting' ? flag('--id-pattern') : undefined;
1697
+ const commandsDeclared = cmd === 'waiting' ? normaliseDeclaredCommands(flagAll('--command-word')) : { words: [], error: null };
1698
+ if (commandsDeclared.error) { say(`[owt] waiting: ${commandsDeclared.error}`); return finish(2); }
1699
+ const roleWords = cmd === 'waiting' ? declaredRoleWords(flagAll) : { words: {}, error: null };
1700
+ if (roleWords.error) { say(`[owt] waiting: ${roleWords.error}`); return finish(2); }
1701
+ const files = args;
1702
+ if (!files.length) { say(`[owt] ${cmd}: no files given`); return finish(2); }
1703
+ const carriers = files.map(readCarrier);
1704
+ if (cmd === 'waiting') {
1705
+ const res = checkWaiting(carriers, { now, root, idPattern, projects, extraCommands: commandsDeclared.words, roleWords: roleWords.words });
1706
+ say(`[owt] OWT-020/021/022 walked ${res.walked} record(s) with a status field in ${carriers.length} carrier(s) (today ${dayString(now)}); ${res.noStateCarriers.length} carrier(s) had none`);
1707
+ say(`[owt] not-yet-asked=${res.counts['not-yet-asked']} asked-awaiting=${res.counts['asked-awaiting']} waiting-unspecified=${res.counts['waiting-unspecified']} done=${res.counts.done} other=${res.counts.other}${res.counts['waiting-cross-project'] ? ` waiting-cross-project=${res.counts['waiting-cross-project']}` : ''} undecidable-table-rows=${res.ragged.length}`);
1708
+ for (const d of res.detail) say(`[owt] ${d.state.padEnd(20)} ${d.path} ${d.where}: ${d.text.slice(0, 60)}${d.note ? ` (${d.note})` : ''}`);
1709
+ if (res.cross.found > 0) {
1710
+ const k = res.cross.counts;
1711
+ say(`[owt] OWT-027/028 ${res.cross.found} release condition(s) name an object in another project (looked up on this machine only; no network): released=${k.released} not-yet-released=${k['not-yet-released']} not-visible-from-here=${k['not-visible']} needs-a-person=${k['needs-a-person']}`);
1712
+ const label = { released: 'RELEASED', 'not-yet-released': 'NOT YET RELEASED', 'not-visible': 'NOT VISIBLE FROM HERE', 'needs-a-person': 'NEEDS A PERSON' };
1713
+ for (const x of res.cross.items) say(`[owt] ${label[x.status].padEnd(21)} ${x.name}:${x.object} (${x.kind}, ${x.observable}) ${x.path} ${x.where}: ${x.why}`);
1714
+ for (const name of [...new Set(res.cross.items.map((x) => x.name))]) if (projects.has(name)) say(`[owt] RESOLUTION: ${lookupSentence(`project "${name}"`, projects.get(name), 'from --root NAME=DIR or open_work.projects')}. Only a path or a version-control tag is looked up; nothing leaves this machine.`);
1715
+ say('[owt] NOT VISIBLE FROM HERE is counted apart: it is not released and it is not zero. NEEDS A PERSON is counted apart and is never released. RELEASED says the object exists there now, never that it is the right object (OWT-014).');
1716
+ }
1717
+ for (const v of res.violations) say(`[owt] VIOLATION ${v.rule}: ${v.path} ${v.where} ${v.why}`);
1718
+ for (const u of res.ragged) say(`[owt] UNDECIDABLE: ${u.path} ${u.where} has ${u.cells} cell(s) but its header has ${u.expected}; the status cell cannot be located, so the row is neither judged nor counted as empty`);
1719
+ say('[owt] A waiting item that is neither not-yet-asked nor asked-awaiting is named above, one by one; it is never folded into a total and never counted as done.');
1720
+ say('[owt] COVERAGE UNKNOWN (OWT-011): state words and field names are matched by vocabulary. A waiting item written in words the vocabulary does not hold is read as "other", not as waiting. A clean pass does not mean nothing is waiting unasked.');
1721
+ say(`[owt] ${UNCALIBRATED_STATE_NOTE}`);
1722
+ if (res.walked === 0) { say('[owt] CANNOT DECIDE: no record with a status field in any carrier (walked 0). Exit 2 is not a pass.'); return finish(2); }
1723
+ if (!res.violations.length && res.ragged.length) { say(`[owt] CANNOT DECIDE: ${res.ragged.length} table row(s) could not be read (see UNDECIDABLE above), so a clean result would cover only part of the field. Exit 2 is not a pass.`); return finish(2); }
1724
+ return finish(res.violations.length ? 1 : 0);
1725
+ }
1726
+ const res = checkObservations(carriers, { now, staleAfterDays });
1727
+ say(`[owt] OWT-023/024/025/026 walked ${res.walked} observation(s) in ${carriers.length} carrier(s) (today ${dayString(now)}); stale after ${res.staleAfter} day(s) (${staleArg === undefined ? 'default, ' : ''}UNCALIBRATED); ${res.noObservationCarriers.length} carrier(s) had none`);
1728
+ say(`[owt] yes=${res.counts.yes} no=${res.counts.no} unknown=${res.counts.unknown} invalid=${res.counts.invalid} | stale=${res.stale.length} | confirmed=${res.confirmed} (yes, well formed, not stale) | undecidable-table-rows=${res.ragged.length}`);
1729
+ for (const d of res.detail) say(`[owt] value=${d.value} age=${d.age === null ? '?' : `${d.age}d`} by=${d.by || '?'} at=${d.observedAt || '?'} ${d.path} ${d.where}: ${d.text.slice(0, 60)}`);
1730
+ for (const u of res.unknown) say(`[owt] UNKNOWN (counted apart, never complete): ${u.path} ${u.where}: ${u.text.slice(0, 60)}`);
1731
+ for (const s of res.stale) say(`[owt] STALE (observed ${s.age}d ago, older than ${res.staleAfter}d; counted apart, not confirmed${s.claimsDone ? '; the item claims done on this observation' : ''}): ${s.path} ${s.where}: ${s.text.slice(0, 60)}`);
1732
+ for (const v of res.violations) say(`[owt] VIOLATION ${v.rule}: ${v.path} ${v.where} ${v.why}`);
1733
+ for (const u of res.ragged) say(`[owt] UNDECIDABLE: ${u.path} ${u.where} has ${u.cells} cell(s) but its header has ${u.expected}; the row is neither judged nor counted as empty`);
1734
+ say('[owt] LIMIT: the check decides that the fields exist, are well formed, and how old the stamp is. It cannot decide that an observation is true, or that it is still true now (OWT-014): a stamp says who saw it and when, never that it still holds.');
1735
+ say('[owt] COVERAGE UNKNOWN (OWT-011): a table is read as an observation carrier only if it has an observed-by or observed-at column (or a list item such a label); the "derivable subject" test is a short word list. A clean pass does not mean no hand-written fact is unstamped or derivable.');
1736
+ say(`[owt] ${UNCALIBRATED_STATE_NOTE}`);
1737
+ if (res.walked === 0) { say('[owt] CANNOT DECIDE: no observation record (no observed-by / observed-at field) in any carrier (walked 0). Exit 2 is not a pass.'); return finish(2); }
1738
+ if (!res.violations.length && res.ragged.length) { say(`[owt] CANNOT DECIDE: ${res.ragged.length} table row(s) could not be read (see UNDECIDABLE above), so a clean result would cover only part of the field. Exit 2 is not a pass.`); return finish(2); }
1739
+ return finish(res.violations.length ? 1 : 0);
1740
+ }
1741
+ // The repo shim (its own `--self-test` flag) is named FIRST on purpose: cli/scripts/check-command-existence.mjs
1742
+ // reads a `uds <...>` string up to the closing quote, so a `--self-test` written AFTER `uds open-work`
1743
+ // is judged as a flag of the `uds open-work` command, which has none (it is the subcommand `self-test`).
1744
+ say('[owt] usage: node scripts/check-open-work-tracking.mjs ... | --self-test (or from the npm package: uds open-work next-action|revision|separation|waiting|observations|self-test ...)');
1745
+ return finish(2);
1746
+ } catch (e) {
1747
+ say(`[owt] CANNOT DECIDE: ${e.message.split('\n')[0]}`);
1748
+ return finish(2);
1749
+ }
1750
+ }
1751
+
1752
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
1753
+ process.exitCode = main(process.argv.slice(2));
1754
+ }