agentlock-harness 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +211 -2
  3. package/README.zh-CN.md +211 -0
  4. package/RELEASE_NOTES.md +35 -0
  5. package/bin/agentlock-harness.mjs +249 -0
  6. package/harness-templates/en-US/common/CLAUDE.md.tmpl +7 -0
  7. package/harness-templates/en-US/common/GEMINI.md.tmpl +7 -0
  8. package/harness-templates/en-US/common/agentlock-harness.json.tmpl +45 -0
  9. package/harness-templates/en-US/common/claude-settings.json +36 -0
  10. package/harness-templates/en-US/common/codex-config.toml.tmpl +11 -0
  11. package/harness-templates/en-US/common/copilot-instructions.md.tmpl +3 -0
  12. package/harness-templates/en-US/common/gemini-settings.json +42 -0
  13. package/harness-templates/en-US/common/git-hooks/pre-commit +24 -0
  14. package/harness-templates/en-US/common/git-hooks/pre-push +11 -0
  15. package/harness-templates/en-US/common/harness-gitignore +3 -0
  16. package/harness-templates/en-US/common/hooks/post-edit-check.mjs +57 -0
  17. package/harness-templates/en-US/common/hooks/pre-tool-guard.mjs +122 -0
  18. package/harness-templates/en-US/common/hooks/rules-drift-check.mjs +69 -0
  19. package/harness-templates/en-US/common/hooks/staged-guard.mjs +197 -0
  20. package/harness-templates/en-US/common/hooks/stop-gate.mjs +164 -0
  21. package/harness-templates/en-US/common/rules/00-testing-integrity.md +11 -0
  22. package/harness-templates/en-US/common/rules/01-security-boundaries.md +11 -0
  23. package/harness-templates/en-US/common/skills/atomic-tdd/SKILL.md +21 -0
  24. package/harness-templates/en-US/common/skills/brainstorming/SKILL.md +24 -0
  25. package/harness-templates/en-US/common/skills/code-grounding/SKILL.md +20 -0
  26. package/harness-templates/en-US/common/skills/cross-model-review/SKILL.md +22 -0
  27. package/harness-templates/en-US/common/skills/worktree-isolation/SKILL.md +19 -0
  28. package/harness-templates/en-US/dual-core/HARNESS_GUIDE.md +19 -0
  29. package/harness-templates/en-US/dual-core/scripts/cross-review.mjs +141 -0
  30. package/harness-templates/en-US/enterprise-platform/ci/agentlock-harness-gate.yml +32 -0
  31. package/harness-templates/en-US/enterprise-platform/governance/mcp-gateway.template.json +18 -0
  32. package/harness-templates/en-US/enterprise-platform/governance/policy.json +26 -0
  33. package/harness-templates/en-US/ralph-factory/PROMPT.loop.md.tmpl +12 -0
  34. package/harness-templates/en-US/ralph-factory/SPRINT_CONTRACT.md.tmpl +25 -0
  35. package/harness-templates/en-US/ralph-factory/sandbox/Dockerfile.sandbox +13 -0
  36. package/harness-templates/en-US/ralph-factory/sandbox/docker-compose.sandbox.yml +22 -0
  37. package/harness-templates/en-US/ralph-factory/sandbox/run-sandbox-loop.sh +8 -0
  38. package/harness-templates/zh-CN/common/CLAUDE.md.tmpl +7 -0
  39. package/harness-templates/zh-CN/common/GEMINI.md.tmpl +7 -0
  40. package/harness-templates/zh-CN/common/agentlock-harness.json.tmpl +45 -0
  41. package/harness-templates/zh-CN/common/claude-settings.json +36 -0
  42. package/harness-templates/zh-CN/common/codex-config.toml.tmpl +11 -0
  43. package/harness-templates/zh-CN/common/copilot-instructions.md.tmpl +3 -0
  44. package/harness-templates/zh-CN/common/gemini-settings.json +42 -0
  45. package/harness-templates/zh-CN/common/git-hooks/pre-commit +24 -0
  46. package/harness-templates/zh-CN/common/git-hooks/pre-push +11 -0
  47. package/harness-templates/zh-CN/common/harness-gitignore +3 -0
  48. package/harness-templates/zh-CN/common/hooks/post-edit-check.mjs +57 -0
  49. package/harness-templates/zh-CN/common/hooks/pre-tool-guard.mjs +122 -0
  50. package/harness-templates/zh-CN/common/hooks/rules-drift-check.mjs +69 -0
  51. package/harness-templates/zh-CN/common/hooks/staged-guard.mjs +197 -0
  52. package/harness-templates/zh-CN/common/hooks/stop-gate.mjs +164 -0
  53. package/harness-templates/zh-CN/common/rules/00-testing-integrity.md +11 -0
  54. package/harness-templates/zh-CN/common/rules/01-security-boundaries.md +11 -0
  55. package/harness-templates/zh-CN/common/skills/atomic-tdd/SKILL.md +21 -0
  56. package/harness-templates/zh-CN/common/skills/brainstorming/SKILL.md +24 -0
  57. package/harness-templates/zh-CN/common/skills/code-grounding/SKILL.md +20 -0
  58. package/harness-templates/zh-CN/common/skills/cross-model-review/SKILL.md +22 -0
  59. package/harness-templates/zh-CN/common/skills/worktree-isolation/SKILL.md +19 -0
  60. package/harness-templates/zh-CN/dual-core/HARNESS_GUIDE.md +19 -0
  61. package/harness-templates/zh-CN/dual-core/scripts/cross-review.mjs +141 -0
  62. package/harness-templates/zh-CN/enterprise-platform/ci/agentlock-harness-gate.yml +32 -0
  63. package/harness-templates/zh-CN/enterprise-platform/governance/mcp-gateway.template.json +18 -0
  64. package/harness-templates/zh-CN/enterprise-platform/governance/policy.json +26 -0
  65. package/harness-templates/zh-CN/ralph-factory/PROMPT.loop.md.tmpl +12 -0
  66. package/harness-templates/zh-CN/ralph-factory/SPRINT_CONTRACT.md.tmpl +25 -0
  67. package/harness-templates/zh-CN/ralph-factory/sandbox/Dockerfile.sandbox +13 -0
  68. package/harness-templates/zh-CN/ralph-factory/sandbox/docker-compose.sandbox.yml +22 -0
  69. package/harness-templates/zh-CN/ralph-factory/sandbox/run-sandbox-loop.sh +8 -0
  70. package/package.json +64 -4
  71. package/scripts/bootstrap.ps1 +13 -0
  72. package/scripts/bootstrap.sh +23 -0
  73. package/src/cli/colors.mjs +42 -0
  74. package/src/cli/commands/adopt.mjs +378 -0
  75. package/src/cli/commands/change.mjs +92 -0
  76. package/src/cli/commands/doctor.mjs +56 -0
  77. package/src/cli/commands/eval.mjs +193 -0
  78. package/src/cli/commands/hooks.mjs +97 -0
  79. package/src/cli/commands/init.mjs +231 -0
  80. package/src/cli/commands/passthrough.mjs +27 -0
  81. package/src/cli/commands/ralph.mjs +208 -0
  82. package/src/cli/commands/rules.mjs +73 -0
  83. package/src/cli/commands/stats.mjs +71 -0
  84. package/src/cli/commands/task.mjs +123 -0
  85. package/src/cli/commands/ui.mjs +84 -0
  86. package/src/cli/commands/verify.mjs +267 -0
  87. package/src/cli/prompt.mjs +55 -0
  88. package/src/core/adopt.mjs +807 -0
  89. package/src/core/agent-runner.mjs +118 -0
  90. package/src/core/audit.mjs +181 -0
  91. package/src/core/catalog.mjs +160 -0
  92. package/src/core/change-flow.mjs +344 -0
  93. package/src/core/detector.mjs +141 -0
  94. package/src/core/doc-drift.mjs +94 -0
  95. package/src/core/eval-fixtures.mjs +676 -0
  96. package/src/core/eval-frontier-fixtures.mjs +657 -0
  97. package/src/core/eval-hard-fixtures.mjs +923 -0
  98. package/src/core/eval-runner.mjs +754 -0
  99. package/src/core/eval-telemetry.mjs +338 -0
  100. package/src/core/harness-writer.mjs +286 -0
  101. package/src/core/installer.mjs +42 -0
  102. package/src/core/rules-compiler.mjs +356 -0
  103. package/src/core/task-ledger.mjs +327 -0
  104. package/src/core/version.mjs +10 -0
  105. package/src/ui/public/app.mjs +2199 -0
  106. package/src/ui/public/index.html +203 -0
  107. package/src/ui/public/styles.css +1200 -0
  108. package/src/ui/server.mjs +457 -0
  109. package/src/ui/service.mjs +860 -0
  110. package/templates/en-US/AGENTS.md +38 -0
  111. package/templates/en-US/DOCS_MAINTENANCE.md +65 -0
  112. package/templates/en-US/MIGRATION.md +46 -0
  113. package/templates/en-US/NEW_PROJECT_CHECKLIST.md +46 -0
  114. package/templates/en-US/README.md +41 -0
  115. package/templates/en-US/SESSION.md +29 -0
  116. package/templates/en-US/docs/00-context.md +38 -0
  117. package/templates/en-US/docs/01-vision/README.md +36 -0
  118. package/templates/en-US/docs/02-requirements/PRD.md +24 -0
  119. package/templates/en-US/docs/02-requirements/glossary.md +20 -0
  120. package/templates/en-US/docs/02-requirements/use-cases.md +36 -0
  121. package/templates/en-US/docs/03-architecture/composite-ai-framework.md +36 -0
  122. package/templates/en-US/docs/03-architecture/integration-architecture.md +36 -0
  123. package/templates/en-US/docs/03-architecture/system-architecture.md +16 -0
  124. package/templates/en-US/docs/04-design/README.md +21 -0
  125. package/templates/en-US/docs/04-design/a2a-integration-spec.md +36 -0
  126. package/templates/en-US/docs/04-design/agent-specs.md +36 -0
  127. package/templates/en-US/docs/04-design/data-model.md +18 -0
  128. package/templates/en-US/docs/04-design/external-api-spec.md +26 -0
  129. package/templates/en-US/docs/04-design/mcp-interface-spec.md +36 -0
  130. package/templates/en-US/docs/04-design/phase1-minimal-implementation-interfaces.md +36 -0
  131. package/templates/en-US/docs/04-design/responsibility-model.md +36 -0
  132. package/templates/en-US/docs/04-design/runtime-control-plane-spec.md +36 -0
  133. package/templates/en-US/docs/04-design/safety-governance.md +18 -0
  134. package/templates/en-US/docs/04-design/sample-scenarios-architecture-refinement.md +20 -0
  135. package/templates/en-US/docs/04-design/skill-syntax-spec.md +36 -0
  136. package/templates/en-US/docs/04-design/storage-schema.md +18 -0
  137. package/templates/en-US/docs/04-design/task-capability-architecture-and-evolution.md +36 -0
  138. package/templates/en-US/docs/05-project/adr/ADR-000-template.md +32 -0
  139. package/templates/en-US/docs/05-project/adr/README.md +15 -0
  140. package/templates/en-US/docs/05-project/doc-code-map.md +17 -0
  141. package/templates/en-US/docs/05-project/evolution-backlog.md +14 -0
  142. package/templates/en-US/docs/05-project/feature-registry.md +16 -0
  143. package/templates/en-US/docs/05-project/master-delivery-tracker.md +14 -0
  144. package/templates/en-US/docs/05-project/risk-register.md +36 -0
  145. package/templates/en-US/docs/05-project/roadmap.md +36 -0
  146. package/templates/en-US/docs/05-project/stage-view.md +14 -0
  147. package/templates/en-US/docs/05-project/tech-stack.md +36 -0
  148. package/templates/en-US/docs/06-dev-guide/SPEC.md +18 -0
  149. package/templates/en-US/docs/06-dev-guide/coding-standards.md +36 -0
  150. package/templates/en-US/docs/06-dev-guide/deployment-architecture.md +20 -0
  151. package/templates/en-US/docs/06-dev-guide/project-scaffold.md +16 -0
  152. package/templates/en-US/docs/06-dev-guide/testing-strategy.md +42 -0
  153. package/templates/en-US/docs/07-frontend/README.md +36 -0
  154. package/templates/en-US/docs/07-frontend/user-personas.md +36 -0
  155. package/templates/en-US/docs/08-process/README.md +27 -0
  156. package/templates/en-US/docs/08-process/ai-collaboration-protocol.md +28 -0
  157. package/templates/en-US/docs/08-process/autopilot.md +18 -0
  158. package/templates/en-US/docs/08-process/code-grounding.md +32 -0
  159. package/templates/en-US/docs/08-process/context-loading-strategy.md +35 -0
  160. package/templates/en-US/docs/08-process/conventions.md +75 -0
  161. package/templates/en-US/docs/08-process/debugging.md +25 -0
  162. package/templates/en-US/docs/08-process/design-gate.md +22 -0
  163. package/templates/en-US/docs/08-process/git-protocol.md +20 -0
  164. package/templates/en-US/docs/08-process/multi-agent-orchestration.md +27 -0
  165. package/templates/en-US/docs/08-process/planning.md +18 -0
  166. package/templates/en-US/docs/08-process/project-intake.md +47 -0
  167. package/templates/en-US/docs/08-process/reflection.md +18 -0
  168. package/templates/en-US/docs/08-process/review.md +30 -0
  169. package/templates/en-US/docs/08-process/session-handoff.md +27 -0
  170. package/templates/en-US/docs/08-process/tdd.md +24 -0
  171. package/templates/en-US/docs/08-process/tool-execution.md +32 -0
  172. package/templates/en-US/docs/08-process/workflow-contract.md +46 -0
  173. package/templates/en-US/docs/08-process/workflow.md +23 -0
  174. package/templates/en-US/docs/README.md +58 -0
  175. package/templates/en-US/docs/design-checklist.md +36 -0
  176. package/templates/en-US/docs/discussions/README.md +13 -0
  177. package/templates/en-US/docs/plans/README.md +13 -0
  178. package/templates/en-US/docs/proposed-design/README.md +13 -0
  179. package/templates/en-US/docs/temp-reference/README.md +11 -0
  180. package/templates/en-US/docs.config.json +46 -0
  181. package/templates/en-US/profiles/README.md +23 -0
  182. package/templates/en-US/profiles/agent-platform/README.md +23 -0
  183. package/templates/en-US/profiles/cli-tool/README.md +23 -0
  184. package/templates/en-US/profiles/library-sdk/README.md +23 -0
  185. package/templates/en-US/profiles/multi-agent/README.md +23 -0
  186. package/templates/en-US/profiles/profiles.json +31 -0
  187. package/templates/en-US/profiles/software-automation/README.md +23 -0
  188. package/templates/en-US/profiles/web-saas/README.md +23 -0
  189. package/templates/en-US/scripts/README.md +89 -0
  190. package/templates/en-US/scripts/doc-find.mjs +156 -0
  191. package/templates/en-US/scripts/doc-map.mjs +50 -0
  192. package/templates/en-US/scripts/doc-tools.mjs +311 -0
  193. package/templates/en-US/scripts/init-docs.mjs +214 -0
  194. package/templates/en-US/scripts/validate-docs.mjs +141 -0
  195. package/templates/zh-CN/AGENTS.md +38 -0
  196. package/templates/zh-CN/DOCS_MAINTENANCE.md +77 -0
  197. package/templates/zh-CN/MIGRATION.md +45 -0
  198. package/templates/zh-CN/NEW_PROJECT_CHECKLIST.md +54 -0
  199. package/templates/zh-CN/README.md +55 -0
  200. package/templates/zh-CN/SESSION.md +29 -0
  201. package/templates/zh-CN/docs/00-context.md +42 -0
  202. package/templates/zh-CN/docs/01-vision/README.md +33 -0
  203. package/templates/zh-CN/docs/02-requirements/PRD.md +26 -0
  204. package/templates/zh-CN/docs/02-requirements/glossary.md +35 -0
  205. package/templates/zh-CN/docs/02-requirements/use-cases.md +31 -0
  206. package/templates/zh-CN/docs/03-architecture/composite-ai-framework.md +27 -0
  207. package/templates/zh-CN/docs/03-architecture/integration-architecture.md +30 -0
  208. package/templates/zh-CN/docs/03-architecture/system-architecture.md +26 -0
  209. package/templates/zh-CN/docs/04-design/README.md +21 -0
  210. package/templates/zh-CN/docs/04-design/a2a-integration-spec.md +45 -0
  211. package/templates/zh-CN/docs/04-design/agent-specs.md +46 -0
  212. package/templates/zh-CN/docs/04-design/data-model.md +18 -0
  213. package/templates/zh-CN/docs/04-design/external-api-spec.md +34 -0
  214. package/templates/zh-CN/docs/04-design/mcp-interface-spec.md +44 -0
  215. package/templates/zh-CN/docs/04-design/phase1-minimal-implementation-interfaces.md +38 -0
  216. package/templates/zh-CN/docs/04-design/responsibility-model.md +37 -0
  217. package/templates/zh-CN/docs/04-design/runtime-control-plane-spec.md +47 -0
  218. package/templates/zh-CN/docs/04-design/safety-governance.md +18 -0
  219. package/templates/zh-CN/docs/04-design/sample-scenarios-architecture-refinement.md +38 -0
  220. package/templates/zh-CN/docs/04-design/skill-syntax-spec.md +43 -0
  221. package/templates/zh-CN/docs/04-design/storage-schema.md +18 -0
  222. package/templates/zh-CN/docs/04-design/task-capability-architecture-and-evolution.md +46 -0
  223. package/templates/zh-CN/docs/05-project/adr/ADR-000-template.md +34 -0
  224. package/templates/zh-CN/docs/05-project/adr/README.md +35 -0
  225. package/templates/zh-CN/docs/05-project/doc-code-map.md +19 -0
  226. package/templates/zh-CN/docs/05-project/evolution-backlog.md +14 -0
  227. package/templates/zh-CN/docs/05-project/feature-registry.md +16 -0
  228. package/templates/zh-CN/docs/05-project/master-delivery-tracker.md +14 -0
  229. package/templates/zh-CN/docs/05-project/risk-register.md +21 -0
  230. package/templates/zh-CN/docs/05-project/roadmap.md +31 -0
  231. package/templates/zh-CN/docs/05-project/stage-view.md +14 -0
  232. package/templates/zh-CN/docs/05-project/tech-stack.md +36 -0
  233. package/templates/zh-CN/docs/06-dev-guide/SPEC.md +24 -0
  234. package/templates/zh-CN/docs/06-dev-guide/coding-standards.md +29 -0
  235. package/templates/zh-CN/docs/06-dev-guide/deployment-architecture.md +22 -0
  236. package/templates/zh-CN/docs/06-dev-guide/project-scaffold.md +16 -0
  237. package/templates/zh-CN/docs/06-dev-guide/testing-strategy.md +46 -0
  238. package/templates/zh-CN/docs/07-frontend/README.md +29 -0
  239. package/templates/zh-CN/docs/07-frontend/user-personas.md +27 -0
  240. package/templates/zh-CN/docs/08-process/README.md +29 -0
  241. package/templates/zh-CN/docs/08-process/ai-collaboration-protocol.md +30 -0
  242. package/templates/zh-CN/docs/08-process/autopilot.md +18 -0
  243. package/templates/zh-CN/docs/08-process/code-grounding.md +40 -0
  244. package/templates/zh-CN/docs/08-process/context-loading-strategy.md +35 -0
  245. package/templates/zh-CN/docs/08-process/conventions.md +77 -0
  246. package/templates/zh-CN/docs/08-process/debugging.md +27 -0
  247. package/templates/zh-CN/docs/08-process/design-gate.md +22 -0
  248. package/templates/zh-CN/docs/08-process/git-protocol.md +20 -0
  249. package/templates/zh-CN/docs/08-process/multi-agent-orchestration.md +27 -0
  250. package/templates/zh-CN/docs/08-process/planning.md +18 -0
  251. package/templates/zh-CN/docs/08-process/project-intake.md +53 -0
  252. package/templates/zh-CN/docs/08-process/reflection.md +18 -0
  253. package/templates/zh-CN/docs/08-process/review.md +30 -0
  254. package/templates/zh-CN/docs/08-process/session-handoff.md +29 -0
  255. package/templates/zh-CN/docs/08-process/tdd.md +24 -0
  256. package/templates/zh-CN/docs/08-process/tool-execution.md +34 -0
  257. package/templates/zh-CN/docs/08-process/workflow-contract.md +48 -0
  258. package/templates/zh-CN/docs/08-process/workflow.md +23 -0
  259. package/templates/zh-CN/docs/README.md +62 -0
  260. package/templates/zh-CN/docs/design-checklist.md +18 -0
  261. package/templates/zh-CN/docs/discussions/README.md +36 -0
  262. package/templates/zh-CN/docs/plans/README.md +15 -0
  263. package/templates/zh-CN/docs/proposed-design/README.md +41 -0
  264. package/templates/zh-CN/docs/temp-reference/README.md +13 -0
  265. package/templates/zh-CN/docs.config.json +46 -0
  266. package/templates/zh-CN/profiles/README.md +23 -0
  267. package/templates/zh-CN/profiles/agent-platform/README.md +23 -0
  268. package/templates/zh-CN/profiles/cli-tool/README.md +23 -0
  269. package/templates/zh-CN/profiles/library-sdk/README.md +23 -0
  270. package/templates/zh-CN/profiles/multi-agent/README.md +23 -0
  271. package/templates/zh-CN/profiles/profiles.json +31 -0
  272. package/templates/zh-CN/profiles/software-automation/README.md +23 -0
  273. package/templates/zh-CN/profiles/web-saas/README.md +23 -0
  274. package/templates/zh-CN/scripts/README.md +97 -0
  275. package/templates/zh-CN/scripts/doc-find.mjs +156 -0
  276. package/templates/zh-CN/scripts/doc-map.mjs +50 -0
  277. package/templates/zh-CN/scripts/doc-tools.mjs +311 -0
  278. package/templates/zh-CN/scripts/init-docs.mjs +214 -0
  279. package/templates/zh-CN/scripts/validate-docs.mjs +141 -0
