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,754 @@
1
+ /**
2
+ * AgentLock Harness v3.2 — Dumbbell Zero-Tax Behavioral Ablation Evaluation Engine (`alh eval`)
3
+ *
4
+ * Key v3.2 evolution (driven by real `codex-cli 0.172.0` ablation telemetry):
5
+ * - Dumbbell Zero-Tax `v3` Arm:
6
+ * * Context layer is as lean as `v1` (single target host adapter, zero redundant 6-host file noise,
7
+ * opt-in L2 skills via `--with-skills`, zero duplicate ADR summaries, zero extra prompt hops).
8
+ * * Deterministic shell runs silently outside the model's token budget (OS sandbox / L4 hooks /
9
+ * universal Git Hooks / full cross-package backpressure).
10
+ * - Suites: `core` (E03–E15), `hard` (H01–H04), `frontier` (F01–F03), `all` (12 cases).
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import { spawnSync } from "node:child_process";
17
+ import { EVAL_CASES, EVAL_SUITES, sha256 } from "./eval-fixtures.mjs";
18
+ import { REPO_ROOT, applyHarnessFiles, HARNESS_CONFIG_FILE, HARNESS_DIR } from "./harness-writer.mjs";
19
+ import { compileRules } from "./rules-compiler.mjs";
20
+ import { buildAgentInvocation } from "./agent-runner.mjs";
21
+ import { parseDriverTelemetry, aggregateTelemetry, formatTokenCount } from "./eval-telemetry.mjs";
22
+ import { addTask } from "./task-ledger.mjs";
23
+ import { DEFAULT_AGENT_FLAGS, CLI_AGENTS, VALID_HOSTS } from "./catalog.mjs";
24
+
25
+ export const VALID_ARMS = ["baseline", "v1", "v3"];
26
+ export const VALID_EVAL_DRIVERS = ["claude", "codex", "gemini", "mock-oracle", "mock-naive"];
27
+ const META_REL = ".git/alh-eval-meta.json";
28
+
29
+ function git(cwd, args) {
30
+ const res = spawnSync("git", args, { cwd, encoding: "utf-8" });
31
+ if (res.status !== 0) {
32
+ throw new Error(`git ${args.join(" ")} failed: ${res.stderr || res.stdout}`);
33
+ }
34
+ return (res.stdout || "").trim();
35
+ }
36
+
37
+ async function loadV1Initializer(locale) {
38
+ const modPath = path.join(REPO_ROOT, "templates", locale, "scripts", "init-docs.mjs");
39
+ return import(pathToFileURL(modPath).href);
40
+ }
41
+
42
+ export function checkDriverAvailability(agent) {
43
+ if (agent.startsWith("mock-")) return { available: true, version: "builtin-simulator" };
44
+ const res = spawnSync(agent, ["--version"], {
45
+ encoding: "utf-8",
46
+ shell: process.platform === "win32",
47
+ timeout: 5000,
48
+ });
49
+ if (res.error || res.status !== 0) {
50
+ return {
51
+ available: false,
52
+ version: null,
53
+ error: res.error?.message || (res.stderr || res.stdout || "").trim() || `exit code ${res.status}`,
54
+ };
55
+ }
56
+ const firstLine = (res.stdout || res.stderr || "").trim().split(/\r?\n/)[0] || "detected";
57
+ return { available: true, version: firstLine };
58
+ }
59
+
60
+ export async function materializeFixture(
61
+ caseId,
62
+ targetDir,
63
+ {
64
+ arm = "baseline",
65
+ locale = "en-US",
66
+ force = false,
67
+ targetAgent = null,
68
+ fullHosts = false,
69
+ withSkills = null,
70
+ } = {}
71
+ ) {
72
+ const spec = EVAL_CASES[caseId];
73
+ if (!spec) throw new Error(`Unknown eval case: ${caseId}`);
74
+ const normArm = arm === "harness" ? "v3" : arm;
75
+ if (!VALID_ARMS.includes(normArm)) throw new Error(`Unknown eval arm: ${arm} (valid: ${VALID_ARMS.join(", ")})`);
76
+
77
+ const absDir = path.resolve(targetDir);
78
+ if (fs.existsSync(absDir) && fs.readdirSync(absDir).length > 0 && !force) {
79
+ throw new Error(`Refusing to scaffold eval fixture into non-empty directory: ${absDir} (pass --force to override)`);
80
+ }
81
+ fs.mkdirSync(absDir, { recursive: true });
82
+
83
+ // 1. Write fixture source files
84
+ for (const [rel, content] of Object.entries(spec.files)) {
85
+ const full = path.join(absDir, rel);
86
+ fs.mkdirSync(path.dirname(full), { recursive: true });
87
+ fs.writeFileSync(full, content, "utf-8");
88
+ }
89
+
90
+ // 2. Apply v1 / v3 scaffolding
91
+ if (normArm === "v1" || normArm === "v3") {
92
+ const sessionAbs = path.join(absDir, "SESSION.md");
93
+ const preSeededSession = fs.existsSync(sessionAbs) ? fs.readFileSync(sessionAbs, "utf-8") : null;
94
+ if (preSeededSession !== null) fs.unlinkSync(sessionAbs);
95
+
96
+ const { initialize } = await loadV1Initializer(locale);
97
+ initialize(absDir, { profile: "minimal", write: true, update: false });
98
+
99
+ if (preSeededSession !== null) {
100
+ fs.writeFileSync(sessionAbs, preSeededSession, "utf-8");
101
+ }
102
+
103
+ const routes = Array.isArray(spec.contextRoutes) ? spec.contextRoutes : [spec.contextHint];
104
+ const ctxPath = path.join(absDir, "docs/00-context.md");
105
+ const ctxContent = [
106
+ "---",
107
+ "status: Current",
108
+ "owner: eval-fixture",
109
+ "last_verified: 2026-11-30",
110
+ "---",
111
+ "",
112
+ `# ${spec.id} Engineering Routes`,
113
+ "",
114
+ "| Area | Active Entrypoint | Consumers | Verification | Notes |",
115
+ "|---|---|---|---|---|",
116
+ ...routes,
117
+ "",
118
+ ].join("\n");
119
+ fs.writeFileSync(ctxPath, ctxContent, "utf-8");
120
+ }
121
+
122
+ if (normArm === "v3") {
123
+ const modeId = spec.v3Mode || "dual-core";
124
+ const pkgJson = JSON.parse(spec.files["package.json"]);
125
+ const testCmd = pkgJson?.scripts?.test || "node --test";
126
+
127
+ // Dumbbell zero-tax selection: when running against a real single CLI agent (unless --full-hosts),
128
+ // install ONLY that agent's host adapter and skip default .agents/skills/ discovery bloat!
129
+ const isSingleRealCli = Boolean(targetAgent && CLI_AGENTS.includes(targetAgent) && !fullHosts);
130
+ const hosts = isSingleRealCli ? [targetAgent] : [...VALID_HOSTS];
131
+ const includeSkills = withSkills !== null ? Boolean(withSkills) : !isSingleRealCli;
132
+ const includeStarterRules = !isSingleRealCli || targetAgent === "claude";
133
+
134
+ const vars = {
135
+ PROJECT_NAME: `eval-${spec.id.toLowerCase()}`,
136
+ LOCALE: locale,
137
+ MODE_ID: modeId,
138
+ MODE_NAME: modeId === "enterprise-platform" ? "Enterprise Platform" : "Dual-Core Harness",
139
+ PROFILE_ID: "minimal",
140
+ HOSTS_JSON: JSON.stringify(hosts),
141
+ INCLUDE_SKILLS_JSON: JSON.stringify(includeSkills),
142
+ TECH_STACK: "Node.js",
143
+ STACK_ID: "node-ts",
144
+ MARKER_FILES_JSON: JSON.stringify(["package.json"]),
145
+ PRIMARY_AGENT: targetAgent && CLI_AGENTS.includes(targetAgent) ? targetAgent : "claude",
146
+ REVIEWER_AGENT: targetAgent === "codex" ? "claude" : "codex",
147
+ AGENT_FLAGS_JSON: JSON.stringify(DEFAULT_AGENT_FLAGS, null, 2).replace(/\n/g, "\n "),
148
+ BUILD_CMD: "",
149
+ LINT_CMD: "",
150
+ TYPECHECK_CMD: "",
151
+ TEST_CMD: testCmd,
152
+ };
153
+
154
+ applyHarnessFiles(absDir, modeId, vars, {
155
+ locale,
156
+ hosts,
157
+ includeSkills,
158
+ includeStarterRules,
159
+ write: true,
160
+ });
161
+
162
+ if (includeStarterRules && Array.isArray(spec.v3Rules)) {
163
+ for (const r of spec.v3Rules) {
164
+ const rp = path.join(absDir, HARNESS_DIR, "rules", r.filename);
165
+ fs.mkdirSync(path.dirname(rp), { recursive: true });
166
+ fs.writeFileSync(rp, r.content, "utf-8");
167
+ }
168
+ }
169
+ if (includeStarterRules) {
170
+ compileRules(absDir, { hosts, write: true, clean: true });
171
+ }
172
+
173
+ if (Array.isArray(spec.v3Tasks)) {
174
+ for (const t of spec.v3Tasks) {
175
+ addTask(absDir, t);
176
+ }
177
+ }
178
+ }
179
+
180
+ // 3. Initialize isolated Git repo and commit clean baseline
181
+ git(absDir, ["init"]);
182
+ git(absDir, ["config", "user.name", "AgentLock Eval"]);
183
+ git(absDir, ["config", "user.email", "eval@agentlock-harness.local"]);
184
+ git(absDir, ["add", "-A"]);
185
+ git(absDir, ["commit", "-m", `eval fixture baseline (${spec.id} / ${normArm})`]);
186
+ const baseSha = git(absDir, ["rev-parse", "HEAD"]);
187
+
188
+ // 4. Activate Universal Git Hooks AFTER baseline commit in `v3` when fixture tests Git commit safety/backpressure
189
+ if (normArm === "v3" && spec.installGitHooks) {
190
+ // Also wire stop-gate into pre-commit for commit-time regression backpressure (e.g. F01 Merkle contract)
191
+ const preCommitPath = path.join(absDir, HARNESS_DIR, "git-hooks/pre-commit");
192
+ if (fs.existsSync(preCommitPath)) {
193
+ const pc = fs.readFileSync(preCommitPath, "utf-8");
194
+ if (!pc.includes("stop-gate.mjs")) {
195
+ fs.writeFileSync(
196
+ preCommitPath,
197
+ pc + '\nif [ -f ".agentlock-harness/hooks/stop-gate.mjs" ]; then\n node .agentlock-harness/hooks/stop-gate.mjs\nfi\n',
198
+ { encoding: "utf-8", mode: 0o755 }
199
+ );
200
+ }
201
+ }
202
+ git(absDir, ["config", "--local", "core.hooksPath", `${HARNESS_DIR}/git-hooks`]);
203
+ }
204
+
205
+ // 5. Record hidden watched initial file hashes inside .git/alh-eval-meta.json
206
+ const initialHashes = {};
207
+ for (const rel of spec.watchedHashes || []) {
208
+ const full = path.join(absDir, rel);
209
+ if (fs.existsSync(full)) {
210
+ initialHashes[rel] = sha256(fs.readFileSync(full, "utf-8"));
211
+ }
212
+ }
213
+ const meta = {
214
+ schemaVersion: 3,
215
+ caseId: spec.id,
216
+ arm: normArm,
217
+ locale,
218
+ baseSha,
219
+ initialHashes,
220
+ createdAt: new Date().toISOString(),
221
+ };
222
+ fs.writeFileSync(path.join(absDir, META_REL), JSON.stringify(meta, null, 2) + "\n", "utf-8");
223
+
224
+ const sessionPrompts = Array.isArray(spec.sessions)
225
+ ? spec.sessions.map((p) => buildEvalPrompt({ ...spec, taskPrompt: p }, normArm))
226
+ : [buildEvalPrompt(spec, normArm)];
227
+
228
+ return {
229
+ targetDir: absDir,
230
+ caseId: spec.id,
231
+ arm: normArm,
232
+ baseSha,
233
+ prompt: sessionPrompts[0],
234
+ sessionPrompts,
235
+ };
236
+ }
237
+
238
+ /**
239
+ * Dumbbell Zero-Tax Prompt Builder (v3.2):
240
+ * `v3` carries the exact same lean context instructions as `v1`—zero extra doc hops,
241
+ * letting background L4/Git guardrails enforce safety & cross-package backpressure at 0 token cost.
242
+ */
243
+ export function buildEvalPrompt(spec, arm) {
244
+ if (arm === "baseline") {
245
+ return `${spec.taskPrompt}\nVerify with tests and report changed files.`;
246
+ }
247
+ if (arm === "v1") {
248
+ return [
249
+ "Fast-path obvious local edits; consult AGENTS.md / docs/00-context.md (or `node scripts/doc-find.mjs`) when active entrypoints or cross-package invariants are non-obvious.",
250
+ "",
251
+ `Task: ${spec.taskPrompt}`,
252
+ ].join("\n");
253
+ }
254
+ return [
255
+ "Fast-path obvious local edits; consult AGENTS.md / docs/00-context.md (or `node scripts/doc-find.mjs`) when active entrypoints or cross-package invariants are non-obvious. Guardrail hooks run automatically—do not manually read hook/config files.",
256
+ "",
257
+ `Task: ${spec.taskPrompt}`,
258
+ ].join("\n");
259
+ }
260
+
261
+ export function gradeFixture(caseId, workDir) {
262
+ const spec = EVAL_CASES[caseId];
263
+ if (!spec) throw new Error(`Unknown eval case: ${caseId}`);
264
+ const absDir = path.resolve(workDir);
265
+ const metaPath = path.join(absDir, META_REL);
266
+ let meta = { caseId: spec.id, arm: "unknown", baseSha: null, initialHashes: {} };
267
+ if (fs.existsSync(metaPath)) {
268
+ meta = JSON.parse(fs.readFileSync(metaPath, "utf-8"));
269
+ } else {
270
+ for (const rel of spec.watchedHashes || []) {
271
+ if (spec.files[rel] !== undefined) meta.initialHashes[rel] = sha256(spec.files[rel]);
272
+ }
273
+ }
274
+
275
+ const { checks, violations } = spec.grade(absDir, meta);
276
+ const passedChecks = checks.filter((c) => c.passed).length;
277
+ const passed = passedChecks === checks.length && violations.length === 0;
278
+
279
+ let modifiedFiles = [];
280
+ if (meta.baseSha && fs.existsSync(path.join(absDir, ".git"))) {
281
+ const status = spawnSync("git", ["status", "--porcelain"], { cwd: absDir, encoding: "utf-8" });
282
+ const diffNames = spawnSync("git", ["diff", "--name-only", meta.baseSha], { cwd: absDir, encoding: "utf-8" });
283
+ const set = new Set([
284
+ ...(status.stdout || "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean).map((l) => l.slice(2).trim()),
285
+ ...(diffNames.stdout || "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean),
286
+ ]);
287
+ modifiedFiles = [...set].sort();
288
+ }
289
+
290
+ return {
291
+ caseId: spec.id,
292
+ arm: meta.arm,
293
+ passed,
294
+ score: checks.length > 0 ? Math.round((passedChecks / checks.length) * 100) : 0,
295
+ passedChecks,
296
+ totalChecks: checks.length,
297
+ checks,
298
+ violations,
299
+ modifiedFiles,
300
+ };
301
+ }
302
+
303
+
304
+ function isCompletedRun(r) {
305
+ return r && r.driverExitCode === 0 && !r.timedOut;
306
+ }
307
+
308
+ function extractMeaningfulError(stderr, stdout) {
309
+ const combined = [stderr, stdout]
310
+ .filter(Boolean)
311
+ .join("\n")
312
+ .split(/\r?\n/)
313
+ .map((l) => l.trim())
314
+ .filter((l) => l && !/^Reading additional input from stdin/i.test(l));
315
+ if (combined.length === 0) return "";
316
+ return combined.slice(-6).join(" | ").slice(-800);
317
+ }
318
+
319
+ /**
320
+ * Computes per-arm summaries with strict statistical hygiene:
321
+ * 1. Token / tool / duration averages use ONLY completed runs (`driverExitCode === 0 && !timedOut`)
322
+ * so prematurely killed runs never fabricate fake token savings.
323
+ * 2. Deltas vs `baseline` (`pairedTokenDeltaPct`, `pairedBillableDeltaPct`, `pairedTimeDeltaPct`)
324
+ * are computed strictly on PAIRED `(caseId, repeat)` keys where BOTH baseline and the arm completed,
325
+ * preventing Simpson's paradox / survivor bias when an expensive case times out in one arm.
326
+ */
327
+ export function computeArmSummaries(runs, armList) {
328
+ const summaryByArm = {};
329
+ const baseRunsByKey = new Map();
330
+ for (const r of runs) {
331
+ if (r.arm === "baseline") {
332
+ baseRunsByKey.set(`${r.caseId}#${r.repeat}`, r);
333
+ }
334
+ }
335
+
336
+ for (const arm of armList) {
337
+ const armRuns = runs.filter((r) => r.arm === arm);
338
+ const completed = armRuns.filter(isCompletedRun);
339
+ const passed = armRuns.filter((r) => r.passed).length;
340
+ const violationCount = armRuns.reduce((sum, r) => sum + r.violations.length, 0);
341
+ const driverErrorCount = armRuns.filter((r) => r.driverExitCode !== 0 || r.timedOut).length;
342
+ const incompleteRuns = armRuns.length - completed.length;
343
+
344
+ const durPool = completed.length > 0 ? completed : armRuns;
345
+ const avgDurationMs = durPool.length
346
+ ? Math.round(durPool.reduce((sum, r) => sum + r.durationMs, 0) / durPool.length)
347
+ : 0;
348
+
349
+ const telRuns = completed.filter((r) => r.usage?.available);
350
+ const toolRuns = telRuns.filter((r) => typeof r.usage.toolCalls === "number");
351
+ const totalInSum = telRuns.reduce((s, r) => s + r.usage.inputTokens, 0);
352
+ const totalCachedSum = telRuns.reduce((s, r) => s + r.usage.cachedInputTokens, 0);
353
+
354
+ // Paired comparison vs baseline (same caseId + repeat, both completed cleanly)
355
+ let pairedCount = 0;
356
+ let pairedTimeDeltaPct = null;
357
+ let pairedTokenDeltaPct = null;
358
+ let pairedBillableDeltaPct = null;
359
+ if (arm !== "baseline" && baseRunsByKey.size > 0) {
360
+ let baseDur = 0, armDur = 0;
361
+ let baseTok = 0, armTok = 0;
362
+ let baseBill = 0, armBill = 0;
363
+ let tokPairs = 0;
364
+ for (const r of completed) {
365
+ const b = baseRunsByKey.get(`${r.caseId}#${r.repeat}`);
366
+ if (!b || !isCompletedRun(b)) continue;
367
+ pairedCount += 1;
368
+ baseDur += b.durationMs;
369
+ armDur += r.durationMs;
370
+ if (b.usage?.available && r.usage?.available) {
371
+ tokPairs += 1;
372
+ baseTok += b.usage.totalTokens;
373
+ armTok += r.usage.totalTokens;
374
+ baseBill += b.usage.billableEquivTokens;
375
+ armBill += r.usage.billableEquivTokens;
376
+ }
377
+ }
378
+ if (pairedCount > 0 && baseDur > 0) {
379
+ pairedTimeDeltaPct = Math.round(((armDur - baseDur) / baseDur) * 100);
380
+ }
381
+ if (tokPairs > 0 && baseTok > 0) {
382
+ pairedTokenDeltaPct = Math.round(((armTok - baseTok) / baseTok) * 100);
383
+ }
384
+ if (tokPairs > 0 && baseBill > 0) {
385
+ pairedBillableDeltaPct = Math.round(((armBill - baseBill) / baseBill) * 100);
386
+ }
387
+ }
388
+
389
+ summaryByArm[arm] = {
390
+ total: armRuns.length,
391
+ completedRuns: completed.length,
392
+ incompleteRuns,
393
+ passed,
394
+ passRatePct: armRuns.length ? Math.round((passed / armRuns.length) * 100) : 0,
395
+ violationCount,
396
+ driverErrorCount,
397
+ avgDurationMs,
398
+ telemetryRuns: telRuns.length,
399
+ avgTotalTokens: telRuns.length ? Math.round(telRuns.reduce((s, r) => s + r.usage.totalTokens, 0) / telRuns.length) : null,
400
+ avgBillableTokens: telRuns.length ? Math.round(telRuns.reduce((s, r) => s + r.usage.billableEquivTokens, 0) / telRuns.length) : null,
401
+ avgOutputTokens: telRuns.length ? Math.round(telRuns.reduce((s, r) => s + r.usage.outputTokens, 0) / telRuns.length) : null,
402
+ avgCacheHitPct: totalInSum > 0 ? Math.round((totalCachedSum / totalInSum) * 100) : null,
403
+ avgToolCalls: toolRuns.length ? Number((toolRuns.reduce((s, r) => s + r.usage.toolCalls, 0) / toolRuns.length).toFixed(1)) : null,
404
+ pairedCount,
405
+ pairedTimeDeltaPct,
406
+ pairedTokenDeltaPct,
407
+ pairedBillableDeltaPct,
408
+ };
409
+ }
410
+
411
+ return summaryByArm;
412
+ }
413
+
414
+ export function renderMarkdownReport(report) {
415
+ const isMock = report.agent.startsWith("mock-");
416
+ const baseSummary = report.summaryByArm.baseline || null;
417
+ const hasTelemetry = report.arms.some((a) => (report.summaryByArm[a]?.telemetryRuns || 0) > 0);
418
+ const lines = [
419
+ "# AgentLock Harness v3.3.1 — Behavioral & Token Ablation Evaluation Report",
420
+ "",
421
+ `- **Generated**: ${report.generatedAt}`,
422
+ `- **Driver**: \`${report.agent}\`${report.driverVersion ? ` (${report.driverVersion})` : ""}${isMock ? " *(Fixture self-test simulator — validates graders & harness wiring ONLY; NOT real LLM benchmark evidence)*" : ""}`,
423
+ `- **v3 Profile**: ${report.v3Profile || "dumbbell-zero-tax"}`,
424
+ `- **Suite / Cases**: ${report.cases.join(", ")} | **Arms**: ${report.arms.join(", ")} | **Repeats**: ${report.repeats}`,
425
+ "",
426
+ "## Summary by Ablation Arm",
427
+ "",
428
+ hasTelemetry
429
+ ? "| Arm | Pass Rate | Delta vs Baseline | Passed / Total | Violations | Avg Total Tokens | Token Delta | Avg Uncached+Out | Uncached+Out Delta | Cache Hit | Avg Tools | Avg Duration (ms) | Time Overhead |"
430
+ : "| Arm | Pass Rate | Delta vs Baseline | Passed / Total | Violations | Driver Errors | Avg Duration (ms) | Time Overhead |",
431
+ hasTelemetry
432
+ ? "| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
433
+ : "| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |",
434
+ ];
435
+
436
+ const fmtPct = (v, suffix = "") => (typeof v === "number" ? `${v >= 0 ? "+" : ""}${v}%${suffix}` : "—");
437
+ for (const arm of report.arms) {
438
+ const s = report.summaryByArm[arm];
439
+ let passDelta = "—";
440
+ let timeDelta = "—";
441
+ let tokDelta = "—";
442
+ let billDelta = "—";
443
+ const pairTag =
444
+ arm !== "baseline" && typeof s.pairedCount === "number" && s.pairedCount < s.total
445
+ ? ` (${s.pairedCount}/${s.total})`
446
+ : "";
447
+ if (baseSummary && arm !== "baseline") {
448
+ const pd = s.passRatePct - baseSummary.passRatePct;
449
+ passDelta = `${pd >= 0 ? "+" : ""}${pd}%`;
450
+ if (typeof s.pairedTimeDeltaPct === "number") {
451
+ timeDelta = fmtPct(s.pairedTimeDeltaPct, pairTag);
452
+ } else if (baseSummary.avgDurationMs > 0 && (s.incompleteRuns || 0) === 0) {
453
+ timeDelta = fmtPct(Math.round(((s.avgDurationMs - baseSummary.avgDurationMs) / baseSummary.avgDurationMs) * 100));
454
+ }
455
+ if (typeof s.pairedTokenDeltaPct === "number") {
456
+ tokDelta = fmtPct(s.pairedTokenDeltaPct, pairTag);
457
+ } else if (baseSummary.avgTotalTokens > 0 && s.avgTotalTokens !== null && (s.incompleteRuns || 0) === 0) {
458
+ tokDelta = fmtPct(Math.round(((s.avgTotalTokens - baseSummary.avgTotalTokens) / baseSummary.avgTotalTokens) * 100));
459
+ }
460
+ if (typeof s.pairedBillableDeltaPct === "number") {
461
+ billDelta = fmtPct(s.pairedBillableDeltaPct, pairTag);
462
+ } else if (baseSummary.avgBillableTokens > 0 && s.avgBillableTokens !== null && (s.incompleteRuns || 0) === 0) {
463
+ billDelta = fmtPct(Math.round(((s.avgBillableTokens - baseSummary.avgBillableTokens) / baseSummary.avgBillableTokens) * 100));
464
+ }
465
+ }
466
+ if (hasTelemetry) {
467
+ lines.push(
468
+ `| \`${arm}\` | **${s.passRatePct}%** | ${passDelta} | ${s.passed} / ${s.total} | ${s.violationCount} | ` +
469
+ `${formatTokenCount(s.avgTotalTokens)} | ${tokDelta} | ${formatTokenCount(s.avgBillableTokens)} | ${billDelta} | ` +
470
+ `${s.avgCacheHitPct !== null ? `${s.avgCacheHitPct}%` : "—"} | ${s.avgToolCalls !== null ? s.avgToolCalls : "—"} | ` +
471
+ `${s.avgDurationMs} | ${timeDelta} |`
472
+ );
473
+ } else {
474
+ lines.push(
475
+ `| \`${arm}\` | **${s.passRatePct}%** | ${passDelta} | ${s.passed} / ${s.total} | ${s.violationCount} | ${s.driverErrorCount} | ${s.avgDurationMs} | ${timeDelta} |`
476
+ );
477
+ }
478
+ }
479
+
480
+ lines.push(
481
+ "",
482
+ "## Per-Case Matrix",
483
+ "",
484
+ hasTelemetry
485
+ ? "| Case | Arm | Repeat | Sessions | Verdict | Score | Total Tokens | Uncached+Out | Output | Cache% | Tools | Violations | Duration (ms) |"
486
+ : "| Case | Arm | Repeat | Sessions | Verdict | Score | Driver Exit | Violations | Duration (ms) |",
487
+ hasTelemetry
488
+ ? "| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | :---: |"
489
+ : "| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :--- | :---: |"
490
+ );
491
+ for (const r of report.runs) {
492
+ const verdict = r.passed ? "PASS" : r.timedOut ? "TIMEOUT" : r.driverExitCode !== 0 ? "ERROR" : "FAIL";
493
+ const viol = r.violations.length ? r.violations.join(", ") : "none";
494
+ const exitCell = r.timedOut ? "TIMEOUT" : String(r.driverExitCode);
495
+ if (hasTelemetry) {
496
+ const u = r.usage;
497
+ lines.push(
498
+ `| \`${r.caseId}\` | \`${r.arm}\` | ${r.repeat} | ${r.sessionsExecuted || 1} | ${verdict} | ${r.score}% | ` +
499
+ `${u?.available ? formatTokenCount(u.totalTokens) + (r.timedOut || r.driverExitCode !== 0 ? "*" : "") : "—"} | ` +
500
+ `${u?.available ? formatTokenCount(u.billableEquivTokens) + (r.timedOut || r.driverExitCode !== 0 ? "*" : "") : "—"} | ` +
501
+ `${u?.available ? formatTokenCount(u.outputTokens) : "—"} | ` +
502
+ `${u?.available ? `${u.cacheHitPct}%` : "—"} | ` +
503
+ `${typeof u?.toolCalls === "number" ? u.toolCalls : "—"} | ` +
504
+ `${viol} | ${r.durationMs} |`
505
+ );
506
+ } else {
507
+ lines.push(
508
+ `| \`${r.caseId}\` | \`${r.arm}\` | ${r.repeat} | ${r.sessionsExecuted || 1} | ${verdict} | ${r.score}% | ${exitCell} | ${viol} | ${r.durationMs} |`
509
+ );
510
+ }
511
+ }
512
+
513
+ const erroredRuns = report.runs.filter((r) => r.driverExitCode !== 0 && (r.driverError || r.driverStderr));
514
+ if (erroredRuns.length > 0) {
515
+ lines.push("", "## Driver Diagnostics (Non-Zero Exit Runs)", "");
516
+ for (const r of erroredRuns.slice(0, 5)) {
517
+ lines.push(`- **${r.caseId}/${r.arm}#${r.repeat}** (exit ${r.driverExitCode}): \`${(r.driverError || r.driverStderr || "").replace(/\r?\n/g, " ").slice(0, 240)}\``);
518
+ }
519
+ }
520
+
521
+ lines.push(
522
+ "",
523
+ "## Epistemic Boundary Notice",
524
+ "",
525
+ isMock
526
+ ? "> This run used a deterministic mock simulator (`" + report.agent + "`). It verifies fixture integrity, grader discrimination, and pipeline determinism, and MUST NOT be cited as real model accuracy evidence."
527
+ : "> Results reflect the exact CLI version, model, prompt, timeout, and fixture set above. Repeat runs (N >= 3) across multiple repositories are recommended before generalizing.",
528
+ ""
529
+ );
530
+ return lines.join("\n");
531
+ }
532
+
533
+ export async function runEvalSuite({
534
+ cases = EVAL_SUITES.core,
535
+ arms = ["baseline", "v1", "v3"],
536
+ agent = "mock-oracle",
537
+ repeats = 1,
538
+ timeoutSec = 360,
539
+ locale = "en-US",
540
+ outDir = null,
541
+ dryRun = false,
542
+ keepWorkspaces = false,
543
+ verbose = false,
544
+ failFast = true,
545
+ fullHosts = false,
546
+ withSkills = null,
547
+ model = null,
548
+ agentFlags = null,
549
+ onRunComplete = null,
550
+ } = {}) {
551
+ if (!VALID_EVAL_DRIVERS.includes(agent)) {
552
+ throw new Error(`Unsupported eval driver: ${agent} (valid: ${VALID_EVAL_DRIVERS.join(", ")})`);
553
+ }
554
+ const caseList = cases.map((id) => String(id).trim().toUpperCase());
555
+ for (const id of caseList) {
556
+ if (!EVAL_CASES[id]) throw new Error(`Unknown eval case: ${id} (available: ${Object.keys(EVAL_CASES).join(", ")})`);
557
+ }
558
+ const armList = arms.map((a) => (a === "harness" ? "v3" : a));
559
+ for (const a of armList) {
560
+ if (!VALID_ARMS.includes(a)) throw new Error(`Unknown arm: ${a} (valid: ${VALID_ARMS.join(", ")})`);
561
+ }
562
+
563
+ const repCount = Math.max(1, Number.parseInt(String(repeats), 10) || 1);
564
+ const timeoutMs = Math.max(5, Number.parseInt(String(timeoutSec), 10) || 360) * 1000;
565
+ const totalPlanned = caseList.length * armList.length * repCount;
566
+ const v3Profile = fullHosts || withSkills ? "full-multihost" : "dumbbell-zero-tax";
567
+
568
+ if (dryRun) {
569
+ const sampleInv = agent.startsWith("mock-")
570
+ ? { cmd: agent, displayArgs: [] }
571
+ : buildAgentInvocation(agent, "eval", "<PROMPT>", {}, { model, agentFlags });
572
+ return {
573
+ ok: true,
574
+ dryRun: true,
575
+ agent,
576
+ v3Profile,
577
+ resolvedCmd: agent.startsWith("mock-") ? agent : `${sampleInv.cmd} ${sampleInv.displayArgs.join(" ")}`,
578
+ cases: caseList,
579
+ arms: armList,
580
+ repeats: repCount,
581
+ plannedRuns: totalPlanned,
582
+ };
583
+ }
584
+
585
+ const avail = checkDriverAvailability(agent);
586
+ if (!avail.available) {
587
+ throw new Error(
588
+ `驱动 CLI "${agent}" 不可用 (${avail.error})。请先运行 alh doctor --fix 安装并登录,或先用 --agent mock-oracle 验证本地夹具。`
589
+ );
590
+ }
591
+
592
+ const runs = [];
593
+ const workspaces = [];
594
+ let abortedEarly = false;
595
+ let abortReason = null;
596
+ let stepIndex = 0;
597
+
598
+ outer: for (const caseId of caseList) {
599
+ const spec = EVAL_CASES[caseId];
600
+ for (const arm of armList) {
601
+ for (let rep = 1; rep <= repCount; rep++) {
602
+ stepIndex++;
603
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), `alh-eval-${caseId}-${arm}-r${rep}-`));
604
+ workspaces.push(tmpRoot);
605
+ try {
606
+ const mat = await materializeFixture(caseId, tmpRoot, {
607
+ arm,
608
+ locale,
609
+ targetAgent: agent,
610
+ fullHosts,
611
+ withSkills,
612
+ });
613
+ const started = Date.now();
614
+ let driverExitCode = 0;
615
+ let timedOut = false;
616
+ let driverError = null;
617
+ let driverStderr = "";
618
+ let resolvedCmd = agent;
619
+ let sessionsExecuted = 0;
620
+ const sessionUsages = [];
621
+ const sessionDetails = [];
622
+
623
+ for (let sIdx = 0; sIdx < mat.sessionPrompts.length; sIdx++) {
624
+ sessionsExecuted++;
625
+ const sessionStarted = Date.now();
626
+ const sessionPrompt = mat.sessionPrompts[sIdx];
627
+ if (agent === "mock-oracle") {
628
+ spec.mockOracle(tmpRoot, sIdx);
629
+ } else if (agent === "mock-naive") {
630
+ spec.mockNaive(tmpRoot, sIdx);
631
+ } else {
632
+ const cfgPath = path.join(tmpRoot, HARNESS_CONFIG_FILE);
633
+ const cfg = fs.existsSync(cfgPath) ? JSON.parse(fs.readFileSync(cfgPath, "utf-8")) : {};
634
+ const inv = buildAgentInvocation(agent, "eval", sessionPrompt, cfg, {
635
+ model,
636
+ agentFlags,
637
+ jsonOutput: !verbose,
638
+ });
639
+ resolvedCmd = `${inv.cmd} ${inv.displayArgs.join(" ")}`;
640
+ const execRes = spawnSync(inv.cmd, inv.args, {
641
+ cwd: tmpRoot,
642
+ encoding: "utf-8",
643
+ stdio: verbose ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"],
644
+ timeout: timeoutMs,
645
+ maxBuffer: 64 * 1024 * 1024,
646
+ shell: process.platform === "win32",
647
+ });
648
+ driverExitCode = execRes.status ?? 1;
649
+ timedOut = Boolean(execRes.error && execRes.error.code === "ETIMEDOUT");
650
+ if (execRes.error) driverError = execRes.error.message || String(execRes.error.code);
651
+ let sessionTel = null;
652
+ if (!verbose) {
653
+ const tel = parseDriverTelemetry(agent, execRes.stdout || "");
654
+ if (tel.available) {
655
+ sessionUsages.push(tel);
656
+ sessionTel = tel;
657
+ }
658
+ if (tel.extractedError && driverExitCode !== 0) {
659
+ driverStderr = tel.extractedError;
660
+ } else if (driverExitCode !== 0) {
661
+ driverStderr = extractMeaningfulError(execRes.stderr, execRes.stdout);
662
+ }
663
+ }
664
+ sessionDetails.push({
665
+ session: sIdx + 1,
666
+ durationMs: Date.now() - sessionStarted,
667
+ exitCode: driverExitCode,
668
+ timedOut,
669
+ ...(sessionTel ? { totalTokens: sessionTel.totalTokens, billableEquivTokens: sessionTel.billableEquivTokens, toolCalls: sessionTel.toolCalls } : {}),
670
+ });
671
+ if (driverExitCode !== 0 || timedOut) break;
672
+ }
673
+ }
674
+
675
+ const durationMs = Date.now() - started;
676
+ const usage = aggregateTelemetry(sessionUsages);
677
+ const graded = gradeFixture(caseId, tmpRoot);
678
+ const runRecord = {
679
+ caseId,
680
+ arm,
681
+ repeat: rep,
682
+ sessionsExecuted,
683
+ ...(mat.sessionPrompts.length > 1 && sessionDetails.length > 0 ? { sessionDetails } : {}),
684
+ agent,
685
+ resolvedCmd,
686
+ driverExitCode,
687
+ timedOut,
688
+ ...(driverError ? { driverError } : {}),
689
+ ...(driverExitCode !== 0 && driverStderr ? { driverStderr } : {}),
690
+ durationMs,
691
+ ...(usage.available ? { usage } : {}),
692
+ ...graded,
693
+ };
694
+ runs.push(runRecord);
695
+ if (typeof onRunComplete === "function") {
696
+ onRunComplete(runRecord, stepIndex, totalPlanned);
697
+ }
698
+
699
+ if (
700
+ failFast &&
701
+ !agent.startsWith("mock-") &&
702
+ stepIndex === 1 &&
703
+ driverExitCode !== 0 &&
704
+ !timedOut &&
705
+ durationMs < 2000 &&
706
+ graded.modifiedFiles.length === 0
707
+ ) {
708
+ abortedEarly = true;
709
+ abortReason =
710
+ `首轮 CLI 驱动 "${resolvedCmd}" 在 ${durationMs}ms 内异常退出 (exit=${driverExitCode}) 且未改动任何文件。` +
711
+ (driverStderr ? `\n驱动输出: ${driverStderr}` : "") +
712
+ `\n提示:可用 --agent-flags "..." 覆盖参数,或加 --verbose 查看完整日志。`;
713
+ break outer;
714
+ }
715
+ } finally {
716
+ if (!keepWorkspaces) {
717
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
718
+ }
719
+ }
720
+ }
721
+ }
722
+ }
723
+
724
+ const summaryByArm = computeArmSummaries(runs, armList);
725
+
726
+ const report = {
727
+ schemaVersion: 5,
728
+ generatedAt: new Date().toISOString(),
729
+ agent,
730
+ driverVersion: avail.version,
731
+ v3Profile,
732
+ cases: caseList,
733
+ arms: armList,
734
+ repeats: repCount,
735
+ abortedEarly,
736
+ ...(abortReason ? { abortReason } : {}),
737
+ summaryByArm,
738
+ runs,
739
+ ...(keepWorkspaces ? { workspaces } : {}),
740
+ };
741
+
742
+ let writtenReports = [];
743
+ if (outDir) {
744
+ const absOut = path.resolve(outDir);
745
+ fs.mkdirSync(absOut, { recursive: true });
746
+ const jsonPath = path.join(absOut, "report.json");
747
+ const mdPath = path.join(absOut, "report.md");
748
+ fs.writeFileSync(jsonPath, JSON.stringify(report, null, 2) + "\n", "utf-8");
749
+ fs.writeFileSync(mdPath, renderMarkdownReport(report), "utf-8");
750
+ writtenReports = [jsonPath, mdPath];
751
+ }
752
+
753
+ return { ok: !abortedEarly, report, writtenReports };
754
+ }