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,860 @@
1
+ /**
2
+ * AgentLock Harness v3.5.0 — UI Backend Service Layer
3
+ *
4
+ * Strictly reuses `src/core/*` and `src/cli/commands/*` without duplicating business logic.
5
+ * Zero third-party dependencies. Never writes UI files into target repositories.
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ import { pathToFileURL } from "node:url";
11
+ import { PKG_VERSION } from "../core/version.mjs";
12
+ import {
13
+ HARNESS_MODES,
14
+ DOMAIN_PROFILES,
15
+ VALID_HOSTS,
16
+ CLI_AGENTS,
17
+ AGENTS,
18
+ TECH_STACKS,
19
+ parseHostsOption,
20
+ } from "../core/catalog.mjs";
21
+ import { scanRepository, discoverSpecs, getProfileDocs, VALID_DOCS_STRATEGIES } from "../core/adopt.mjs";
22
+ import { detectEnvironment } from "../core/detector.mjs";
23
+ import { resolveInstallCommand } from "../core/installer.mjs";
24
+ import {
25
+ REPO_ROOT,
26
+ HARNESS_CONFIG_FILE,
27
+ HARNESS_DIR,
28
+ assertSafeDestination,
29
+ } from "../core/harness-writer.mjs";
30
+ import { checkRulesDrift, compileRules, loadSourceRules } from "../core/rules-compiler.mjs";
31
+ import {
32
+ CHANGES_DIR_REL,
33
+ validateSlug,
34
+ createChange,
35
+ inspectChange,
36
+ listChanges,
37
+ archiveChange,
38
+ } from "../core/change-flow.mjs";
39
+ import {
40
+ readLedger,
41
+ hasDependencyCycle,
42
+ computeReadyTasks,
43
+ addTask,
44
+ claimTask,
45
+ releaseTask,
46
+ blockTask,
47
+ completeTask,
48
+ } from "../core/task-ledger.mjs";
49
+ import { computeStats } from "../core/audit.mjs";
50
+ import { detectWorkingTreeDocDrift } from "../core/doc-drift.mjs";
51
+ import { EVAL_CASES, EVAL_SUITES } from "../core/eval-fixtures.mjs";
52
+ import {
53
+ VALID_ARMS,
54
+ VALID_EVAL_DRIVERS,
55
+ checkDriverAvailability,
56
+ runEvalSuite,
57
+ } from "../core/eval-runner.mjs";
58
+ import { runAdopt } from "../cli/commands/adopt.mjs";
59
+ import { runInit } from "../cli/commands/init.mjs";
60
+ import { runHooks } from "../cli/commands/hooks.mjs";
61
+
62
+ const CLI_BIN = path.join(REPO_ROOT, "bin/agentlock-harness.mjs");
63
+
64
+ // eslint-disable-next-line no-control-regex
65
+ const ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/g;
66
+
67
+ export function stripAnsi(text) {
68
+ return String(text || "").replace(ANSI_RE, "");
69
+ }
70
+
71
+ function cleanChildEnv() {
72
+ const env = { ...process.env };
73
+ delete env.NODE_TEST_CONTEXT;
74
+ return env;
75
+ }
76
+
77
+ export function validateWorkspaceDir(rawPath) {
78
+ if (!rawPath || typeof rawPath !== "string") {
79
+ throw new Error("Workspace path is required.");
80
+ }
81
+ const trimmed = rawPath.trim();
82
+ if (!trimmed) throw new Error("Workspace path cannot be empty.");
83
+ const resolved = path.resolve(trimmed);
84
+ if (!fs.existsSync(resolved)) {
85
+ throw new Error(`Directory does not exist: ${resolved}`);
86
+ }
87
+ const stat = fs.statSync(resolved);
88
+ if (!stat.isDirectory()) {
89
+ throw new Error(`Path is not a directory: ${resolved}`);
90
+ }
91
+ return resolved;
92
+ }
93
+
94
+ async function loadV1Validator() {
95
+ const modPath = path.join(REPO_ROOT, "templates/zh-CN/scripts/validate-docs.mjs");
96
+ return import(pathToFileURL(modPath).href);
97
+ }
98
+
99
+ function readJsonSafe(filePath) {
100
+ if (!fs.existsSync(filePath)) return null;
101
+ try {
102
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ export function classifyDirectory(targetDir) {
109
+ const entries = fs.readdirSync(targetDir).filter((name) => name !== ".DS_Store");
110
+ const nonGitEntries = entries.filter((name) => name !== ".git");
111
+ const hasHarness = fs.existsSync(path.join(targetDir, HARNESS_CONFIG_FILE));
112
+ const hasV1 = fs.existsSync(path.join(targetDir, ".agentlock.json")) || fs.existsSync(path.join(targetDir, "docs.config.json"));
113
+ const isEmpty = nonGitEntries.length === 0;
114
+ return {
115
+ isEmpty,
116
+ hasHarness,
117
+ hasV1,
118
+ hasGit: entries.includes(".git"),
119
+ kind: hasHarness ? "adopted" : isEmpty ? "empty" : "brownfield",
120
+ entryCount: nonGitEntries.length,
121
+ };
122
+ }
123
+
124
+ function readEntryBudgets(targetDir, explicitLocale = null) {
125
+ const docsCfg = readJsonSafe(path.join(targetDir, "docs.config.json"));
126
+ const cfgBudgets = docsCfg?.entryBudgets || {};
127
+ const baseLines = {
128
+ "AGENTS.md": 50,
129
+ "SESSION.md": 60,
130
+ "docs/00-context.md": 80,
131
+ };
132
+ const zhChars = {
133
+ "AGENTS.md": 1400,
134
+ "SESSION.md": 1800,
135
+ "docs/00-context.md": 2200,
136
+ };
137
+ const enChars = {
138
+ "AGENTS.md": 3600,
139
+ "SESSION.md": 4000,
140
+ "docs/00-context.md": 4400,
141
+ };
142
+
143
+ return Object.keys(baseLines).map((relPath) => {
144
+ const absPath = path.join(targetDir, relPath);
145
+ const exists = fs.existsSync(absPath);
146
+ const content = exists ? fs.readFileSync(absPath, "utf-8") : "";
147
+ const inferredLocale =
148
+ docsCfg?.locale ||
149
+ explicitLocale ||
150
+ (exists && !/[\u3400-\u9fff]/.test(content) ? "en-US" : "zh-CN");
151
+ const isEn = inferredLocale === "en-US";
152
+ const maxLines = cfgBudgets[relPath]?.lines || cfgBudgets[relPath]?.maxLines || baseLines[relPath];
153
+ const maxChars =
154
+ cfgBudgets[relPath]?.characters ||
155
+ cfgBudgets[relPath]?.maxChars ||
156
+ (isEn ? enChars[relPath] : zhChars[relPath]);
157
+
158
+ if (!exists) {
159
+ return {
160
+ path: relPath,
161
+ exists: false,
162
+ detectedLocale: inferredLocale,
163
+ lines: 0,
164
+ chars: 0,
165
+ maxLines,
166
+ maxChars,
167
+ lineRatio: 0,
168
+ charRatio: 0,
169
+ status: "missing",
170
+ };
171
+ }
172
+ const lines = content === "" ? 0 : content.replace(/\r\n/g, "\n").split("\n").length;
173
+ const chars = [...content].length;
174
+ const lineRatio = Number((lines / maxLines).toFixed(3));
175
+ const charRatio = Number((chars / maxChars).toFixed(3));
176
+ const worst = Math.max(lineRatio, charRatio);
177
+ const status = worst > 1 ? "over" : worst >= 0.85 ? "warn" : "ok";
178
+ return {
179
+ path: relPath,
180
+ exists: true,
181
+ detectedLocale: inferredLocale,
182
+ lines,
183
+ chars,
184
+ maxLines,
185
+ maxChars,
186
+ lineRatio,
187
+ charRatio,
188
+ status,
189
+ };
190
+ });
191
+ }
192
+
193
+ export function getWorkspaceMeta(targetDir) {
194
+ const dirInfo = classifyDirectory(targetDir);
195
+ const harnessCfg = readJsonSafe(path.join(targetDir, HARNESS_CONFIG_FILE));
196
+ const scan = scanRepository(targetDir);
197
+ return {
198
+ version: PKG_VERSION,
199
+ workspace: targetDir,
200
+ workspaceName: path.basename(targetDir) || targetDir,
201
+ dirInfo,
202
+ harnessConfig: harnessCfg,
203
+ scan,
204
+ catalog: {
205
+ modes: Object.values(HARNESS_MODES),
206
+ profiles: DOMAIN_PROFILES.map((p) => ({
207
+ ...p,
208
+ docs: getProfileDocs(p.value, harnessCfg?.locale || "zh-CN"),
209
+ })),
210
+ docsStrategies: VALID_DOCS_STRATEGIES,
211
+ hosts: VALID_HOSTS,
212
+ cliAgents: CLI_AGENTS,
213
+ agents: AGENTS,
214
+ stacks: TECH_STACKS,
215
+ },
216
+ };
217
+ }
218
+
219
+ export async function getHealthSnapshot(targetDir) {
220
+ const dirInfo = classifyDirectory(targetDir);
221
+ const harnessCfg = readJsonSafe(path.join(targetDir, HARNESS_CONFIG_FILE));
222
+ const explicitLocale = harnessCfg?.locale === "en-US" || harnessCfg?.locale === "zh-CN" ? harnessCfg.locale : null;
223
+ const budgets = readEntryBudgets(targetDir, explicitLocale);
224
+ const specDiscovery = discoverSpecs(targetDir);
225
+ const scan = scanRepository(targetDir);
226
+ const isAdopted = Boolean(dirInfo.hasHarness || dirInfo.hasV1);
227
+
228
+ // 1. v1 document validation (only for repos that actually adopted v1 docs.config.json / .agentlock.json)
229
+ let v1Docs = { checked: false, files: 0, errors: [], warnings: [] };
230
+ const hasV1Config = fs.existsSync(path.join(targetDir, "docs.config.json"));
231
+ const hasV1Manifest = fs.existsSync(path.join(targetDir, ".agentlock.json"));
232
+ if (hasV1Config || hasV1Manifest) {
233
+ try {
234
+ const { validate } = await loadV1Validator();
235
+ const res = validate(targetDir, { mode: "project" });
236
+ v1Docs = {
237
+ checked: true,
238
+ files: res.files,
239
+ errors: res.errors || [],
240
+ warnings: res.warnings || [],
241
+ };
242
+ } catch (err) {
243
+ v1Docs = {
244
+ checked: true,
245
+ files: 0,
246
+ errors: [err.message],
247
+ warnings: [],
248
+ };
249
+ }
250
+ }
251
+
252
+ // 2. Rules drift status
253
+ const hosts = Array.isArray(harnessCfg?.hosts) ? harnessCfg.hosts : null;
254
+ let rules = { sourceCount: 0, ok: true, driftCount: 0, missing: [], drifted: [], stale: [], sources: [] };
255
+ try {
256
+ const sourceRules = loadSourceRules(targetDir);
257
+ if (sourceRules.length > 0 && harnessCfg?.mode !== "docs-only") {
258
+ const drift = checkRulesDrift(targetDir, { hosts });
259
+ rules = {
260
+ sourceCount: sourceRules.length,
261
+ ok: drift.ok,
262
+ driftCount: drift.missing.length + drift.drifted.length + drift.stale.length,
263
+ missing: drift.missing,
264
+ drifted: drift.drifted,
265
+ stale: drift.stale,
266
+ sources: sourceRules.map((r) => ({
267
+ id: r.id,
268
+ relPath: r.relPath,
269
+ alwaysApply: r.alwaysApply,
270
+ globs: r.globs,
271
+ })),
272
+ };
273
+ }
274
+ } catch (err) {
275
+ rules = { ...rules, ok: false, error: err.message };
276
+ }
277
+
278
+ // 3. Git Hooks status
279
+ const hooks = runHooks("status", { target: targetDir, quiet: true });
280
+
281
+ // 4. Changes & Tasks summary
282
+ const changes = listWorkspaceChanges(targetDir);
283
+ const ledger = readLedger(targetDir);
284
+ const readyTasks = computeReadyTasks(ledger.tasks);
285
+ let hasCycle = false;
286
+ for (const t of ledger.tasks) {
287
+ if (hasDependencyCycle(ledger.tasks, t.id, t.dependsOn || [])) {
288
+ hasCycle = true;
289
+ break;
290
+ }
291
+ }
292
+
293
+ // 5. Audit telemetry stats & working-tree doc-code drift
294
+ const stats = computeStats(targetDir);
295
+ const docDrift = await detectWorkingTreeDocDrift(targetDir);
296
+
297
+ // 6. Build explicit, de-duplicated diagnostics list (no black-box counts)
298
+ const critical = [];
299
+ const advisory = [];
300
+
301
+ for (const err of v1Docs.errors) {
302
+ critical.push({ category: "v1-docs", message: err });
303
+ }
304
+ if (!rules.ok) {
305
+ const parts = [
306
+ ...(rules.missing || []).map((p) => `missing: ${p}`),
307
+ ...(rules.drifted || []).map((p) => `drifted: ${p}`),
308
+ ...(rules.stale || []).map((p) => `stale: ${p}`),
309
+ ];
310
+ critical.push({
311
+ category: "rules",
312
+ message: rules.error || `Rule drift detected (${parts.slice(0, 4).join(", ")})`,
313
+ });
314
+ }
315
+ if (hasCycle) {
316
+ critical.push({ category: "tasks", message: "DAG task ledger contains a dependency cycle (.agentlock-harness/tasks.json)" });
317
+ }
318
+
319
+ for (const w of v1Docs.warnings) {
320
+ advisory.push({ category: "v1-docs", message: w });
321
+ }
322
+
323
+ // Entry budgets are advisory (per AgentLock v1 rule); avoid duplicating budget warnings already in v1Docs.warnings
324
+ const v1WarnJoined = v1Docs.warnings.join("\n");
325
+ for (const b of budgets) {
326
+ if (!b.exists) continue;
327
+ if (b.status === "over" && !v1WarnJoined.includes(`${b.path}:`)) {
328
+ advisory.push({
329
+ category: "budget",
330
+ message: `${b.path}: exceeds entry budget (${b.lines}/${b.maxLines}L, ${b.chars}/${b.maxChars}C)`,
331
+ });
332
+ } else if (b.status === "warn" && !v1WarnJoined.includes(`${b.path}:`)) {
333
+ advisory.push({
334
+ category: "budget",
335
+ message: `${b.path}: approaching entry budget (${b.lines}/${b.maxLines}L, ${b.chars}/${b.maxChars}C)`,
336
+ });
337
+ }
338
+ }
339
+
340
+ const activeChangesWithPendingAc = changes.active.filter((ch) => !ch.readyToArchive);
341
+ for (const ch of activeChangesWithPendingAc) {
342
+ advisory.push({
343
+ category: "changes",
344
+ message: `Active change "${ch.slug}" has ${ch.acceptance.open} unchecked acceptance item(s)`,
345
+ });
346
+ }
347
+ if (harnessCfg && harnessCfg.mode !== "docs-only" && !harnessCfg.commands?.test) {
348
+ advisory.push({
349
+ category: "backpressure",
350
+ message: "agentlock-harness.json commands.test is empty (code test backpressure inactive)",
351
+ });
352
+ }
353
+ for (const d of docDrift.staleDocs) {
354
+ advisory.push({
355
+ category: "doc-drift",
356
+ message: `${d.document} may be stale (code edited: ${d.matchedCodeFiles.join(", ")})`,
357
+ });
358
+ }
359
+
360
+ const level = !isAdopted
361
+ ? "unadopted"
362
+ : critical.length > 0
363
+ ? "error"
364
+ : advisory.length > 0
365
+ ? "warn"
366
+ : "healthy";
367
+
368
+ return {
369
+ version: PKG_VERSION,
370
+ workspace: targetDir,
371
+ dirInfo,
372
+ harnessConfig: harnessCfg,
373
+ detectedStacks: scan.detectedStacks,
374
+ budgets,
375
+ v1Docs,
376
+ docDrift,
377
+ specDiscovery,
378
+ rules,
379
+ hooks,
380
+ changesSummary: {
381
+ activeCount: changes.active.length,
382
+ archivedCount: changes.archived.length,
383
+ pendingAcCount: activeChangesWithPendingAc.length,
384
+ },
385
+ tasksSummary: {
386
+ total: ledger.tasks.length,
387
+ ready: readyTasks.length,
388
+ inProgress: ledger.tasks.filter((t) => t.status === "in_progress").length,
389
+ done: ledger.tasks.filter((t) => t.status === "done").length,
390
+ blocked: ledger.tasks.filter((t) => t.status === "blocked").length,
391
+ hasCycle,
392
+ },
393
+ stats,
394
+ diagnostics: {
395
+ critical,
396
+ advisory,
397
+ },
398
+ summaryStatus: {
399
+ level,
400
+ criticalIssues: critical.length,
401
+ advisoryIssues: advisory.length,
402
+ },
403
+ };
404
+ }
405
+
406
+ export function getDoctorReport(modeId = null) {
407
+ const filterIds = modeId && HARNESS_MODES[modeId] ? HARNESS_MODES[modeId].recommendedTools : null;
408
+ const env = detectEnvironment(filterIds);
409
+ return {
410
+ ...env,
411
+ tools: env.tools.map((t) => ({
412
+ ...t,
413
+ resolvedInstallCmd: resolveInstallCommand(t, env.pkgManagers),
414
+ })),
415
+ };
416
+ }
417
+
418
+ export function installSingleTool(toolId, { dryRun = false } = {}) {
419
+ const env = detectEnvironment([toolId]);
420
+ const tool = env.tools[0];
421
+ if (!tool) {
422
+ throw new Error(`Unknown tool id: ${toolId}`);
423
+ }
424
+ if (tool.installed) {
425
+ return { ok: true, alreadyInstalled: true, toolId, version: tool.version };
426
+ }
427
+ const cmd = resolveInstallCommand(tool, env.pkgManagers);
428
+ if (!cmd) {
429
+ throw new Error(`No automatic install command configured for "${toolId}" on ${process.platform}.`);
430
+ }
431
+ if (dryRun) {
432
+ return { ok: true, dryRun: true, toolId, command: cmd };
433
+ }
434
+ const res = spawnSync(cmd, {
435
+ shell: true,
436
+ stdio: ["ignore", "pipe", "pipe"],
437
+ encoding: "utf-8",
438
+ maxBuffer: 16 * 1024 * 1024,
439
+ env: cleanChildEnv(),
440
+ timeout: 180_000,
441
+ });
442
+ return {
443
+ ok: res.status === 0,
444
+ toolId,
445
+ command: cmd,
446
+ exitCode: res.status,
447
+ stdout: stripAnsi(res.stdout || "").slice(-4000),
448
+ stderr: stripAnsi(res.stderr || "").slice(-4000),
449
+ };
450
+ }
451
+
452
+ export function buildAdoptCliCommand(targetDir, opts = {}) {
453
+ const parts = ["alh", "adopt", `"${targetDir}"`];
454
+ if (opts.lean !== false) parts.push("--lean");
455
+ if (opts.mode && opts.mode !== "dual-core") parts.push("--mode", opts.mode);
456
+ if (opts.profile) parts.push("--profile", opts.profile);
457
+ if (opts.docsStrategy === "archive-switch") {
458
+ parts.push("--docs-strategy", "archive-switch");
459
+ if (!opts.dryRun && opts.confirmArchive) parts.push("--confirm-archive");
460
+ }
461
+ if (opts.locale === "en-US") parts.push("--locale", "en-US");
462
+ if (Array.isArray(opts.hosts) && opts.hosts.length > 0) parts.push("--hosts", opts.hosts.join(","));
463
+ if (opts.withSkills) parts.push("--with-skills");
464
+ if (opts.noGitHooks) parts.push("--no-git-hooks");
465
+ if (opts.dryRun) parts.push("--dry-run");
466
+ return parts.join(" ");
467
+ }
468
+
469
+ export function buildInitCliCommand(targetDir, opts = {}) {
470
+ const parts = ["alh", "init", `"${targetDir}"`];
471
+ parts.push("--mode", opts.mode || "dual-core");
472
+ parts.push("--profile", opts.profile || "minimal");
473
+ parts.push("--stack", opts.stack || "node-ts");
474
+ if (opts.locale === "en-US") parts.push("--locale", "en-US");
475
+ if (Array.isArray(opts.hosts) && opts.hosts.length > 0) parts.push("--hosts", opts.hosts.join(","));
476
+ if (opts.lean !== false) parts.push("--lean");
477
+ if (opts.installGitHooks) parts.push("--install-git-hooks");
478
+ if (opts.dryRun) parts.push("--dry-run");
479
+ parts.push("-y");
480
+ return parts.join(" ");
481
+ }
482
+
483
+ export async function runAdoptAction(targetDir, opts = {}, { dryRun = true } = {}) {
484
+ const hosts = Array.isArray(opts.hosts) && opts.hosts.length > 0 ? parseHostsOption(opts.hosts.join(",")) : undefined;
485
+ const docsStrategy = VALID_DOCS_STRATEGIES.includes(opts.docsStrategy) ? opts.docsStrategy : "thin-route";
486
+ const flags = {
487
+ target: targetDir,
488
+ locale: opts.locale === "en-US" ? "en-US" : "zh-CN",
489
+ mode: opts.mode || "dual-core",
490
+ profile: opts.profile || undefined,
491
+ docsStrategy,
492
+ confirmArchive: Boolean(opts.confirmArchive),
493
+ hosts: hosts ? hosts.join(",") : undefined,
494
+ lean: opts.lean !== false,
495
+ withSkills: Boolean(opts.withSkills),
496
+ noGitHooks: Boolean(opts.noGitHooks),
497
+ force: Boolean(opts.force),
498
+ skipEnvCheck: Boolean(opts.skipEnvCheck),
499
+ dryRun,
500
+ json: true,
501
+ silent: true,
502
+ };
503
+ const summary = await runAdopt(flags);
504
+ return {
505
+ ...summary,
506
+ cliCommand: buildAdoptCliCommand(targetDir, { ...opts, docsStrategy, hosts: summary.hosts || hosts, dryRun }),
507
+ };
508
+ }
509
+
510
+ export async function runInitAction(targetDir, opts = {}, { dryRun = false } = {}) {
511
+ const hosts = Array.isArray(opts.hosts) && opts.hosts.length > 0 ? parseHostsOption(opts.hosts.join(",")) : ["codex"];
512
+ // Silence stdout during in-process runInit call
513
+ const origLog = console.log;
514
+ const origErr = console.error;
515
+ const logs = [];
516
+ console.log = (...args) => logs.push(stripAnsi(args.join(" ")));
517
+ console.error = (...args) => logs.push(stripAnsi(args.join(" ")));
518
+ try {
519
+ const result = await runInit({
520
+ target: targetDir,
521
+ yes: true,
522
+ dryRun,
523
+ locale: opts.locale === "en-US" ? "en-US" : "zh-CN",
524
+ mode: opts.mode || "dual-core",
525
+ profile: opts.profile || "minimal",
526
+ stack: opts.stack || "node-ts",
527
+ hosts: hosts.join(","),
528
+ lean: opts.lean !== false,
529
+ noSkills: opts.lean !== false && !opts.withSkills,
530
+ installGitHooks: Boolean(opts.installGitHooks),
531
+ primary: opts.primary || undefined,
532
+ reviewer: opts.reviewer || undefined,
533
+ force: Boolean(opts.force),
534
+ });
535
+ return {
536
+ ...result,
537
+ logs,
538
+ cliCommand: buildInitCliCommand(targetDir, { ...opts, hosts, dryRun }),
539
+ };
540
+ } finally {
541
+ console.log = origLog;
542
+ console.error = origErr;
543
+ }
544
+ }
545
+
546
+ export function compileWorkspaceRules(targetDir) {
547
+ const cfg = readJsonSafe(path.join(targetDir, HARNESS_CONFIG_FILE));
548
+ const hosts = Array.isArray(cfg?.hosts) ? cfg.hosts : null;
549
+ const res = compileRules(targetDir, { hosts, write: true, clean: true });
550
+ return {
551
+ ok: true,
552
+ ...res,
553
+ cliCommand: `alh rules compile "${targetDir}"`,
554
+ };
555
+ }
556
+
557
+ export function toggleWorkspaceHooks(targetDir, { enable, force = false } = {}) {
558
+ const action = enable ? "install" : "uninstall";
559
+ const res = runHooks(action, { target: targetDir, force: Boolean(force), quiet: true });
560
+ return {
561
+ ...res,
562
+ action,
563
+ status: runHooks("status", { target: targetDir, quiet: true }),
564
+ cliCommand: `alh hooks ${action} "${targetDir}"`,
565
+ };
566
+ }
567
+
568
+ export function parseAcceptanceChecklist(markdown) {
569
+ const lines = String(markdown || "").replace(/\r\n/g, "\n").split("\n");
570
+ const items = [];
571
+ lines.forEach((line, idx) => {
572
+ const m = line.match(/^(\s*-\s+\[)([ xX])(\]\s*)(.*)$/);
573
+ if (m) {
574
+ items.push({
575
+ lineIndex: idx,
576
+ checked: m[2].toLowerCase() === "x",
577
+ text: m[4].trim(),
578
+ });
579
+ }
580
+ });
581
+ return items;
582
+ }
583
+
584
+ function normalizeAcceptance(acc) {
585
+ const done = acc?.done ?? 0;
586
+ const open = acc?.open ?? 0;
587
+ return { done, open, checked: done, total: done + open };
588
+ }
589
+
590
+ export function readChangeDetail(targetDir, rawSlug) {
591
+ const slug = validateSlug(rawSlug);
592
+ const inspected = inspectChange(targetDir, slug);
593
+ const changeDir = assertSafeDestination(targetDir, `${CHANGES_DIR_REL}/${slug}`);
594
+ const deltaPath = path.join(changeDir, "delta.md");
595
+ const accPath = path.join(changeDir, "acceptance.md");
596
+ const delta = fs.existsSync(deltaPath) ? fs.readFileSync(deltaPath, "utf-8") : "";
597
+ const acceptance = fs.existsSync(accPath) ? fs.readFileSync(accPath, "utf-8") : "";
598
+ return {
599
+ ...inspected,
600
+ acceptance: normalizeAcceptance(inspected.acceptance),
601
+ delta,
602
+ acceptanceText: acceptance,
603
+ checklist: parseAcceptanceChecklist(acceptance),
604
+ };
605
+ }
606
+
607
+ export function saveChangeDetail(targetDir, rawSlug, { delta, acceptance, toggleLineIndex, checked } = {}) {
608
+ const slug = validateSlug(rawSlug);
609
+ inspectChange(targetDir, slug);
610
+ const changeDir = assertSafeDestination(targetDir, `${CHANGES_DIR_REL}/${slug}`);
611
+ const deltaPath = path.join(changeDir, "delta.md");
612
+ const accPath = path.join(changeDir, "acceptance.md");
613
+
614
+ if (typeof delta === "string") {
615
+ fs.writeFileSync(deltaPath, delta, "utf-8");
616
+ }
617
+ if (typeof acceptance === "string") {
618
+ fs.writeFileSync(accPath, acceptance, "utf-8");
619
+ } else if (Number.isInteger(toggleLineIndex) && fs.existsSync(accPath)) {
620
+ const lines = fs.readFileSync(accPath, "utf-8").replace(/\r\n/g, "\n").split("\n");
621
+ if (toggleLineIndex >= 0 && toggleLineIndex < lines.length) {
622
+ lines[toggleLineIndex] = lines[toggleLineIndex].replace(
623
+ /^(\s*-\s+\[)([ xX])(\])/,
624
+ (_, p1, cur, p3) => {
625
+ const next = typeof checked === "boolean" ? (checked ? "x" : " ") : cur === " " ? "x" : " ";
626
+ return `${p1}${next}${p3}`;
627
+ }
628
+ );
629
+ fs.writeFileSync(accPath, lines.join("\n"), "utf-8");
630
+ }
631
+ }
632
+ return readChangeDetail(targetDir, slug);
633
+ }
634
+
635
+ export function createWorkspaceChange(targetDir, { slug, title = "", locale = "zh-CN" } = {}) {
636
+ const res = createChange(targetDir, slug, { title, locale });
637
+ return {
638
+ ...res,
639
+ detail: readChangeDetail(targetDir, res.slug),
640
+ cliCommand: `alh change new ${res.slug}${title ? ` --title "${title.replace(/"/g, '\\"')}"` : ""}`,
641
+ };
642
+ }
643
+
644
+ export function archiveWorkspaceChange(targetDir, slug, { force = false, syncSpec = true } = {}) {
645
+ const res = archiveChange(targetDir, slug, { force: Boolean(force), syncSpec: syncSpec !== false });
646
+ return {
647
+ ...res,
648
+ cliCommand: `alh change archive ${validateSlug(slug)}${syncSpec === false ? " --no-sync-spec" : ""}${force ? " --force" : ""}`,
649
+ };
650
+ }
651
+
652
+ export function listWorkspaceChanges(targetDir) {
653
+ const listed = listChanges(targetDir, { includeArchived: true });
654
+ return {
655
+ active: (listed.active || []).map((c) => ({ ...c, acceptance: normalizeAcceptance(c.acceptance) })),
656
+ archived: listed.archived || [],
657
+ };
658
+ }
659
+
660
+ export function getWorkspaceTasks(targetDir) {
661
+ const ledger = readLedger(targetDir);
662
+ const ready = computeReadyTasks(ledger.tasks);
663
+ const readyIds = new Set(ready.map((t) => t.id));
664
+ let hasCycle = false;
665
+ for (const t of ledger.tasks) {
666
+ if (hasDependencyCycle(ledger.tasks, t.id, t.dependsOn || [])) {
667
+ hasCycle = true;
668
+ break;
669
+ }
670
+ }
671
+ return {
672
+ tasks: ledger.tasks.map((t) => ({
673
+ ...t,
674
+ isReady: readyIds.has(t.id),
675
+ })),
676
+ readyCount: ready.length,
677
+ hasCycle,
678
+ };
679
+ }
680
+
681
+ export function createWorkspaceTask(targetDir, { title, priority = "P1", dependsOn = [], change = null } = {}) {
682
+ const deps = Array.isArray(dependsOn)
683
+ ? dependsOn.map((d) => String(d).trim()).filter(Boolean)
684
+ : String(dependsOn || "")
685
+ .split(",")
686
+ .map((s) => s.trim())
687
+ .filter(Boolean);
688
+ const task = addTask(targetDir, { title, priority, dependsOn: deps, change: change || null });
689
+ return {
690
+ ok: true,
691
+ task,
692
+ cliCommand: `alh task add "${String(title || "").replace(/"/g, '\\"')}" --priority ${priority}${deps.length ? ` --depends ${deps.join(",")}` : ""}`,
693
+ };
694
+ }
695
+
696
+ export function performTaskAction(targetDir, id, action, payload = {}) {
697
+ let task;
698
+ if (action === "claim") {
699
+ task = claimTask(targetDir, id, { owner: payload.owner || "ui-user", force: Boolean(payload.force) });
700
+ } else if (action === "done") {
701
+ task = completeTask(targetDir, id, { evidence: payload.evidence || "" });
702
+ } else if (action === "release") {
703
+ task = releaseTask(targetDir, id);
704
+ } else if (action === "block") {
705
+ task = blockTask(targetDir, id, { reason: payload.reason || "" });
706
+ } else {
707
+ throw new Error(`Unsupported task action: ${action}`);
708
+ }
709
+ return {
710
+ ok: true,
711
+ task,
712
+ cliCommand: `alh task ${action} ${id}`,
713
+ };
714
+ }
715
+
716
+ export function getEvalCatalog() {
717
+ const cases = Object.values(EVAL_CASES).map((cs) => ({
718
+ id: cs.id,
719
+ category: cs.category,
720
+ title: cs.title,
721
+ zhTitle: cs.zhTitle,
722
+ description: cs.description,
723
+ }));
724
+ const drivers = VALID_EVAL_DRIVERS.map((id) => ({
725
+ id,
726
+ ...checkDriverAvailability(id),
727
+ isSimulator: id.startsWith("mock-"),
728
+ }));
729
+ return {
730
+ suites: EVAL_SUITES,
731
+ arms: VALID_ARMS,
732
+ cases,
733
+ drivers,
734
+ };
735
+ }
736
+
737
+ export function listLocalEvalReports(targetDir) {
738
+ const candidates = [];
739
+ const searchDirs = [
740
+ path.join(targetDir, HARNESS_DIR, "eval-reports"),
741
+ path.join(targetDir, "eval-reports"),
742
+ path.join(REPO_ROOT, "tmp"),
743
+ ];
744
+ for (const dir of searchDirs) {
745
+ if (!fs.existsSync(dir)) continue;
746
+ let entries;
747
+ try {
748
+ entries = fs.readdirSync(dir, { withFileTypes: true });
749
+ } catch {
750
+ continue;
751
+ }
752
+ for (const ent of entries) {
753
+ const full = path.join(dir, ent.name);
754
+ if (ent.isFile() && ent.name.endsWith(".json") && ent.name.includes("report")) {
755
+ candidates.push(full);
756
+ } else if (ent.isDirectory()) {
757
+ const nested = path.join(full, "report.json");
758
+ if (fs.existsSync(nested)) candidates.push(nested);
759
+ }
760
+ }
761
+ }
762
+ const seen = new Set();
763
+ const reports = [];
764
+ for (const filePath of candidates) {
765
+ const resolved = path.resolve(filePath);
766
+ if (seen.has(resolved)) continue;
767
+ seen.add(resolved);
768
+ const data = readJsonSafe(resolved);
769
+ if (!data || !Array.isArray(data.runs)) continue;
770
+ const stat = fs.statSync(resolved);
771
+ reports.push({
772
+ id: Buffer.from(resolved).toString("base64url"),
773
+ path: resolved,
774
+ name: path.basename(path.dirname(resolved)) + "/" + path.basename(resolved),
775
+ mtime: stat.mtime.toISOString(),
776
+ agent: data.agent,
777
+ cases: data.cases || [],
778
+ arms: data.arms || [],
779
+ isSimulator: Boolean(data.isSimulator || String(data.agent || "").startsWith("mock-")),
780
+ report: data,
781
+ });
782
+ }
783
+ reports.sort((a, b) => b.mtime.localeCompare(a.mtime));
784
+ return reports.slice(0, 20);
785
+ }
786
+
787
+ export function spawnCliStream(args, { cwd = REPO_ROOT } = {}, onEvent = () => {}) {
788
+ return new Promise((resolve) => {
789
+ const child = spawn(process.execPath, [CLI_BIN, ...args], {
790
+ cwd,
791
+ stdio: ["ignore", "pipe", "pipe"],
792
+ env: cleanChildEnv(),
793
+ });
794
+ let stdoutBuf = "";
795
+ let stderrBuf = "";
796
+
797
+ const emitLines = (streamName, chunk) => {
798
+ const text = stripAnsi(chunk.toString("utf-8"));
799
+ if (streamName === "stdout") stdoutBuf += text;
800
+ else stderrBuf += text;
801
+ for (const line of text.split(/\r?\n/)) {
802
+ if (line.length > 0) onEvent({ type: "log", stream: streamName, line });
803
+ }
804
+ };
805
+
806
+ child.stdout.on("data", (d) => emitLines("stdout", d));
807
+ child.stderr.on("data", (d) => emitLines("stderr", d));
808
+
809
+ child.on("error", (err) => {
810
+ onEvent({ type: "error", message: err.message });
811
+ resolve({ ok: false, exitCode: 1, error: err.message });
812
+ });
813
+
814
+ child.on("close", (code) => {
815
+ resolve({
816
+ ok: code === 0,
817
+ exitCode: code ?? 1,
818
+ stdout: stdoutBuf.slice(-24000),
819
+ stderr: stderrBuf.slice(-12000),
820
+ });
821
+ });
822
+ });
823
+ }
824
+
825
+ export async function runEvalStream(opts = {}, onEvent = () => {}) {
826
+ const suiteKey = opts.suite && EVAL_SUITES[opts.suite] ? opts.suite : "core";
827
+ const cases = Array.isArray(opts.cases) && opts.cases.length > 0 ? opts.cases : EVAL_SUITES[suiteKey];
828
+ const arms = Array.isArray(opts.arms) && opts.arms.length > 0 ? opts.arms : ["baseline", "v1", "v3"];
829
+ const agent = VALID_EVAL_DRIVERS.includes(opts.agent) ? opts.agent : "mock-oracle";
830
+ const repeats = Math.max(1, Math.min(3, Number.parseInt(opts.repeats || 1, 10) || 1));
831
+
832
+ const cliCommand = `alh eval run --suite ${suiteKey} --agent ${agent} --compare ${arms.join(",")}${repeats > 1 ? ` --repeats ${repeats}` : ""}`;
833
+ onEvent({
834
+ type: "start",
835
+ suite: suiteKey,
836
+ cases,
837
+ arms,
838
+ agent,
839
+ repeats,
840
+ totalRuns: cases.length * arms.length * repeats,
841
+ cliCommand,
842
+ });
843
+
844
+ const result = await runEvalSuite({
845
+ cases,
846
+ arms,
847
+ agent,
848
+ repeats,
849
+ timeoutSec: Math.max(30, Math.min(600, Number.parseInt(opts.timeout || 360, 10) || 360)),
850
+ locale: opts.locale === "zh-CN" ? "zh-CN" : "en-US",
851
+ onRunComplete: (runRecord, index, total) => {
852
+ onEvent({ type: "progress", index, total, run: runRecord });
853
+ },
854
+ });
855
+
856
+ return {
857
+ ...result,
858
+ cliCommand,
859
+ };
860
+ }