@@ -0,0 +1,311 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export function isMain(url) {
6
+ if (!process.argv[1]) return false;
7
+ try { return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(url)); }
8
+ catch { return false; }
9
+ }
10
+
11
+ export const defaults = {
12
+ version: 1,
13
+ locale: 'en-US',
14
+ mode: 'project',
15
+ documentRoots: ['AGENTS.md', 'SESSION.md', 'DOCS_MAINTENANCE.md', 'docs'],
16
+ requiredFiles: ['AGENTS.md', 'SESSION.md', 'docs/00-context.md'],
17
+ exclude: ['.git', 'node_modules', '.cache', 'vendor', 'build', 'dist', '.worktrees', 'tmp', '99-source-archive'],
18
+ entryBudgets: {
19
+ 'AGENTS.md': { characters: 1400, lines: 50 },
20
+ 'SESSION.md': { characters: 1800, lines: 60 },
21
+ 'docs/00-context.md': { characters: 2200, lines: 80 },
22
+ },
23
+ };
24
+
25
+ export function normalize(text) {
26
+ return text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
27
+ }
28
+
29
+ export function inside(root, target) {
30
+ const rel = path.relative(root, target);
31
+ return rel === '' || (!path.isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + path.sep));
32
+ }
33
+
34
+ export function localPath(root, target, base = root) {
35
+ const resolved = path.resolve(base, target);
36
+ if (!inside(path.resolve(root), resolved)) throw new Error('Path escapes project: ' + target);
37
+ if (fs.existsSync(root)) {
38
+ let ancestor = resolved;
39
+ while (ancestor !== path.dirname(ancestor)) {
40
+ try {
41
+ if (fs.lstatSync(ancestor, { throwIfNoEntry: false })) break;
42
+ } catch (error) {
43
+ if (error.code === 'ENOTDIR') throw new Error('Target parent is not a directory: ' + target);
44
+ throw error;
45
+ }
46
+ ancestor = path.dirname(ancestor);
47
+ }
48
+ if (!inside(fs.realpathSync(root), fs.realpathSync(ancestor))) {
49
+ throw new Error('Symlink escapes project: ' + target);
50
+ }
51
+ }
52
+ return resolved;
53
+ }
54
+
55
+ export function readConfig(root) {
56
+ const file = path.join(root, 'docs.config.json');
57
+ const supplied = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')) : {};
58
+ if (!supplied || typeof supplied !== 'object' || Array.isArray(supplied)) throw new Error('Configuration must be an object');
59
+ for (const key of Object.keys(supplied)) {
60
+ if (!Object.hasOwn(defaults, key)) throw new Error('Unknown configuration field: ' + key);
61
+ }
62
+ const config = { ...defaults, ...supplied };
63
+ if (config.version !== 1) throw new Error('Unsupported configuration version');
64
+ if (!['template', 'project'].includes(config.mode)) throw new Error('mode must be template or project');
65
+ if (!['zh-CN', 'en-US'].includes(config.locale)) throw new Error('locale must be zh-CN or en-US');
66
+ for (const key of ['documentRoots', 'requiredFiles', 'exclude']) {
67
+ if (!Array.isArray(config[key]) || config[key].some(value => typeof value !== 'string' || !value)) {
68
+ throw new Error(key + ' must be an array of non-empty strings');
69
+ }
70
+ for (const name of config[key]) {
71
+ if (name !== '.' && (name.includes('\\') || path.isAbsolute(name) || /^[A-Za-z]:/.test(name) || name.split('/').some(part => !part || part === '.' || part === '..'))) {
72
+ throw new Error(key + ': Use normalized repository-relative paths: ' + name);
73
+ }
74
+ if (key !== 'exclude') localPath(root, name);
75
+ }
76
+ }
77
+ if (!config.entryBudgets || typeof config.entryBudgets !== 'object' || Array.isArray(config.entryBudgets)) {
78
+ throw new Error('entryBudgets must be an object');
79
+ }
80
+ for (const [name, budget] of Object.entries(config.entryBudgets)) {
81
+ if (!name || name.includes('\\') || path.isAbsolute(name) || /^[A-Za-z]:/.test(name) ||
82
+ name.split('/').some(part => !part || part === '.' || part === '..')) {
83
+ throw new Error('Budget keys require normalized repository-relative paths: ' + name);
84
+ }
85
+ localPath(root, name);
86
+ if (!budget || typeof budget !== 'object' || Array.isArray(budget)) throw new Error('Invalid budget: ' + name);
87
+ for (const [unit, value] of Object.entries(budget)) {
88
+ if (!['characters', 'lines'].includes(unit) || !Number.isInteger(value) || value < 1) {
89
+ throw new Error('Invalid budget: ' + name + '.' + unit);
90
+ }
91
+ }
92
+ }
93
+ return config;
94
+ }
95
+
96
+ export function documents(root, config) {
97
+ const found = new Set();
98
+ function visit(file) {
99
+ const name = relative(root, file);
100
+ if (config.exclude.some(entry => entry.includes('/')
101
+ ? name === entry || name.startsWith(entry + '/')
102
+ : name.split('/').includes(entry))) return;
103
+ if (!fs.existsSync(file)) return;
104
+ const stat = fs.lstatSync(file);
105
+ if (stat.isSymbolicLink()) return;
106
+ if (stat.isDirectory()) {
107
+ for (const item of fs.readdirSync(file).sort()) {
108
+ if (!config.exclude.includes(item)) visit(path.join(file, item));
109
+ }
110
+ } else if (stat.isFile() && file.endsWith('.md')) {
111
+ found.add(file);
112
+ }
113
+ }
114
+ for (const entry of config.documentRoots) {
115
+ const file = localPath(root, entry);
116
+ let current = file, symlink = false;
117
+ while (current !== root && inside(root, current)) {
118
+ if (fs.lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) { symlink = true; break; }
119
+ current = path.dirname(current);
120
+ }
121
+ if (!symlink) visit(file);
122
+ }
123
+ return [...found].sort();
124
+ }
125
+
126
+ function withoutComment(value) {
127
+ let quote = '';
128
+ const array = value.trimStart().startsWith('[');
129
+ let mayQuote = true;
130
+ for (let i = 0; i < value.length; i++) {
131
+ const c = value[i];
132
+ if (quote) {
133
+ if (c === '\\' && quote === '"') { i++; continue; }
134
+ if (c === quote) {
135
+ if (quote === "'" && value[i + 1] === "'") { i++; continue; }
136
+ quote = '';
137
+ mayQuote = false;
138
+ }
139
+ } else if ((c === '"' || c === "'") && mayQuote) quote = c;
140
+ else {
141
+ if (c === '#' && (i === 0 || /\s/.test(value[i - 1]))) return value.slice(0, i).trim();
142
+ if (!/\s/.test(c)) mayQuote = array && (c === '[' || c === ',');
143
+ }
144
+ }
145
+ return value.trim();
146
+ }
147
+
148
+ function scalar(value) {
149
+ value = withoutComment(value);
150
+ if (value.startsWith('"')) {
151
+ const parsed = JSON.parse(value);
152
+ if (typeof parsed !== 'string') throw new Error('Metadata scalars must be strings');
153
+ return parsed;
154
+ }
155
+ if (value.startsWith("'")) {
156
+ if (!/^'(?:[^']|'')*'$/.test(value)) throw new Error('Incomplete single-quoted string');
157
+ return value.slice(1, -1).replace(/''/g, "'");
158
+ }
159
+ if (/^[{[>|&*!]/.test(value)) throw new Error('Use plain scalars or string lists');
160
+ if (/^(?:-|\?)\s/.test(value)) throw new Error('Nested sequences or mappings are unsupported');
161
+ if (/:\s|:$/.test(value)) throw new Error('Nested mappings are unsupported; quote a literal string');
162
+ return value;
163
+ }
164
+
165
+ // Deliberately supports a documented flat subset, not arbitrary YAML.
166
+ export function parseDocument(input) {
167
+ const text = normalize(input);
168
+ const match = text.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
169
+ if (!match) return { meta: null, body: text, errors: text.startsWith('---\n') ? ['Unclosed front-matter'] : [] };
170
+ const meta = {};
171
+ const errors = [];
172
+ let listKey = null;
173
+ let listIndent = null;
174
+ for (const [index, raw] of match[1].split('\n').entries()) {
175
+ if (!raw.trim() || raw.trimStart().startsWith('#')) continue;
176
+ try {
177
+ const item = raw.match(/^( +)-\s+(.+)$/);
178
+ if (item) {
179
+ if (!listKey) throw new Error('List has no field');
180
+ if (listIndent !== null && item[1].length !== listIndent) throw new Error('Nested or inconsistent list indentation');
181
+ listIndent = item[1].length;
182
+ meta[listKey].push(scalar(item[2]));
183
+ continue;
184
+ }
185
+ const field = raw.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
186
+ if (!field) throw new Error('Nested or multiline metadata is unsupported; link separate evidence');
187
+ const [, key, rawValue] = field;
188
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) throw new Error('Unsupported metadata field: ' + key);
189
+ if (Object.hasOwn(meta, key)) throw new Error('Duplicate field: ' + key);
190
+ const value = withoutComment(rawValue);
191
+ listKey = null;
192
+ listIndent = null;
193
+ if (!value) { meta[key] = []; listKey = key; }
194
+ else if (value.startsWith('[')) {
195
+ const list = JSON.parse(value);
196
+ if (!Array.isArray(list) || list.some(v => typeof v !== 'string')) throw new Error('Lists must use JSON string arrays');
197
+ meta[key] = list;
198
+ } else meta[key] = scalar(value);
199
+ } catch (error) { errors.push('Metadata line ' + (index + 2) + ': ' + error.message); }
200
+ }
201
+ return { meta, body: text.slice(match[0].length), errors };
202
+ }
203
+
204
+ export function withoutCode(input) {
205
+ let fence = null;
206
+ return normalize(input).split('\n').map(line => {
207
+ const marker = line.match(/^ {0,3}([\x60~])\1{2,}/);
208
+ if (marker) {
209
+ if (!fence) fence = { char: marker[1], length: marker[0].trim().length };
210
+ else if (marker[1] === fence.char && marker[0].trim().length >= fence.length &&
211
+ line.slice(marker[0].length).trim() === '') fence = null;
212
+ return '';
213
+ }
214
+ return fence ? '' : line;
215
+ }).join('\n');
216
+ }
217
+
218
+ export function markdownLinks(body) {
219
+ const text = withoutCode(body).replace(/(\x60+)[^\n]*?\1/g, '');
220
+ const results = [];
221
+ const pattern = /!?\[[^\]\n]*\]\(\s*/g;
222
+ const unescape = value => value.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g, '$1');
223
+ for (const match of text.matchAll(pattern)) {
224
+ let start = match.index + match[0].length, end = start, suffix;
225
+ if (text[start] === '<') {
226
+ start++;
227
+ end = text.indexOf('>', start);
228
+ if (end < 0 || text.slice(start, end).includes('\n')) continue;
229
+ suffix = end + 1;
230
+ } else {
231
+ let depth = 0;
232
+ for (; end < text.length; end++) {
233
+ const char = text[end];
234
+ if (char === '\\') { end++; continue; }
235
+ if (char === '(') depth++;
236
+ else if (char === ')') {
237
+ if (depth === 0) break;
238
+ depth--;
239
+ } else if (/\s/.test(char)) break;
240
+ }
241
+ if (depth !== 0) continue;
242
+ suffix = end;
243
+ }
244
+ if (/^\s*(?:(?:"[^"\n]*"|'[^'\n]*'|\([^\n)]*\))\s*)?\)/.test(text.slice(suffix))) {
245
+ results.push(unescape(text.slice(start, end)));
246
+ }
247
+ }
248
+ for (const match of text.matchAll(/^\s{0,3}\[[^\]\n]+\]:\s*(<[^>\n]+>|\S+)/gm)) {
249
+ results.push(unescape(match[1].replace(/^<|>$/g, '')));
250
+ }
251
+ return results;
252
+ }
253
+
254
+ export function codeReferences(meta) {
255
+ const values = [];
256
+ for (const key of ['code_refs', 'code_owns']) {
257
+ if (meta?.[key] === undefined) continue;
258
+ if (!Array.isArray(meta[key]) || meta[key].some(v => typeof v !== 'string' || !v)) {
259
+ throw new Error(key + ' must be a list of path strings');
260
+ }
261
+ values.push(...meta[key]);
262
+ }
263
+ return [...new Set(values)];
264
+ }
265
+
266
+ export function globMatcher(pattern) {
267
+ if (!pattern || pattern.includes('\\') || pattern.startsWith('/') || /^[A-Za-z]:/.test(pattern) ||
268
+ pattern.split('/').some(part => !part || part === '.' || part === '..') || /[\[\]{}]/.test(pattern)) {
269
+ throw new Error('Code mappings require normalized root-relative paths with *, **, ?: ' + pattern);
270
+ }
271
+ const chars = Array.from(pattern), tokens = [];
272
+ for (let i = 0; i < chars.length; i++) {
273
+ const c = chars[i];
274
+ if (c === '*' && chars[i + 1] === '*') {
275
+ i++;
276
+ if (chars[i + 1] === '/') { i++; tokens.push({ kind: 'directories' }); }
277
+ else tokens.push({ kind: 'all' });
278
+ } else if (c === '*') tokens.push({ kind: 'segment' });
279
+ else if (c === '?') tokens.push({ kind: 'one' });
280
+ else tokens.push({ kind: 'literal', value: c });
281
+ }
282
+ // Dynamic programming bounds work by pattern length * path length;
283
+ // repeated wildcards must not cause exponential regex backtracking.
284
+ return { test(value) {
285
+ const input = Array.from(value);
286
+ let previous = new Uint8Array(input.length + 1);
287
+ previous[0] = 1;
288
+ for (const token of tokens) {
289
+ const next = new Uint8Array(input.length + 1);
290
+ if (['all', 'segment', 'directories'].includes(token.kind)) next[0] = previous[0];
291
+ let reachable = previous[0];
292
+ for (let j = 1; j <= input.length; j++) {
293
+ const char = input[j - 1];
294
+ if (token.kind === 'all' || token.kind === 'segment') {
295
+ next[j] = previous[j] || (next[j - 1] && (token.kind === 'all' || char !== '/'));
296
+ } else if (token.kind === 'directories') {
297
+ next[j] = previous[j] || (reachable && char === '/');
298
+ reachable ||= previous[j];
299
+ } else {
300
+ next[j] = previous[j - 1] && (token.kind === 'one' ? char !== '/' : char === token.value);
301
+ }
302
+ }
303
+ previous = next;
304
+ }
305
+ return Boolean(previous[input.length]);
306
+ } };
307
+ }
308
+
309
+ export function relative(root, file) {
310
+ return path.relative(root, file).split(path.sep).join('/');
311
+ }
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { defaults, localPath, normalize, readConfig, isMain } from './doc-tools.mjs';
7
+
8
+ const sourceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
9
+ const core = ['AGENTS.md', 'SESSION.md', 'docs/00-context.md', 'docs/README.md', 'DOCS_MAINTENANCE.md', 'docs/08-process/conventions.md'];
10
+ // Ship conditional route targets without making them mandatory reading.
11
+ const onDemand = ['docs/08-process/project-intake.md'];
12
+ const tooling = ['scripts/doc-tools.mjs', 'scripts/validate-docs.mjs', 'scripts/doc-map.mjs', 'scripts/doc-find.mjs', 'scripts/README.md'];
13
+ const manifestName = '.agentlock.json';
14
+ const digest = content => createHash('sha256').update(content).digest('hex');
15
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
16
+
17
+ // Reject lexical symlinks even when they resolve inside the project.
18
+ function destination(root, name) {
19
+ const file = localPath(root, name);
20
+ let current = file;
21
+ while (current !== path.dirname(root)) {
22
+ const stat = fs.lstatSync(current, { throwIfNoEntry: false });
23
+ if (stat?.isSymbolicLink()) throw new Error('Refusing symlink destination: ' + name);
24
+ if (current !== file && stat && !stat.isDirectory()) throw new Error('Target parent is not a directory: ' + name);
25
+ if (current === root) break;
26
+ current = path.dirname(current);
27
+ }
28
+ return file;
29
+ }
30
+
31
+ function readOwned(root, name, limit = 2 * 1024 * 1024) {
32
+ const file = destination(root, name);
33
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
34
+ if (!stat) return null;
35
+ if (!stat.isFile() || stat.size > limit) throw new Error('Not a bounded regular file: ' + name);
36
+ return fs.readFileSync(file);
37
+ }
38
+
39
+ function readManifest(root, locale, catalog, allowed) {
40
+ const content = readOwned(root, manifestName, 128 * 1024);
41
+ if (!content) throw new Error('Update requires an AgentLock manifest; migrate untracked projects manually');
42
+ const data = JSON.parse(content.toString('utf8'));
43
+ if (!object(data) || data.version !== 1 || data.locale !== locale || !object(data.files) ||
44
+ !/^[a-f0-9]{64}$/.test(data.sourceFingerprint ?? '') || !Array.isArray(data.profiles) || !data.profiles.length ||
45
+ data.profiles.some(name => typeof name !== 'string' || !Object.hasOwn(catalog, name)) ||
46
+ Object.keys(data).some(key => !['version', 'locale', 'profiles', 'sourceFingerprint', 'files'].includes(key))) {
47
+ throw new Error('Invalid manifest schema or locale');
48
+ }
49
+ for (const [name, entry] of Object.entries(data.files)) {
50
+ const kind = tooling.includes(name) ? 'managed' : 'seed';
51
+ if (!allowed.has(name) || !object(entry) || entry.kind !== kind || !/^[a-f0-9]{64}$/.test(entry.sha256 ?? '') ||
52
+ Object.keys(entry).some(key => !['kind', 'sha256'].includes(key))) throw new Error('Invalid manifest ownership/path: ' + name);
53
+ destination(root, name);
54
+ }
55
+ return { data, content };
56
+ }
57
+
58
+ export function initialize(target, options = {}) {
59
+ const sourceConfig = readConfig(sourceRoot);
60
+ const zh = sourceConfig.locale === 'zh-CN';
61
+ const profile = options.profile ?? 'minimal';
62
+ const catalog = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'profiles/profiles.json'), 'utf8'));
63
+ if (!Object.hasOwn(catalog, profile) || !Array.isArray(catalog[profile])) throw new Error('Unknown profile: ' + profile);
64
+ const root = path.resolve(target);
65
+ if (fs.existsSync(root) && !fs.statSync(root).isDirectory()) throw new Error('Target is not a directory: ' + root);
66
+ const allowed = new Set([...core, ...onDemand, ...tooling, ...Object.values(catalog).flat(), 'docs.config.json']);
67
+ const previous = options.update ? readManifest(root, sourceConfig.locale, catalog, allowed) : null;
68
+ const profiles = [...new Set([...(previous?.data.profiles ?? []), profile])].sort();
69
+ const files = [...new Set([...core, ...onDemand, ...tooling, ...profiles.flatMap(name => catalog[name])])];
70
+ const outputs = new Map();
71
+ for (const name of files) {
72
+ const source = localPath(sourceRoot, name);
73
+ localPath(root, name);
74
+ outputs.set(name, normalize(fs.readFileSync(source, 'utf8')));
75
+ }
76
+ const index = [
77
+ '---', 'status: Draft', 'owner: project-owner', '---', '',
78
+ zh ? '# 已启用文档' : '# Enabled Documents', '',
79
+ zh ? '本页由初始化器按所选配置建立。样板内容尚需核验,文档存在不代表功能存在。' : 'Selected templates still need verification. A document does not prove implementation.', '',
80
+ zh ? '默认入口:[协作规则](../AGENTS.md)、[当前快照](../SESSION.md)、[任务路由](00-context.md)。' : 'Start with [collaboration rules](../AGENTS.md), [current snapshot](../SESSION.md), and [engineering routes](00-context.md).', '',
81
+ zh ? '项目实际使用的需求、任务、接口与决策来源:待填写。' : 'Actual requirements, tasks, contracts, and decisions: TBD.', '',
82
+ zh ? '## 按需查阅' : '## On Demand', '',
83
+ zh ? '- [维护规则](../DOCS_MAINTENANCE.md)' : '- [Maintenance rules](../DOCS_MAINTENANCE.md)',
84
+ zh ? '- [按主题或代码路径检索文档](../scripts/README.md)' : '- [Find documents by topic or code path](../scripts/README.md)',
85
+ ];
86
+ for (const name of files.filter(name => name.startsWith('docs/') && name.endsWith('.md') && name !== 'docs/README.md')) {
87
+ const title = outputs.get(name).match(/^#\s+(.+)$/m)?.[1] ?? name;
88
+ index.push('- [' + title + '](' + name.slice(5) + ')');
89
+ }
90
+ outputs.set('docs/README.md', index.join('\n') + '\n');
91
+ outputs.set('docs.config.json', JSON.stringify({
92
+ ...defaults,
93
+ locale: sourceConfig.locale,
94
+ mode: 'project',
95
+ entryBudgets: sourceConfig.entryBudgets,
96
+ documentRoots: [...defaults.documentRoots, 'scripts/README.md'],
97
+ }, null, 2) + '\n');
98
+
99
+ const changes = [], observed = new Map(), nextFiles = { ...(previous?.data.files ?? {}) };
100
+ for (const [name, content] of outputs) {
101
+ const file = destination(root, name);
102
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
103
+ if (!options.update && stat) throw new Error('Refusing to overwrite existing file: ' + name);
104
+ const entry = previous?.data.files[name];
105
+ const kind = tooling.includes(name) ? 'managed' : 'seed';
106
+ let action, reason;
107
+ if (options.update && kind === 'seed' && (entry || stat)) {
108
+ action = 'preserve'; reason = entry ? 'Project-owned seed' : 'Untracked project document';
109
+ } else if (!stat) action = 'add';
110
+ else if (!entry) { action = 'conflict'; reason = 'Unknown tool ownership'; }
111
+ else {
112
+ let current;
113
+ try { current = readOwned(root, name); }
114
+ catch (error) { action = 'conflict'; reason = error.message; }
115
+ if (current) {
116
+ observed.set(name, current);
117
+ const hash = digest(current);
118
+ if (hash !== entry.sha256) { action = 'conflict'; reason = 'Managed file modified locally'; }
119
+ else action = hash === digest(content) ? 'unchanged' : 'update';
120
+ }
121
+ }
122
+ changes.push({ path: name, action, ...(reason ? { reason } : {}) });
123
+ if (['add', 'update', 'unchanged'].includes(action)) nextFiles[name] = { kind, sha256: digest(content) };
124
+ }
125
+ const next = {
126
+ version: 1, locale: sourceConfig.locale, profiles,
127
+ sourceFingerprint: digest(JSON.stringify([...outputs])),
128
+ files: Object.fromEntries(Object.entries(nextFiles).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)),
129
+ };
130
+ const manifestText = JSON.stringify(next, null, 2) + '\n';
131
+ const manifestFile = destination(root, manifestName);
132
+ if (!previous && fs.lstatSync(manifestFile, { throwIfNoEntry: false })) throw new Error('Refusing to overwrite existing manifest');
133
+ if (previous) observed.set(manifestName, previous.content);
134
+ outputs.set(manifestName, manifestText);
135
+ changes.push({ path: manifestName, action: !previous ? 'add' : previous.content.equals(Buffer.from(manifestText)) ? 'unchanged' : 'update' });
136
+ const pending = changes.filter(row => ['add', 'update'].includes(row.action));
137
+ const writtenFiles = [], attemptedFiles = [];
138
+ let failedFile;
139
+ function recheck(row) {
140
+ const file = destination(root, row.path);
141
+ if (row.action === 'add') {
142
+ if (fs.lstatSync(file, { throwIfNoEntry: false })) throw new Error('Destination changed after preview: ' + row.path);
143
+ } else {
144
+ const now = readOwned(root, row.path);
145
+ if (!now || !now.equals(observed.get(row.path))) throw new Error('Destination changed after preview: ' + row.path);
146
+ }
147
+ return file;
148
+ }
149
+ if (options.write) {
150
+ if (changes.some(row => row.action === 'conflict')) {
151
+ throw Object.assign(new Error('Update conflicts; no files written'), { changes, writtenFiles });
152
+ }
153
+ // Validate the complete plan again; per-file rechecks reduce, but do not eliminate, external-editor races.
154
+ for (const row of pending) recheck(row);
155
+ try {
156
+ for (const row of pending) {
157
+ failedFile = row.path;
158
+ const file = recheck(row);
159
+ fs.mkdirSync(path.dirname(file), { recursive: true });
160
+ attemptedFiles.push(row.path);
161
+ if (row.action === 'add') {
162
+ destination(root, row.path);
163
+ fs.writeFileSync(file, outputs.get(row.path), { encoding: 'utf8', flag: 'wx' });
164
+ } else {
165
+ const temporary = file + '.agentlock-' + randomUUID();
166
+ try {
167
+ fs.writeFileSync(temporary, outputs.get(row.path), { encoding: 'utf8', flag: 'wx', mode: fs.statSync(file).mode });
168
+ recheck(row);
169
+ fs.renameSync(temporary, file);
170
+ } finally {
171
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
172
+ }
173
+ }
174
+ writtenFiles.push(row.path);
175
+ }
176
+ } catch (error) { throw Object.assign(error, { writtenFiles, attemptedFiles, failedFile, changes }); }
177
+ }
178
+ return { target: root, profile, profiles, written: writtenFiles.length > 0, writtenFiles, files: [...outputs.keys()], changes };
179
+ }
180
+
181
+ function main() {
182
+ const args = process.argv.slice(2);
183
+ let target, profile = 'minimal', write = false, update = false, json = false;
184
+ for (let i = 0; i < args.length; i++) {
185
+ if (args[i] === '--help') {
186
+ console.log('node scripts/init-docs.mjs <target> [--profile name] [--update] [--write] [--json]');
187
+ return;
188
+ }
189
+ if (args[i] === '--profile') profile = args[++i] ?? '';
190
+ else if (args[i] === '--write') write = true;
191
+ else if (args[i] === '--update') update = true;
192
+ else if (args[i] === '--json') json = true;
193
+ else if (!args[i].startsWith('-') && !target) target = args[i];
194
+ else throw new Error('Unknown argument: ' + args[i]);
195
+ }
196
+ if (!target) throw new Error('Target directory required; preview is default, use --write to create files');
197
+ const result = initialize(target, { profile, write, update });
198
+ if (json) { console.log(JSON.stringify(result)); return; }
199
+ console.log((result.written ? 'Written' : write ? 'No changes' : 'Preview only') + ': ' + result.target + ' (' + result.profiles.join(', ') + ')');
200
+ for (const row of result.changes) console.log('- ' + row.action + ': ' + row.path + (row.reason ? ' (' + row.reason + ')' : ''));
201
+ console.log('Project facts still need verification. Structure checks do not prove implementation or acceptance.');
202
+ }
203
+ if (isMain(import.meta.url)) {
204
+ try { main(); } catch (error) {
205
+ if (process.argv.includes('--json')) console.log(JSON.stringify({ error: error.message, writtenFiles: error.writtenFiles ?? [],
206
+ attemptedFiles: error.attemptedFiles ?? [], ...(error.failedFile ? { failedFile: error.failedFile } : {}), ...(error.changes ? { changes: error.changes } : {}) }));
207
+ else {
208
+ console.error(error.message);
209
+ if (error.writtenFiles?.length) console.error('Written before failure: ' + error.writtenFiles.join(', '));
210
+ if (error.failedFile) console.error('Inspect attempted file (may be partial): ' + error.failedFile);
211
+ }
212
+ process.exitCode = 1;
213
+ }
214
+ }
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { normalize, localPath, readConfig, documents, parseDocument, withoutCode, markdownLinks, codeReferences, globMatcher, relative, isMain } from './doc-tools.mjs';
5
+
6
+ const states = new Set(['Current', 'Draft', 'Unverified', 'Superseded', 'Archived']);
7
+
8
+ function validDate(value) {
9
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) &&
10
+ Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
11
+ }
12
+
13
+ export function validate(root, options = {}) {
14
+ root = path.resolve(root);
15
+ const errors = [], warnings = [];
16
+ const config = readConfig(root);
17
+ const mode = options.mode ?? config.mode;
18
+ if (!['template', 'project'].includes(mode)) throw new Error('mode must be template or project');
19
+ if (!fs.existsSync(root)) throw new Error('Project directory does not exist: ' + root);
20
+ for (const name of config.requiredFiles) {
21
+ const file = localPath(root, name);
22
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) errors.push('Missing required entry: ' + name);
23
+ }
24
+ const files = documents(root, config), loaded = new Map(), edges = new Map();
25
+ for (const file of files) {
26
+ const name = relative(root, file);
27
+ const text = normalize(fs.readFileSync(file, 'utf8'));
28
+ const parsed = parseDocument(text);
29
+ loaded.set(name, parsed);
30
+ errors.push(...parsed.errors.map(error => name + ': ' + error));
31
+ const { meta, body } = parsed;
32
+ if (!meta) {
33
+ if (config.requiredFiles.includes(name)) errors.push(name + ': Missing front-matter');
34
+ else if (mode === 'project') warnings.push(name + ': No document status yet');
35
+ } else {
36
+ if (!states.has(meta.status)) errors.push(name + ': Invalid status');
37
+ if (typeof meta.owner !== 'string' || !meta.owner.trim()) errors.push(name + ': Missing owner');
38
+ if (meta.status === 'Current') {
39
+ if (!validDate(meta.last_verified)) errors.push(name + ': Current needs valid last_verified');
40
+ if (mode === 'project' && /待填写|YYYY-MM-DD|F-xxx|\bTODO\b|\bTBD\b|\bto be filled\b/i.test(withoutCode(body))) {
41
+ errors.push(name + ': Current still contains placeholders');
42
+ }
43
+ } else if (mode === 'project' && ['Draft', 'Unverified'].includes(meta.status)) {
44
+ warnings.push(name + ': ' + meta.status + ': content needs verification; this is not implementation evidence');
45
+ }
46
+ if (meta.status === 'Superseded' && !meta.superseded_by) errors.push(name + ': Missing superseded_by');
47
+ if (meta.superseded_by) {
48
+ if (typeof meta.superseded_by !== 'string') errors.push(name + ': superseded_by must be a path');
49
+ else if (!fs.existsSync(localPath(root, meta.superseded_by))) errors.push(name + ': Replacement document does not exist');
50
+ }
51
+ if (meta.kind === 'process' && (typeof meta.trigger !== 'string' || !meta.trigger)) {
52
+ errors.push(name + ': Process document missing trigger');
53
+ }
54
+ if (meta.kind === 'task') {
55
+ const text = withoutCode(body);
56
+ for (const [zh, en] of [['目标', 'Goal'], ['范围', 'Allowed Changes'], ['验收与验证', 'Required Validation']]) {
57
+ if (!new RegExp('^##\\s+(?:' + zh + '|' + en + ')\\s*$', 'm').test(text)) {
58
+ errors.push(name + ': Task missing heading ' + zh);
59
+ }
60
+ }
61
+ }
62
+ const deps = meta.must_read_with ?? [];
63
+ if (!Array.isArray(deps) || deps.some(dep => typeof dep !== 'string' || !dep)) {
64
+ errors.push(name + ': must_read_with must be a path list');
65
+ } else {
66
+ try { edges.set(name, deps.map(dep => relative(root, localPath(root, dep)))); }
67
+ catch (error) { errors.push(name + ': ' + error.message); }
68
+ }
69
+ try {
70
+ for (const ref of codeReferences(meta)) {
71
+ globMatcher(ref);
72
+ if (mode !== 'project') continue;
73
+ const prefix = ref.split(/[*?]/)[0];
74
+ const probe = /[*?]/.test(ref) ? prefix.slice(0, prefix.lastIndexOf('/') + 1) : ref;
75
+ if (probe && !fs.existsSync(localPath(root, probe))) warnings.push(name + ': Code reference not found: ' + ref);
76
+ }
77
+ } catch (error) { errors.push(name + ': ' + error.message); }
78
+ }
79
+ for (const target of markdownLinks(body)) {
80
+ if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:|#|\/\/)/.test(target)) continue;
81
+ try {
82
+ const clean = decodeURIComponent(target.split(/[?#]/)[0]);
83
+ if (clean && !fs.existsSync(localPath(root, clean, path.dirname(file)))) {
84
+ errors.push(name + ': Broken link -> ' + target);
85
+ }
86
+ } catch (error) { errors.push(name + ': ' + error.message); }
87
+ }
88
+ const budget = config.entryBudgets[name];
89
+ if (budget) {
90
+ const characters = Array.from(text).length;
91
+ const lines = text.trimEnd().split('\n').length;
92
+ if (budget.characters && characters > budget.characters) warnings.push(name + ': Character budget exceeded ' + characters + '/' + budget.characters);
93
+ if (budget.lines && lines > budget.lines) warnings.push(name + ': Line budget exceeded ' + lines + '/' + budget.lines);
94
+ }
95
+ }
96
+ for (const name of config.requiredFiles) {
97
+ if (!loaded.has(name) && fs.existsSync(localPath(root, name))) errors.push('Required entry not included in documentRoots: ' + name);
98
+ }
99
+ const visited = new Set(), active = [];
100
+ function visit(name) {
101
+ if (active.includes(name)) { errors.push('Required-reading dependency cycle: ' + [...active, name].join(' -> ')); return; }
102
+ if (visited.has(name)) return;
103
+ active.push(name);
104
+ for (const dep of edges.get(name) ?? []) {
105
+ if (!loaded.has(dep)) errors.push(name + ': Required-reading dependency unavailable: ' + dep);
106
+ else visit(dep);
107
+ }
108
+ active.pop();
109
+ visited.add(name);
110
+ }
111
+ for (const name of edges.keys()) visit(name);
112
+ return { mode, files: files.length, errors, warnings };
113
+ }
114
+
115
+ function main() {
116
+ const args = process.argv.slice(2);
117
+ let root = '.', mode, json = false, strict = false;
118
+ let hasRoot = false;
119
+ for (let i = 0; i < args.length; i++) {
120
+ if (args[i] === '--help') {
121
+ console.log('node scripts/validate-docs.mjs [root] [--mode template|project] [--strict] [--json]');
122
+ return;
123
+ }
124
+ if (args[i] === '--mode') mode = args[++i] ?? '';
125
+ else if (args[i] === '--json') json = true;
126
+ else if (args[i] === '--strict') strict = true;
127
+ else if (!args[i].startsWith('-') && !hasRoot) { root = args[i]; hasRoot = true; }
128
+ else throw new Error('Unknown argument: ' + args[i]);
129
+ }
130
+ const result = validate(root, { mode });
131
+ if (json) console.log(JSON.stringify(result, null, 2));
132
+ else {
133
+ for (const warning of result.warnings) console.log('Warning: ' + warning);
134
+ for (const error of result.errors) console.error('Error: ' + error);
135
+ console.log('Documentation structure check ' + (result.errors.length || (strict && result.warnings.length) ? 'failed' : 'passed') + ' (' + result.files + ' files). This does not prove implementation or acceptance.');
136
+ }
137
+ if (result.errors.length || (strict && result.warnings.length)) process.exitCode = 1;
138
+ }
139
+ if (isMain(import.meta.url)) {
140
+ try { main(); } catch (error) { console.error(error.message); process.exitCode = 1; }
141
+ }