spexcode 0.6.1 → 0.6.5

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 (480) hide show
  1. package/README.md +99 -149
  2. package/bin/spex.mjs +4 -0
  3. package/node_modules/@spexcode/spec-cli/bin/spex.mjs +76 -0
  4. package/node_modules/@spexcode/spec-cli/dist/attach.d.ts +2 -0
  5. package/node_modules/@spexcode/spec-cli/dist/attach.js +48 -0
  6. package/node_modules/@spexcode/spec-cli/dist/claude-headless.d.ts +33 -0
  7. package/node_modules/@spexcode/spec-cli/dist/claude-headless.js +307 -0
  8. package/node_modules/@spexcode/spec-cli/dist/cli.d.ts +1 -0
  9. package/node_modules/@spexcode/spec-cli/dist/cli.js +1859 -0
  10. package/node_modules/@spexcode/spec-cli/dist/client.d.ts +111 -0
  11. package/node_modules/@spexcode/spec-cli/dist/client.js +476 -0
  12. package/node_modules/@spexcode/spec-cli/dist/cockpit.d.ts +7 -0
  13. package/node_modules/@spexcode/spec-cli/dist/cockpit.js +26 -0
  14. package/node_modules/@spexcode/spec-cli/dist/codex-headless.d.ts +1 -0
  15. package/{spec-cli/src/codex-headless.ts → node_modules/@spexcode/spec-cli/dist/codex-headless.js} +3 -9
  16. package/node_modules/@spexcode/spec-cli/dist/codex-runtime-generations.d.ts +53 -0
  17. package/node_modules/@spexcode/spec-cli/dist/codex-runtime-generations.js +686 -0
  18. package/node_modules/@spexcode/spec-cli/dist/commit-surgery.d.ts +1 -0
  19. package/node_modules/@spexcode/spec-cli/dist/commit-surgery.js +90 -0
  20. package/node_modules/@spexcode/spec-cli/dist/contract-filter.d.ts +14 -0
  21. package/node_modules/@spexcode/spec-cli/dist/contract-filter.js +219 -0
  22. package/node_modules/@spexcode/spec-cli/dist/dashboard-assets.d.ts +6 -0
  23. package/node_modules/@spexcode/spec-cli/dist/dashboard-assets.js +50 -0
  24. package/node_modules/@spexcode/spec-cli/dist/delivery-queue.d.ts +23 -0
  25. package/node_modules/@spexcode/spec-cli/dist/delivery-queue.js +179 -0
  26. package/node_modules/@spexcode/spec-cli/dist/doctor.d.ts +9 -0
  27. package/node_modules/@spexcode/spec-cli/dist/doctor.js +547 -0
  28. package/node_modules/@spexcode/spec-cli/dist/eval-host.d.ts +1 -0
  29. package/node_modules/@spexcode/spec-cli/dist/eval-host.js +19 -0
  30. package/node_modules/@spexcode/spec-cli/dist/execution-trace.d.ts +26 -0
  31. package/node_modules/@spexcode/spec-cli/dist/execution-trace.js +475 -0
  32. package/node_modules/@spexcode/spec-cli/dist/file-write.d.ts +2 -0
  33. package/node_modules/@spexcode/spec-cli/dist/file-write.js +26 -0
  34. package/node_modules/@spexcode/spec-cli/dist/flat.d.ts +89 -0
  35. package/node_modules/@spexcode/spec-cli/dist/flat.js +1076 -0
  36. package/node_modules/@spexcode/spec-cli/dist/gateway-auth.d.ts +56 -0
  37. package/node_modules/@spexcode/spec-cli/dist/gateway-auth.js +168 -0
  38. package/node_modules/@spexcode/spec-cli/dist/gateway-hub.d.ts +28 -0
  39. package/node_modules/@spexcode/spec-cli/dist/gateway-hub.js +361 -0
  40. package/node_modules/@spexcode/spec-cli/dist/gateway.d.ts +37 -0
  41. package/node_modules/@spexcode/spec-cli/dist/gateway.js +503 -0
  42. package/node_modules/@spexcode/spec-cli/dist/graphCache.d.ts +27 -0
  43. package/node_modules/@spexcode/spec-cli/dist/graphCache.js +716 -0
  44. package/node_modules/@spexcode/spec-cli/dist/graphSnapshot.d.ts +14 -0
  45. package/node_modules/@spexcode/spec-cli/dist/graphSnapshot.js +35 -0
  46. package/node_modules/@spexcode/spec-cli/dist/graphStream.d.ts +85 -0
  47. package/node_modules/@spexcode/spec-cli/dist/graphStream.js +1195 -0
  48. package/node_modules/@spexcode/spec-cli/dist/guidance-catalog.d.ts +64 -0
  49. package/node_modules/@spexcode/spec-cli/dist/guidance-catalog.js +166 -0
  50. package/node_modules/@spexcode/spec-cli/dist/guide.d.ts +8 -0
  51. package/{spec-cli/src/guide.ts → node_modules/@spexcode/spec-cli/dist/guide.js} +115 -22
  52. package/node_modules/@spexcode/spec-cli/dist/harness-select.d.ts +18 -0
  53. package/node_modules/@spexcode/spec-cli/dist/harness-select.js +62 -0
  54. package/node_modules/@spexcode/spec-cli/dist/harness.d.ts +325 -0
  55. package/node_modules/@spexcode/spec-cli/dist/harness.js +3026 -0
  56. package/node_modules/@spexcode/spec-cli/dist/headless-controller.d.ts +9 -0
  57. package/node_modules/@spexcode/spec-cli/dist/headless-controller.js +47 -0
  58. package/node_modules/@spexcode/spec-cli/dist/help.d.ts +10 -0
  59. package/node_modules/@spexcode/spec-cli/dist/help.js +574 -0
  60. package/node_modules/@spexcode/spec-cli/dist/hook-prompts.d.ts +18 -0
  61. package/node_modules/@spexcode/spec-cli/dist/hook-prompts.js +122 -0
  62. package/node_modules/@spexcode/spec-cli/dist/hooks.d.ts +1 -0
  63. package/{spec-cli/src/hooks.ts → node_modules/@spexcode/spec-cli/dist/hooks.js} +15 -15
  64. package/node_modules/@spexcode/spec-cli/dist/host-resources.d.ts +97 -0
  65. package/node_modules/@spexcode/spec-cli/dist/host-resources.js +795 -0
  66. package/node_modules/@spexcode/spec-cli/dist/host.d.ts +88 -0
  67. package/node_modules/@spexcode/spec-cli/dist/host.js +663 -0
  68. package/node_modules/@spexcode/spec-cli/dist/index.d.ts +1 -0
  69. package/node_modules/@spexcode/spec-cli/dist/index.js +899 -0
  70. package/node_modules/@spexcode/spec-cli/dist/init.d.ts +1 -0
  71. package/node_modules/@spexcode/spec-cli/dist/init.js +284 -0
  72. package/node_modules/@spexcode/spec-cli/dist/issues-cli.d.ts +6 -0
  73. package/node_modules/@spexcode/spec-cli/dist/issues-cli.js +334 -0
  74. package/node_modules/@spexcode/spec-cli/dist/issues.d.ts +69 -0
  75. package/node_modules/@spexcode/spec-cli/dist/issues.js +189 -0
  76. package/node_modules/@spexcode/spec-cli/dist/lint.d.ts +34 -0
  77. package/node_modules/@spexcode/spec-cli/dist/lint.js +476 -0
  78. package/node_modules/@spexcode/spec-cli/dist/listen.d.ts +7 -0
  79. package/{spec-cli/src/listen.ts → node_modules/@spexcode/spec-cli/dist/listen.js} +13 -17
  80. package/node_modules/@spexcode/spec-cli/dist/localIssues.d.ts +65 -0
  81. package/node_modules/@spexcode/spec-cli/dist/localIssues.js +582 -0
  82. package/node_modules/@spexcode/spec-cli/dist/login-page.d.ts +5 -0
  83. package/{spec-cli/src/login-page.ts → node_modules/@spexcode/spec-cli/dist/login-page.js} +7 -7
  84. package/node_modules/@spexcode/spec-cli/dist/loop-in.d.ts +23 -0
  85. package/{spec-cli/src/loop-in.ts → node_modules/@spexcode/spec-cli/dist/loop-in.js} +35 -45
  86. package/node_modules/@spexcode/spec-cli/dist/machine-peer.d.ts +69 -0
  87. package/node_modules/@spexcode/spec-cli/dist/machine-peer.js +603 -0
  88. package/node_modules/@spexcode/spec-cli/dist/materialize.d.ts +18 -0
  89. package/node_modules/@spexcode/spec-cli/dist/materialize.js +468 -0
  90. package/node_modules/@spexcode/spec-cli/dist/mentions.d.ts +50 -0
  91. package/node_modules/@spexcode/spec-cli/dist/mentions.js +117 -0
  92. package/node_modules/@spexcode/spec-cli/dist/opencode-headless.d.ts +4 -0
  93. package/node_modules/@spexcode/spec-cli/dist/opencode-headless.js +208 -0
  94. package/node_modules/@spexcode/spec-cli/dist/opencode.d.ts +3 -0
  95. package/{spec-cli/src/opencode.ts → node_modules/@spexcode/spec-cli/dist/opencode.js} +9 -13
  96. package/node_modules/@spexcode/spec-cli/dist/pi-harness.d.ts +3 -0
  97. package/{spec-cli/src/pi-harness.ts → node_modules/@spexcode/spec-cli/dist/pi-harness.js} +45 -40
  98. package/node_modules/@spexcode/spec-cli/dist/pi-headless.d.ts +25 -0
  99. package/node_modules/@spexcode/spec-cli/dist/pi-headless.js +196 -0
  100. package/node_modules/@spexcode/spec-cli/dist/plugin-harness.d.ts +21 -0
  101. package/node_modules/@spexcode/spec-cli/dist/plugin-harness.js +146 -0
  102. package/node_modules/@spexcode/spec-cli/dist/pty-bridge.d.ts +10 -0
  103. package/node_modules/@spexcode/spec-cli/dist/pty-bridge.js +404 -0
  104. package/node_modules/@spexcode/spec-cli/dist/pty-helper.d.mts +1 -0
  105. package/node_modules/@spexcode/spec-cli/dist/pty-helper.mjs +101 -0
  106. package/node_modules/@spexcode/spec-cli/dist/pty-native-helper.d.mts +2 -0
  107. package/node_modules/@spexcode/spec-cli/dist/pty-native-helper.mjs +23 -0
  108. package/node_modules/@spexcode/spec-cli/dist/public-graph.d.ts +46 -0
  109. package/node_modules/@spexcode/spec-cli/dist/public-graph.js +56 -0
  110. package/node_modules/@spexcode/spec-cli/dist/ranker.d.ts +15 -0
  111. package/node_modules/@spexcode/spec-cli/dist/ranker.js +188 -0
  112. package/node_modules/@spexcode/spec-cli/dist/reaper.d.ts +6 -0
  113. package/node_modules/@spexcode/spec-cli/dist/reaper.js +81 -0
  114. package/node_modules/@spexcode/spec-cli/dist/reviews.d.ts +189 -0
  115. package/node_modules/@spexcode/spec-cli/dist/reviews.js +350 -0
  116. package/node_modules/@spexcode/spec-cli/dist/runtime-guard.d.ts +6 -0
  117. package/node_modules/@spexcode/spec-cli/dist/runtime-guard.js +37 -0
  118. package/node_modules/@spexcode/spec-cli/dist/runtime-ownership.d.ts +21 -0
  119. package/node_modules/@spexcode/spec-cli/dist/runtime-ownership.js +84 -0
  120. package/node_modules/@spexcode/spec-cli/dist/search.bench.d.mts +1 -0
  121. package/node_modules/@spexcode/spec-cli/dist/search.bench.mjs +75 -0
  122. package/node_modules/@spexcode/spec-cli/dist/search.d.ts +20 -0
  123. package/node_modules/@spexcode/spec-cli/dist/search.js +61 -0
  124. package/node_modules/@spexcode/spec-cli/dist/session-cursors.d.ts +14 -0
  125. package/node_modules/@spexcode/spec-cli/dist/session-cursors.js +82 -0
  126. package/node_modules/@spexcode/spec-cli/dist/session-declarations.d.ts +13 -0
  127. package/node_modules/@spexcode/spec-cli/dist/session-declarations.js +126 -0
  128. package/node_modules/@spexcode/spec-cli/dist/session-execution.d.ts +10 -0
  129. package/node_modules/@spexcode/spec-cli/dist/session-execution.js +70 -0
  130. package/node_modules/@spexcode/spec-cli/dist/session-files.d.ts +28 -0
  131. package/node_modules/@spexcode/spec-cli/dist/session-files.js +130 -0
  132. package/node_modules/@spexcode/spec-cli/dist/session-follow.d.ts +31 -0
  133. package/node_modules/@spexcode/spec-cli/dist/session-follow.js +179 -0
  134. package/node_modules/@spexcode/spec-cli/dist/session-reparent.d.ts +10 -0
  135. package/node_modules/@spexcode/spec-cli/dist/session-reparent.js +33 -0
  136. package/node_modules/@spexcode/spec-cli/dist/session-timeline.d.ts +51 -0
  137. package/node_modules/@spexcode/spec-cli/dist/session-timeline.js +233 -0
  138. package/node_modules/@spexcode/spec-cli/dist/session-web.d.ts +24 -0
  139. package/node_modules/@spexcode/spec-cli/dist/session-web.js +141 -0
  140. package/node_modules/@spexcode/spec-cli/dist/sessions.d.ts +412 -0
  141. package/node_modules/@spexcode/spec-cli/dist/sessions.js +4239 -0
  142. package/node_modules/@spexcode/spec-cli/dist/sh.d.ts +1 -0
  143. package/node_modules/@spexcode/spec-cli/dist/sh.js +3 -0
  144. package/node_modules/@spexcode/spec-cli/dist/shim-runtime.d.ts +1 -0
  145. package/{spec-cli/src/shim-runtime.ts → node_modules/@spexcode/spec-cli/dist/shim-runtime.js} +3 -4
  146. package/node_modules/@spexcode/spec-cli/dist/slash-commands.d.ts +9 -0
  147. package/node_modules/@spexcode/spec-cli/dist/slash-commands.js +307 -0
  148. package/node_modules/@spexcode/spec-cli/dist/source-files.d.ts +9 -0
  149. package/node_modules/@spexcode/spec-cli/dist/source-files.js +113 -0
  150. package/node_modules/@spexcode/spec-cli/dist/supervise.d.ts +1 -0
  151. package/node_modules/@spexcode/spec-cli/dist/supervise.js +308 -0
  152. package/node_modules/@spexcode/spec-cli/dist/tree.d.ts +25 -0
  153. package/node_modules/@spexcode/spec-cli/dist/tree.js +98 -0
  154. package/node_modules/@spexcode/spec-cli/dist/tsx-bin.d.ts +3 -0
  155. package/node_modules/@spexcode/spec-cli/dist/tsx-bin.js +41 -0
  156. package/node_modules/@spexcode/spec-cli/dist/uninstall.d.ts +3 -0
  157. package/node_modules/@spexcode/spec-cli/dist/uninstall.js +177 -0
  158. package/node_modules/@spexcode/spec-cli/dist/uploads.d.ts +36 -0
  159. package/node_modules/@spexcode/spec-cli/dist/uploads.js +243 -0
  160. package/node_modules/@spexcode/spec-cli/dist/worktree-sources.d.ts +1 -0
  161. package/node_modules/@spexcode/spec-cli/dist/worktree-sources.js +47 -0
  162. package/{spec-cli → node_modules/@spexcode/spec-cli}/hooks/dispatch.sh +5 -5
  163. package/{spec-cli → node_modules/@spexcode/spec-cli}/hooks/harness.sh +27 -7
  164. package/node_modules/@spexcode/spec-cli/package.json +47 -0
  165. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/commands/supervisor/spec.md +8 -0
  166. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/core/comment-altitude/spec.md +9 -0
  167. package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/spec-first/spec-first.sh +1 -1
  168. package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/spec-of-file/spec-of-file.sh +1 -0
  169. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/core/spec.md +22 -0
  170. package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/stop-gate/spec.md +2 -2
  171. package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/stop-gate/stop-gate.sh +31 -29
  172. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/prompts/atomic-landing/spec.md +15 -0
  173. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/prompts/forge-link/spec.md +10 -0
  174. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/prompts/memory-hygiene/spec.md +13 -0
  175. package/node_modules/@spexcode/spec-cli/templates/spec/project/.plugins/prompts/reproduce-before-fix/spec.md +12 -0
  176. package/node_modules/@spexcode/spec-core/dist/anchors.d.ts +94 -0
  177. package/node_modules/@spexcode/spec-core/dist/anchors.js +730 -0
  178. package/node_modules/@spexcode/spec-core/dist/git.d.ts +166 -0
  179. package/node_modules/@spexcode/spec-core/dist/git.js +2736 -0
  180. package/node_modules/@spexcode/spec-core/dist/graph-delta.d.ts +44 -0
  181. package/node_modules/@spexcode/spec-core/dist/graph-delta.js +72 -0
  182. package/node_modules/@spexcode/spec-core/dist/graph.d.ts +34 -0
  183. package/node_modules/@spexcode/spec-core/dist/graph.js +237 -0
  184. package/node_modules/@spexcode/spec-core/dist/graphDelta.d.ts +3 -0
  185. package/node_modules/@spexcode/spec-core/dist/graphDelta.js +13 -0
  186. package/node_modules/@spexcode/spec-core/dist/harness-identity.d.ts +31 -0
  187. package/node_modules/@spexcode/spec-core/dist/harness-identity.js +20 -0
  188. package/node_modules/@spexcode/spec-core/dist/identity-presets.d.ts +152 -0
  189. package/node_modules/@spexcode/spec-core/dist/identity-presets.js +132 -0
  190. package/node_modules/@spexcode/spec-core/dist/index.d.ts +45 -0
  191. package/node_modules/@spexcode/spec-core/dist/index.js +19 -0
  192. package/node_modules/@spexcode/spec-core/dist/layout.d.ts +183 -0
  193. package/node_modules/@spexcode/spec-core/dist/layout.js +548 -0
  194. package/node_modules/@spexcode/spec-core/dist/process-identity.d.ts +37 -0
  195. package/node_modules/@spexcode/spec-core/dist/process-identity.js +214 -0
  196. package/node_modules/@spexcode/spec-core/dist/project-identity.d.ts +12 -0
  197. package/node_modules/@spexcode/spec-core/dist/project-identity.js +71 -0
  198. package/node_modules/@spexcode/spec-core/dist/project-store.d.ts +3 -0
  199. package/node_modules/@spexcode/spec-core/dist/project-store.js +14 -0
  200. package/node_modules/@spexcode/spec-core/dist/resilience.d.ts +2 -0
  201. package/node_modules/@spexcode/spec-core/dist/resilience.js +40 -0
  202. package/node_modules/@spexcode/spec-core/dist/review/index.d.ts +3 -0
  203. package/node_modules/@spexcode/spec-core/dist/review/index.js +5 -0
  204. package/node_modules/@spexcode/spec-core/dist/review/reviewFilters.d.ts +77 -0
  205. package/node_modules/@spexcode/spec-core/dist/review/reviewFilters.js +308 -0
  206. package/node_modules/@spexcode/spec-core/dist/review/reviewQuery.d.ts +66 -0
  207. package/node_modules/@spexcode/spec-core/dist/review/reviewQuery.js +180 -0
  208. package/node_modules/@spexcode/spec-core/dist/review/session.d.ts +4 -0
  209. package/node_modules/@spexcode/spec-core/dist/review/session.js +8 -0
  210. package/node_modules/@spexcode/spec-core/dist/reviewSnapshot.d.ts +15 -0
  211. package/node_modules/@spexcode/spec-core/dist/reviewSnapshot.js +12 -0
  212. package/node_modules/@spexcode/spec-core/dist/root-lru.d.ts +4 -0
  213. package/{spec-cli/src/root-lru.ts → node_modules/@spexcode/spec-core/dist/root-lru.js} +26 -30
  214. package/node_modules/@spexcode/spec-core/dist/specs.d.ts +117 -0
  215. package/node_modules/@spexcode/spec-core/dist/specs.js +489 -0
  216. package/node_modules/@spexcode/spec-core/package.json +28 -0
  217. package/node_modules/@spexcode/spec-eval/dist/cache.d.ts +10 -0
  218. package/node_modules/@spexcode/spec-eval/dist/cache.js +50 -0
  219. package/node_modules/@spexcode/spec-eval/dist/cli.d.ts +22 -0
  220. package/node_modules/@spexcode/spec-eval/dist/cli.js +981 -0
  221. package/node_modules/@spexcode/spec-eval/dist/evaltab.d.ts +98 -0
  222. package/node_modules/@spexcode/spec-eval/dist/evaltab.js +176 -0
  223. package/node_modules/@spexcode/spec-eval/dist/filing.d.ts +16 -0
  224. package/node_modules/@spexcode/spec-eval/dist/filing.js +36 -0
  225. package/node_modules/@spexcode/spec-eval/dist/freshness.d.ts +48 -0
  226. package/node_modules/@spexcode/spec-eval/dist/freshness.js +799 -0
  227. package/node_modules/@spexcode/spec-eval/dist/host.d.ts +46 -0
  228. package/node_modules/@spexcode/spec-eval/dist/host.js +53 -0
  229. package/node_modules/@spexcode/spec-eval/dist/humanok.d.ts +11 -0
  230. package/node_modules/@spexcode/spec-eval/dist/humanok.js +27 -0
  231. package/node_modules/@spexcode/spec-eval/dist/index.d.ts +4 -0
  232. package/node_modules/@spexcode/spec-eval/dist/index.js +4 -0
  233. package/node_modules/@spexcode/spec-eval/dist/remarks.d.ts +31 -0
  234. package/node_modules/@spexcode/spec-eval/dist/remarks.js +1 -0
  235. package/node_modules/@spexcode/spec-eval/dist/scenariofresh.d.ts +13 -0
  236. package/node_modules/@spexcode/spec-eval/dist/scenariofresh.js +303 -0
  237. package/node_modules/@spexcode/spec-eval/dist/scenarios.d.ts +99 -0
  238. package/node_modules/@spexcode/spec-eval/dist/scenarios.js +650 -0
  239. package/node_modules/@spexcode/spec-eval/dist/sessioneval.d.ts +307 -0
  240. package/node_modules/@spexcode/spec-eval/dist/sessioneval.js +1883 -0
  241. package/node_modules/@spexcode/spec-eval/dist/sidecar.d.ts +55 -0
  242. package/node_modules/@spexcode/spec-eval/dist/sidecar.js +82 -0
  243. package/node_modules/@spexcode/spec-eval/dist/timeline.d.ts +25 -0
  244. package/node_modules/@spexcode/spec-eval/dist/timeline.js +65 -0
  245. package/node_modules/@spexcode/spec-eval/dist/ui-path.d.ts +1 -0
  246. package/node_modules/@spexcode/spec-eval/dist/ui-path.js +2 -0
  247. package/node_modules/@spexcode/spec-eval/package.json +36 -0
  248. package/node_modules/@spexcode/spec-forge/dist/cache.d.ts +29 -0
  249. package/node_modules/@spexcode/spec-forge/dist/cache.js +59 -0
  250. package/node_modules/@spexcode/spec-forge/dist/cli.d.ts +1 -0
  251. package/node_modules/@spexcode/spec-forge/dist/cli.js +100 -0
  252. package/node_modules/@spexcode/spec-forge/dist/drivers/github.d.ts +2 -0
  253. package/node_modules/@spexcode/spec-forge/dist/drivers/github.js +116 -0
  254. package/node_modules/@spexcode/spec-forge/dist/drivers/gitlab.d.ts +7 -0
  255. package/node_modules/@spexcode/spec-forge/dist/drivers/gitlab.js +144 -0
  256. package/node_modules/@spexcode/spec-forge/dist/drivers.d.ts +10 -0
  257. package/node_modules/@spexcode/spec-forge/dist/drivers.js +83 -0
  258. package/node_modules/@spexcode/spec-forge/dist/index.d.ts +4 -0
  259. package/node_modules/@spexcode/spec-forge/dist/index.js +4 -0
  260. package/node_modules/@spexcode/spec-forge/dist/links.d.ts +15 -0
  261. package/node_modules/@spexcode/spec-forge/dist/links.js +65 -0
  262. package/node_modules/@spexcode/spec-forge/dist/needs-eval.d.ts +10 -0
  263. package/node_modules/@spexcode/spec-forge/dist/needs-eval.js +20 -0
  264. package/node_modules/@spexcode/spec-forge/dist/port.d.ts +53 -0
  265. package/node_modules/@spexcode/spec-forge/dist/port.js +1 -0
  266. package/node_modules/@spexcode/spec-forge/dist/resident.d.ts +7 -0
  267. package/node_modules/@spexcode/spec-forge/dist/resident.js +43 -0
  268. package/node_modules/@spexcode/spec-forge/package.json +32 -0
  269. package/package.json +33 -19
  270. package/spec-cli/bin/spex.mjs +0 -69
  271. package/spec-cli/src/anchors.ts +0 -706
  272. package/spec-cli/src/attach.ts +0 -43
  273. package/spec-cli/src/claude-headless.ts +0 -321
  274. package/spec-cli/src/cli.ts +0 -1115
  275. package/spec-cli/src/client.ts +0 -315
  276. package/spec-cli/src/cockpit.ts +0 -43
  277. package/spec-cli/src/codex-runtime-generations.ts +0 -646
  278. package/spec-cli/src/commit-surgery.ts +0 -68
  279. package/spec-cli/src/contract-filter.ts +0 -202
  280. package/spec-cli/src/delivery-queue.ts +0 -107
  281. package/spec-cli/src/doctor.ts +0 -516
  282. package/spec-cli/src/file-write.ts +0 -22
  283. package/spec-cli/src/gateway-auth.ts +0 -181
  284. package/spec-cli/src/gateway-hub.ts +0 -356
  285. package/spec-cli/src/gateway.ts +0 -368
  286. package/spec-cli/src/git.ts +0 -2180
  287. package/spec-cli/src/graph.ts +0 -221
  288. package/spec-cli/src/graphCache.ts +0 -641
  289. package/spec-cli/src/graphDelta.ts +0 -77
  290. package/spec-cli/src/graphStream.ts +0 -1019
  291. package/spec-cli/src/harness-select.ts +0 -77
  292. package/spec-cli/src/harness.ts +0 -2747
  293. package/spec-cli/src/headless-controller.ts +0 -63
  294. package/spec-cli/src/help.ts +0 -480
  295. package/spec-cli/src/host-resources.ts +0 -707
  296. package/spec-cli/src/host.ts +0 -611
  297. package/spec-cli/src/identity-presets.d.ts +0 -13
  298. package/spec-cli/src/identity-presets.js +0 -128
  299. package/spec-cli/src/index.ts +0 -730
  300. package/spec-cli/src/init.ts +0 -258
  301. package/spec-cli/src/issues-cli.ts +0 -276
  302. package/spec-cli/src/issues.ts +0 -237
  303. package/spec-cli/src/layout.ts +0 -557
  304. package/spec-cli/src/lint.ts +0 -458
  305. package/spec-cli/src/localIssues.ts +0 -538
  306. package/spec-cli/src/materialize.ts +0 -412
  307. package/spec-cli/src/mentions.ts +0 -81
  308. package/spec-cli/src/opencode-headless.ts +0 -205
  309. package/spec-cli/src/pi-headless.ts +0 -153
  310. package/spec-cli/src/plugin-harness.ts +0 -157
  311. package/spec-cli/src/process-identity.ts +0 -207
  312. package/spec-cli/src/project-identity.ts +0 -73
  313. package/spec-cli/src/project-store.ts +0 -17
  314. package/spec-cli/src/pty-bridge.ts +0 -396
  315. package/spec-cli/src/pty-helper.mjs +0 -96
  316. package/spec-cli/src/pty-native-helper.mjs +0 -22
  317. package/spec-cli/src/ranker.ts +0 -191
  318. package/spec-cli/src/reaper.ts +0 -125
  319. package/spec-cli/src/resilience.ts +0 -41
  320. package/spec-cli/src/reviewSnapshot.ts +0 -28
  321. package/spec-cli/src/reviews.ts +0 -405
  322. package/spec-cli/src/runtime-guard.ts +0 -35
  323. package/spec-cli/src/runtime-ownership.ts +0 -88
  324. package/spec-cli/src/search.bench.mjs +0 -80
  325. package/spec-cli/src/search.ts +0 -63
  326. package/spec-cli/src/session-cursors.ts +0 -91
  327. package/spec-cli/src/session-follow.ts +0 -182
  328. package/spec-cli/src/session-timeline.ts +0 -98
  329. package/spec-cli/src/sessions.ts +0 -3403
  330. package/spec-cli/src/sh.ts +0 -3
  331. package/spec-cli/src/slash-commands.ts +0 -318
  332. package/spec-cli/src/source-files.ts +0 -104
  333. package/spec-cli/src/specs.ts +0 -498
  334. package/spec-cli/src/supervise.ts +0 -245
  335. package/spec-cli/src/tree.ts +0 -118
  336. package/spec-cli/src/tsx-bin.ts +0 -18
  337. package/spec-cli/src/uninstall.ts +0 -171
  338. package/spec-cli/src/uploads.ts +0 -253
  339. package/spec-cli/src/worktree-sources.ts +0 -42
  340. package/spec-cli/templates/spec/project/.plugins/commands/supervisor/spec.md +0 -8
  341. package/spec-cli/templates/spec/project/.plugins/core/comment-altitude/spec.md +0 -28
  342. package/spec-cli/templates/spec/project/.plugins/core/spec.md +0 -23
  343. package/spec-cli/templates/spec/project/.plugins/prompts/atomic-landing/spec.md +0 -32
  344. package/spec-cli/templates/spec/project/.plugins/prompts/forge-link/spec.md +0 -9
  345. package/spec-cli/templates/spec/project/.plugins/prompts/memory-hygiene/spec.md +0 -15
  346. package/spec-cli/templates/spec/project/.plugins/prompts/reproduce-before-fix/spec.md +0 -18
  347. package/spec-dashboard/dist/assets/App-F9uaAVcH.js +0 -2
  348. package/spec-dashboard/dist/assets/Dashboard-Ba_jhxp1.js +0 -27
  349. package/spec-dashboard/dist/assets/Dashboard-C5ap-Sga.css +0 -1
  350. package/spec-dashboard/dist/assets/EvalsPage-FixoOg_n.js +0 -2
  351. package/spec-dashboard/dist/assets/IssuesPage-CuKLFhH3.js +0 -1
  352. package/spec-dashboard/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  353. package/spec-dashboard/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  354. package/spec-dashboard/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  355. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  356. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  357. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  358. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  359. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  360. package/spec-dashboard/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  361. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  362. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  363. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  364. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  365. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  366. package/spec-dashboard/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  367. package/spec-dashboard/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  368. package/spec-dashboard/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  369. package/spec-dashboard/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  370. package/spec-dashboard/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  371. package/spec-dashboard/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  372. package/spec-dashboard/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  373. package/spec-dashboard/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  374. package/spec-dashboard/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  375. package/spec-dashboard/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  376. package/spec-dashboard/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  377. package/spec-dashboard/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  378. package/spec-dashboard/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  379. package/spec-dashboard/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  380. package/spec-dashboard/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  381. package/spec-dashboard/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  382. package/spec-dashboard/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  383. package/spec-dashboard/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  384. package/spec-dashboard/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  385. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  386. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  387. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  388. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  389. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  390. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  391. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  392. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  393. package/spec-dashboard/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  394. package/spec-dashboard/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  395. package/spec-dashboard/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  396. package/spec-dashboard/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  397. package/spec-dashboard/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  398. package/spec-dashboard/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  399. package/spec-dashboard/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  400. package/spec-dashboard/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  401. package/spec-dashboard/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  402. package/spec-dashboard/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  403. package/spec-dashboard/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  404. package/spec-dashboard/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  405. package/spec-dashboard/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  406. package/spec-dashboard/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  407. package/spec-dashboard/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  408. package/spec-dashboard/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  409. package/spec-dashboard/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  410. package/spec-dashboard/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  411. package/spec-dashboard/dist/assets/MobileApp-CHgEHORJ.js +0 -2
  412. package/spec-dashboard/dist/assets/Modal-CQgYymmr.js +0 -1
  413. package/spec-dashboard/dist/assets/PageScroll-hT7UTLvD.js +0 -1
  414. package/spec-dashboard/dist/assets/ProjectsPage-CtXxakF9.js +0 -1
  415. package/spec-dashboard/dist/assets/SessionInterface-6GBZ9nXN.css +0 -32
  416. package/spec-dashboard/dist/assets/SessionInterface-Bpie-9fs.js +0 -39
  417. package/spec-dashboard/dist/assets/SessionWindow-CixDi4PI.js +0 -1
  418. package/spec-dashboard/dist/assets/Settings-C2MsucfE.js +0 -1
  419. package/spec-dashboard/dist/assets/Thread-C6Go8HRh.js +0 -13
  420. package/spec-dashboard/dist/assets/bindings-BC9vqpYU.js +0 -1
  421. package/spec-dashboard/dist/assets/data-B-RQmit6.js +0 -1
  422. package/spec-dashboard/dist/assets/index-CsI8DElI.css +0 -1
  423. package/spec-dashboard/dist/assets/index-DrVao0Ep.js +0 -41
  424. package/spec-dashboard/dist/assets/launch-BBH02b1v.js +0 -276
  425. package/spec-dashboard/dist/assets/launch-Cp579UoJ.css +0 -1
  426. package/spec-dashboard/dist/assets/terminalFont-C6oGNKrf.js +0 -1
  427. package/spec-dashboard/dist/index.html +0 -29
  428. package/spec-dashboard/src/reviewFilters.js +0 -322
  429. package/spec-dashboard/src/reviewQuery.js +0 -174
  430. package/spec-dashboard/src/session.js +0 -199
  431. package/spec-eval/src/cache.ts +0 -57
  432. package/spec-eval/src/cli.ts +0 -889
  433. package/spec-eval/src/evaltab.ts +0 -262
  434. package/spec-eval/src/filing.ts +0 -39
  435. package/spec-eval/src/freshness.ts +0 -557
  436. package/spec-eval/src/humanok.ts +0 -28
  437. package/spec-eval/src/scenariofresh.ts +0 -244
  438. package/spec-eval/src/scenarios.ts +0 -672
  439. package/spec-eval/src/sessioneval.ts +0 -2226
  440. package/spec-eval/src/sidecar.ts +0 -93
  441. package/spec-eval/src/timeline.ts +0 -54
  442. package/spec-forge/src/__fixtures__/github-forge.json +0 -63
  443. package/spec-forge/src/cache.ts +0 -66
  444. package/spec-forge/src/cli.ts +0 -99
  445. package/spec-forge/src/drivers/github.ts +0 -132
  446. package/spec-forge/src/drivers/gitlab.ts +0 -153
  447. package/spec-forge/src/drivers.ts +0 -73
  448. package/spec-forge/src/links.ts +0 -72
  449. package/spec-forge/src/needs-eval.ts +0 -29
  450. package/spec-forge/src/port.ts +0 -36
  451. package/spec-forge/src/resident.ts +0 -46
  452. /package/{spec-cli → node_modules/@spexcode/spec-cli}/README.md +0 -0
  453. /package/{spec-cli → node_modules/@spexcode/spec-cli}/hooks/compat/mark-active-0.5.2-eef1.fixture +0 -0
  454. /package/{spec-cli → node_modules/@spexcode/spec-cli}/hooks/compat/mark-active-sed-v0.fixture +0 -0
  455. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/commit-msg +0 -0
  456. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/post-checkout +0 -0
  457. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/post-merge +0 -0
  458. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/pre-commit +0 -0
  459. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/prepare-commit-msg +0 -0
  460. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/hooks/reference-transaction +0 -0
  461. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/commands/extract/spec.md +0 -0
  462. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/commands/regroup/spec.md +0 -0
  463. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/commands/rename/spec.md +0 -0
  464. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/commands/spec.md +0 -0
  465. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/commands/tidy/spec.md +0 -0
  466. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/idle/idle.sh +0 -0
  467. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/idle/spec.md +0 -0
  468. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/mark-active/mark-active.sh +0 -0
  469. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/mark-active/spec.md +0 -0
  470. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/session-fail/fail.sh +0 -0
  471. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/session-fail/spec.md +0 -0
  472. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/spec-first/spec.md +0 -0
  473. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/core/spec-of-file/spec.md +0 -0
  474. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/prompts/spec.md +0 -0
  475. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/skills/distill/digest.mjs +0 -0
  476. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/skills/distill/spec.md +0 -0
  477. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/skills/spec.md +0 -0
  478. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/.plugins/spec.md +0 -0
  479. /package/{spec-cli → node_modules/@spexcode/spec-cli}/templates/spec/project/spec.md +0 -0
  480. /package/{spec-cli → node_modules/@spexcode/spec-core}/templates/spexcode.json +0 -0
@@ -1,2226 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto'
2
- import { mkdtemp, readFile, rm } from 'node:fs/promises'
3
- import { tmpdir } from 'node:os'
4
- import { dirname, join, relative, resolve as resolvePath } from 'node:path'
5
- import {
6
- batchBlobTexts,
7
- batchRevisionOids,
8
- git,
9
- gitA,
10
- gitTry,
11
- pathRangeEvents,
12
- repoRoot,
13
- driftIndex,
14
- historyIndex,
15
- treeTextFiles,
16
- type DriftIndex,
17
- type DriftPathEvent,
18
- type ReviewDiffFile,
19
- } from '../../spec-cli/src/git.js'
20
- import { touchRoot } from '../../spec-cli/src/root-lru.js'
21
- import { loadSpecs } from '../../spec-cli/src/specs.js'
22
- import { mainBranch } from '../../spec-cli/src/layout.js'
23
- import { reviewIdentity, reviewPayload, type ReviewIdentity } from '../../spec-cli/src/sessions.js'
24
- import { loadEvalRemarkTracks } from '../../spec-cli/src/issues.js'
25
- import {
26
- anchorHitCommits,
27
- diffHunkRanges,
28
- extOf,
29
- extractorFor,
30
- extractors,
31
- parseRelation,
32
- relationClaimsPath,
33
- resolveAnchor,
34
- selectorsHitRanges,
35
- type AnchorHit,
36
- type Extractor,
37
- type RelationEntry,
38
- type Unit,
39
- } from '../../spec-cli/src/anchors.js'
40
- import { evalTimelines, evalContext, readBlobByHash, type EvalEntry, type EvalTimeline, type ScenarioInfo } from './evaltab.js'
41
- import { isUiPath } from './cli.js'
42
- import { readReadings } from './sidecar.js'
43
- import { parseScenarios, scenarioCodeAxis, scenarioHash, type Scenario } from './scenarios.js'
44
-
45
- // ---- the model ----
46
-
47
- type ScoreState = 'pass' | 'fail' | 'stalePass' | 'staleFail' | 'empty' | null
48
-
49
- export type ScenarioImpactReason = 'code' | 'contract' | 'measurement'
50
- export type SessionScenarioInfo = ScenarioInfo & { impact: ScenarioImpactReason[] }
51
-
52
- export type SessionImpactSelectorHit = AnchorHit & { path: string }
53
- export type SessionImpactScenarioDelta = {
54
- kind: 'added' | 'removed' | 'modified' | 'unchanged'
55
- semantic: boolean
56
- metadata: boolean
57
- metadataOnly: boolean
58
- }
59
- export type SessionImpactScenario = {
60
- name: string
61
- state: 'added' | 'removed' | 'present'
62
- impact: ScenarioImpactReason[]
63
- baseEffectiveCode: RelationEntry[]
64
- headEffectiveCode: RelationEntry[]
65
- selectorHits: SessionImpactSelectorHit[]
66
- baseScenarioHash: string | null
67
- headScenarioHash: string | null
68
- delta: SessionImpactScenarioDelta
69
- }
70
- export type SessionImpactNodeCause = {
71
- kind: 'spec' | 'eval' | 'code' | 'related' | 'contract' | 'measurement'
72
- paths: string[]
73
- scenarios: string[]
74
- selectorHits: SessionImpactSelectorHit[]
75
- }
76
- export type SessionImpactNode = {
77
- id: string
78
- causes: SessionImpactNodeCause[]
79
- scenarios: SessionImpactScenario[]
80
- }
81
- export type SessionImpactProjection = {
82
- base: string
83
- head: string
84
- revision: string
85
- nodes: SessionImpactNode[]
86
- }
87
- export type SessionImpactOptions = {
88
- base: string
89
- head: string
90
- measurements?: Readonly<Record<string, readonly string[]>>
91
- overlay?: SessionImpactOverlay
92
- }
93
-
94
- export type SessionImpactOverlay = {
95
- revision: string
96
- paths: string[]
97
- baseRanges: Record<string, [number, number][]>
98
- ranges: Record<string, [number, number][]>
99
- specs: SessionImpactSpecSnapshot[]
100
- evalSources: Record<string, string | null>
101
- files: Record<string, string | null>
102
- }
103
-
104
- export type SessionImpactSpecSnapshot = Pick<LoadedSpec,
105
- 'id' | 'path' | 'code' | 'codeEntries' | 'codeScoped' | 'related' | 'relatedEntries' | 'relatedScoped' | 'relationProblems'>
106
-
107
- export class SessionEvalUnavailableError extends Error {
108
- override name = 'SessionEvalUnavailableError'
109
- }
110
-
111
- export class SessionImpactUnavailableError extends SessionEvalUnavailableError {
112
- override name = 'SessionImpactUnavailableError'
113
- }
114
-
115
- export class SessionImpactRevisionMovedError extends SessionImpactUnavailableError {
116
- override name = 'SessionImpactRevisionMovedError'
117
- }
118
-
119
- type LoadedSpec = Awaited<ReturnType<typeof loadSpecs>>[number]
120
-
121
- async function impactGit(root: string, args: string[], operation: string): Promise<string> {
122
- const result = await gitTry(['-C', root, ...args])
123
- if (!result.ok) {
124
- const detail = result.stderr.trim() || `${result.failure ?? 'git'} failure`
125
- throw new SessionImpactUnavailableError(`session impact cannot ${operation}: ${detail}`)
126
- }
127
- return result.stdout
128
- }
129
-
130
- async function impactIndexGit(root: string, indexFile: string, args: string[], operation: string): Promise<string> {
131
- const result = await gitTry(['-C', root, ...args], { indexFile })
132
- if (!result.ok) {
133
- const detail = result.stderr.trim() || `${result.failure ?? 'git'} failure`
134
- throw new SessionImpactUnavailableError(`session impact cannot ${operation}: ${detail}`)
135
- }
136
- return result.stdout
137
- }
138
-
139
- async function impactCommit(root: string, selector: string): Promise<string> {
140
- const out = await impactGit(root, ['rev-parse', '--verify', `${selector}^{commit}`], `resolve revision '${selector}'`)
141
- const oid = out.trim()
142
- if (!oid) throw new SessionImpactUnavailableError(`session impact revision '${selector}' resolved to no commit`)
143
- return oid
144
- }
145
-
146
- type NameStatusChange = { status: string; before: string; after: string }
147
- function parseNameStatusChanges(out: string): NameStatusChange[] {
148
- const records = out.split('\0')
149
- const changes: NameStatusChange[] = []
150
- for (let index = 0; index < records.length;) {
151
- const status = records[index++]
152
- if (!status) continue
153
- const first = records[index++]
154
- if (!first) throw new SessionImpactUnavailableError(`session impact diff emitted '${status}' without a path`)
155
- if (/^[RC]/.test(status)) {
156
- const second = records[index++]
157
- if (!second) throw new SessionImpactUnavailableError(`session impact diff emitted '${status}' without both rename paths`)
158
- changes.push({ status, before: first, after: second })
159
- } else changes.push({ status, before: first, after: first })
160
- }
161
- return changes
162
- }
163
-
164
- async function revisionFile(root: string, revision: string, path: string): Promise<string | null> {
165
- const listed = await impactGit(root, ['-c', 'core.quotePath=false', 'ls-tree', '-z', '--name-only', revision, '--', path], `read ${revision}:${path}`)
166
- if (!listed.split('\0').includes(path)) return null
167
- return impactGit(root, ['show', `${revision}:${path}`], `read ${revision}:${path}`)
168
- }
169
-
170
- // the snapshot already carries parsed entries; a caller wanting one relation just picks it. This used to mint
171
- // `path#selector` STRINGS from the split path/scoped pair and hand them back to the parser to be turned into
172
- // the entries the loader had all along — a serialize/reparse round-trip through a form nobody stored.
173
- function loadedRelationEntries(spec: SessionImpactSpecSnapshot | undefined, relation: 'code' | 'related'): readonly RelationEntry[] {
174
- if (!spec) return []
175
- return relation === 'code' ? spec.codeEntries : spec.relatedEntries
176
- }
177
-
178
- function scenarioMetadata(scenario: Scenario, effectiveCode: readonly RelationEntry[]): string {
179
- return JSON.stringify({
180
- tags: scenario.tags ?? [],
181
- test: scenario.test ?? null,
182
- effectiveCode,
183
- related: scenario.related ?? [],
184
- })
185
- }
186
-
187
- type ImpactReadContext = {
188
- root: string
189
- base: string
190
- head: string
191
- committedPaths: ReadonlySet<string>
192
- changedPaths: ReadonlySet<string>
193
- overlay?: SessionImpactOverlay
194
- regs: ReturnType<typeof extractors>
195
- didx: DriftIndex | null
196
- entryImpacts: Map<string, Promise<{ paths: string[]; selectorHits: SessionImpactSelectorHit[] }>>
197
- windows: Map<string, DriftPathEvent[]>
198
- sources: Map<string, Promise<string | null>>
199
- units: Map<string, Promise<{ extractor: Extractor; units: Unit[] }>>
200
- }
201
-
202
- async function selectorSource(
203
- context: ImpactReadContext,
204
- revision: string,
205
- path: string,
206
- sourceView: 'base' | 'head',
207
- ): Promise<string | null> {
208
- if (sourceView === 'head' && context.overlay && Object.hasOwn(context.overlay.files, path)) return context.overlay.files[path]
209
- const key = `${revision}\0${path}`
210
- let pending = context.sources.get(key)
211
- if (!pending) {
212
- pending = revisionFile(context.root, revision, path)
213
- context.sources.set(key, pending)
214
- }
215
- return pending
216
- }
217
-
218
- async function validateSelectorEntry(
219
- context: ImpactReadContext,
220
- revision: string,
221
- entry: RelationEntry,
222
- sourceView: 'base' | 'head',
223
- ): Promise<{ extractor: Extractor; units: Unit[] }> {
224
- const x = extractorFor(context.regs, extOf(entry.path))
225
- if (!x) {
226
- throw new SessionImpactUnavailableError(`session impact selector '${entry.path}#${entry.selectors[0]}' is unavailable: no designated extractor for '.${extOf(entry.path)}'`)
227
- }
228
- const ready = x.ready()
229
- if (ready !== true) {
230
- throw new SessionImpactUnavailableError(`session impact selectors on '${entry.path}' are unavailable: ${ready}`)
231
- }
232
- const sourceIdentity = sourceView === 'head' && context.overlay && Object.hasOwn(context.overlay.files, entry.path)
233
- ? `overlay:${context.overlay.revision}`
234
- : 'exact'
235
- const key = `${revision}\0${sourceIdentity}\0${entry.path}\0${x.id}\0${x.memoKey(entry.path)}`
236
- let extracted = context.units.get(key)
237
- if (!extracted) {
238
- extracted = (async () => {
239
- const source = await selectorSource(context, revision, entry.path, sourceView)
240
- if (source === null) {
241
- throw new SessionImpactUnavailableError(`session impact selector '${entry.path}#${entry.selectors[0]}' is dead at ${revision.slice(0, 8)}: the file does not exist`)
242
- }
243
- try { return { extractor: x, units: x.extract(source, entry.path) } }
244
- catch (error: any) {
245
- throw new SessionImpactUnavailableError(`session impact selectors on '${entry.path}' are unextractable at ${revision.slice(0, 8)}: ${error?.message ?? String(error)}`)
246
- }
247
- })()
248
- context.units.set(key, extracted)
249
- }
250
- const { extractor, units } = await extracted
251
- for (const selector of entry.selectors) {
252
- const resolved = resolveAnchor(units, selector)
253
- if ('dead' in resolved) {
254
- throw new SessionImpactUnavailableError(`dead session impact selector '${entry.path}#${selector}' at ${revision.slice(0, 8)}: follow the rename or repair the code relation`)
255
- }
256
- if ('ambiguous' in resolved) {
257
- throw new SessionImpactUnavailableError(`ambiguous session impact selector '${entry.path}#${selector}' at ${revision.slice(0, 8)}: ${resolved.ambiguous} units share that name`)
258
- }
259
- }
260
- return { extractor, units }
261
- }
262
-
263
- function selectorEntriesForSnapshot(
264
- specs: readonly SessionImpactSpecSnapshot[],
265
- scenariosById: ReadonlyMap<string, readonly Scenario[]>,
266
- ): RelationEntry[] {
267
- const entries: RelationEntry[] = []
268
- for (const spec of specs) {
269
- entries.push(...loadedRelationEntries(spec, 'code'))
270
- entries.push(...loadedRelationEntries(spec, 'related'))
271
- for (const scenario of scenariosById.get(spec.id) ?? []) {
272
- entries.push(...parsedRelation(scenario.code ?? [], 'code', `scenario '${spec.id} · ${scenario.name}'`))
273
- entries.push(...parsedRelation(scenario.related ?? [], 'related', `scenario '${spec.id} · ${scenario.name}'`))
274
- }
275
- }
276
- const unique = new Map<string, RelationEntry>()
277
- for (const entry of entries) if (entry.selectors.length) unique.set(`${entry.path}\0${entry.selectors.join('\x1e')}`, entry)
278
- return [...unique.values()]
279
- }
280
-
281
- async function primeSelectorSources(
282
- context: ImpactReadContext,
283
- revision: string,
284
- paths: readonly string[],
285
- sourceView: 'base' | 'head',
286
- ): Promise<void> {
287
- const exactPaths = [...new Set(paths)].filter((path) => (
288
- !context.sources.has(`${revision}\0${path}`)
289
- && !(sourceView === 'head' && context.overlay && Object.hasOwn(context.overlay.files, path))
290
- )).sort()
291
- if (!exactPaths.length) return
292
- try {
293
- const oids = await batchRevisionOids(context.root, exactPaths.map((path) => `${revision}:${path}`))
294
- const blobs = await batchBlobTexts(context.root, oids.filter((oid): oid is string => !!oid))
295
- for (let index = 0; index < exactPaths.length; index++) {
296
- const path = exactPaths[index]
297
- const oid = oids[index]
298
- if (oid && !blobs.has(oid)) throw new Error(`cat-file returned no bytes for ${revision.slice(0, 8)}:${path}`)
299
- context.sources.set(`${revision}\0${path}`, Promise.resolve(oid ? blobs.get(oid)! : null))
300
- }
301
- } catch (error: any) {
302
- throw new SessionImpactUnavailableError(`session impact cannot batch-read selector sources at ${revision.slice(0, 8)}: ${error?.message ?? String(error)}`)
303
- }
304
- }
305
-
306
- async function impactForEntry(
307
- context: ImpactReadContext,
308
- entry: RelationEntry,
309
- options: { validateUnchanged?: boolean; validationRevision?: string; validationSide?: 'base' | 'head' } = {},
310
- ): Promise<{ paths: string[]; selectorHits: SessionImpactSelectorHit[] }> {
311
- const revision = options.validationRevision ?? context.head
312
- const sourceView = options.validationSide ?? 'head'
313
- const key = `${context.base}\0${context.head}\0${context.overlay?.revision ?? ''}\0${sourceView}\0${revision}\0${entry.path}\0${entry.selectors.join('\x1e')}\0${options.validateUnchanged ? 1 : 0}`
314
- let pending = context.entryImpacts.get(key)
315
- if (pending) return pending
316
- pending = (async () => {
317
- // Reuse sessioneval's existing relation claim matcher over the ONE exact base..head changed set. The
318
- // projector adds no impact-local glob/path grammar; selector entries then narrow that file result.
319
- const changed = [...context.changedPaths].filter((path) => codeClaims([entry.path], path))
320
- if (!entry.selectors.length) return { paths: changed.sort(), selectorHits: [] }
321
- // Resolution is a validity claim about the selected HEAD, independent of whether the file moved.
322
- // Validating first prevents a dead selector from becoming a vacuous no-hit/fresh answer.
323
- if (!changed.length && !options.validateUnchanged) return { paths: [], selectorHits: [] }
324
- const { units } = await validateSelectorEntry(context, revision, entry, sourceView)
325
- if (!changed.length) return { paths: [], selectorHits: [] }
326
- const selectorHits: SessionImpactSelectorHit[] = []
327
- const committed = [...context.committedPaths].some((path) => codeClaims([entry.path], path))
328
- if (committed) {
329
- if (!context.didx) throw new SessionImpactUnavailableError('session impact has committed paths but no exact event index')
330
- const windowKey = `${revision}\0${entry.path}`
331
- let window = context.windows.get(windowKey)
332
- if (!window) {
333
- const projected = pathRangeEvents(context.didx, context.base, entry.path, revision)
334
- if (!projected) throw new SessionImpactUnavailableError(`session impact cannot place base ${context.base.slice(0, 8)} in the exact event topology`)
335
- window = projected
336
- context.windows.set(windowKey, window)
337
- }
338
- try {
339
- const hits = await anchorHitCommits(context.root, window, [...entry.selectors], context.regs)
340
- for (const hit of hits) selectorHits.push({ path: entry.path, ...hit })
341
- } catch (error: any) {
342
- throw new SessionImpactUnavailableError(`session impact selector '${entry.path}#${entry.selectors.join(',#')}' is unavailable: ${error?.message ?? String(error)}`)
343
- }
344
- }
345
- if (context.overlay && context.overlay.paths.some((path) => codeClaims([entry.path], path))) {
346
- const ranges = sourceView === 'base' ? context.overlay.baseRanges : context.overlay.ranges
347
- const touched = selectorsHitRanges(units, entry.selectors, ranges[entry.path] ?? [])
348
- if (touched.length) selectorHits.push({
349
- path: entry.path,
350
- commit: `worktree:${context.overlay.revision.slice(0, 12)}`,
351
- selectors: touched,
352
- })
353
- }
354
- return { paths: selectorHits.length ? changed.sort() : [], selectorHits }
355
- })()
356
- context.entryImpacts.set(key, pending)
357
- return pending
358
- }
359
-
360
- async function impactForEntries(
361
- context: ImpactReadContext,
362
- entries: readonly RelationEntry[],
363
- options: { validateUnchanged?: boolean; validationRevision?: string; validationSide?: 'base' | 'head' } = {},
364
- ): Promise<{ paths: string[]; selectorHits: SessionImpactSelectorHit[] }> {
365
- const results = await Promise.all(entries.map((entry) => impactForEntry(context, entry, options)))
366
- return {
367
- paths: [...new Set(results.flatMap((result) => result.paths))].sort(),
368
- selectorHits: results.flatMap((result) => result.selectorHits),
369
- }
370
- }
371
-
372
- function pushNodeCause(
373
- causes: SessionImpactNodeCause[],
374
- kind: SessionImpactNodeCause['kind'],
375
- paths: readonly string[] = [],
376
- scenarios: readonly string[] = [],
377
- selectorHits: readonly SessionImpactSelectorHit[] = [],
378
- ): void {
379
- let cause = causes.find((candidate) => candidate.kind === kind)
380
- if (!cause) {
381
- cause = { kind, paths: [], scenarios: [], selectorHits: [] }
382
- causes.push(cause)
383
- }
384
- cause.paths = [...new Set([...cause.paths, ...paths])].sort()
385
- cause.scenarios = [...new Set([...cause.scenarios, ...scenarios])].sort()
386
- const seen = new Set(cause.selectorHits.map((hit) => JSON.stringify(hit)))
387
- for (const hit of selectorHits) {
388
- const key = JSON.stringify(hit)
389
- if (!seen.has(key)) { seen.add(key); cause.selectorHits.push(hit) }
390
- }
391
- }
392
-
393
- function parsedRelation(raw: readonly string[], relation: 'code' | 'related', owner: string): RelationEntry[] {
394
- const parsed = parseRelation([...raw], relation)
395
- if (parsed.problems.length) {
396
- throw new SessionImpactUnavailableError(`session impact ${owner} has invalid ${relation}: ${parsed.problems.join('; ')}`)
397
- }
398
- return parsed.entries
399
- }
400
-
401
- // Public, exact-revision impact projection. It reads both spec trees and all scenario declarations from
402
- // immutable Git objects, reuses the canonical relation/anchor engine, then re-resolves the caller's selectors
403
- // before publication. Callers may pass branch names, but never receive a projection spanning two ref states.
404
- // @@@ the projection is the PERMANENT half ([[taste]] 19) - what commits between two immutable trees changed
405
- // which paths, and what each side declared, are facts about those commits: they cannot change, so a repeat
406
- // projection over the same inputs is pure recomputation. It used to be deliberately build-local, which was
407
- // right while it was cheap; on a branch 840 commits from its base it is 2.4s, and a detail open pays it
408
- // EVERY time because a focused build deposits no cut. Every input that can move the result is in the key —
409
- // the two resolved commit oids, the live overlay's own content revision, and the measurement axis — so a hit
410
- // answers the identical question. The promise is cached, not the value, so concurrent openers join one
411
- // projection; a rejection is never retained, keeping an unavailable selector loud on every read.
412
- const impactSlots = Math.max(4, Number(process.env.SPEXCODE_IMPACT_SLOTS || 32))
413
- const impactRoots = new Map<string, string>()
414
- const impactMemo = new Map<string, Promise<SessionImpactProjection>>()
415
- function impactKey(root: string, base: string, head: string, options: SessionImpactOptions): string {
416
- const measurements = Object.entries(options.measurements ?? {})
417
- .map(([node, names]) => `${node}:${[...names].sort().join(',')}`).sort().join('\u001f')
418
- return [resolvePath(root), base, head, options.overlay?.revision ?? '', createHash('sha256').update(measurements).digest('hex')].join('\0')
419
- }
420
-
421
- export async function projectSessionImpact(root: string, options: SessionImpactOptions): Promise<SessionImpactProjection> {
422
- const [base, head] = await Promise.all([
423
- impactCommit(root, options.base),
424
- impactCommit(root, options.head),
425
- ])
426
- const memoKey = impactKey(root, base, head, options)
427
- const memoHit = impactMemo.get(memoKey)
428
- if (memoHit) return memoHit
429
- const flight = projectSessionImpactUncached(root, options, base, head)
430
- impactMemo.set(memoKey, flight)
431
- flight.catch(() => { if (impactMemo.get(memoKey) === flight) impactMemo.delete(memoKey) })
432
- touchRoot(impactRoots, impactMemo, resolvePath(root), memoKey, impactSlots)
433
- return flight
434
- }
435
-
436
- // the slow, obviously-correct recompute — kept whole as the specification the cached path must equal
437
- export async function projectSessionImpactUncached(
438
- root: string,
439
- options: SessionImpactOptions,
440
- base: string,
441
- head: string,
442
- ): Promise<SessionImpactProjection> {
443
- const ancestry = await gitTry(['-C', root, 'merge-base', '--is-ancestor', base, head])
444
- if (!ancestry.ok) {
445
- if (ancestry.failure === 'exit') {
446
- throw new SessionImpactUnavailableError(`session impact base ${base.slice(0, 8)} is not an ancestor of head ${head.slice(0, 8)}; use the session merge-base as base`)
447
- }
448
- throw new SessionImpactUnavailableError(`session impact cannot verify base/head ancestry: ${ancestry.stderr.trim() || ancestry.failure}`)
449
- }
450
- // One immutable .spec tree read per distinct revision supplies BOTH spec relations and eval declarations.
451
- // Build-local by design: the memo above owns reuse ACROSS builds, this map owns it within one.
452
- const treeByRevision = new Map<string, ReadonlyMap<string, string>>()
453
- const readTree = (revision: string): ReadonlyMap<string, string> => {
454
- const cached = treeByRevision.get(revision)
455
- if (cached) return cached
456
- try {
457
- const tree = treeTextFiles(root, revision, '.spec')
458
- treeByRevision.set(revision, tree)
459
- return tree
460
- } catch (error: any) {
461
- throw new SessionImpactUnavailableError(`session impact cannot read ${revision.slice(0, 8)} declarations: ${error?.message ?? String(error)}`)
462
- }
463
- }
464
- const baseTree = readTree(base)
465
- const headTree = options.overlay ? null : readTree(head)
466
- const [baseSpecs, headSpecs] = await Promise.all([
467
- loadSpecs(root, { tip: base, history: null, drift: null, snapshot: { tip: base, files: baseTree } }),
468
- options.overlay
469
- ? Promise.resolve(options.overlay.specs)
470
- : loadSpecs(root, { tip: head, history: null, drift: null, snapshot: { tip: head, files: headTree! } }),
471
- ])
472
- const committedChanges = parseNameStatusChanges(await impactGit(
473
- root,
474
- ['-c', 'core.quotePath=false', 'diff', '--name-status', '-z', '-M', base, head],
475
- `diff ${base.slice(0, 8)}..${head.slice(0, 8)}`,
476
- ))
477
- const committedPaths = new Set(committedChanges.flatMap((change) => [change.before, change.after]))
478
- let didx: DriftIndex | null = null
479
- if (committedPaths.size) {
480
- try { didx = await driftIndex(root, head) }
481
- catch (error: any) {
482
- throw new SessionImpactUnavailableError(`session impact cannot derive the exact ${base.slice(0, 8)}..${head.slice(0, 8)} event window: ${error?.message ?? String(error)}`)
483
- }
484
- }
485
- const changedPaths = new Set([...committedPaths, ...(options.overlay?.paths ?? [])])
486
- const context: ImpactReadContext = {
487
- root,
488
- base,
489
- head,
490
- committedPaths,
491
- changedPaths,
492
- overlay: options.overlay,
493
- regs: extractors(root),
494
- didx,
495
- entryImpacts: new Map(),
496
- windows: new Map(),
497
- sources: new Map(),
498
- units: new Map(),
499
- }
500
- const baseById = new Map<string, SessionImpactSpecSnapshot>(baseSpecs.map((spec) => [spec.id, spec]))
501
- const headById = new Map<string, SessionImpactSpecSnapshot>(headSpecs.map((spec) => [spec.id, spec]))
502
- const nodeIds = [...new Set([...baseById.keys(), ...headById.keys()])].sort()
503
- if (options.overlay) {
504
- for (const path of options.overlay.paths) {
505
- if (!Object.hasOwn(options.overlay.files, path)
506
- || !Object.hasOwn(options.overlay.baseRanges, path)
507
- || !Object.hasOwn(options.overlay.ranges, path)) {
508
- throw new SessionImpactUnavailableError(`session impact overlay '${options.overlay.revision}' is incomplete for '${path}'`)
509
- }
510
- }
511
- }
512
- const scenariosAt = (
513
- side: 'base' | 'head',
514
- spec: SessionImpactSpecSnapshot,
515
- ): Scenario[] => {
516
- const evalPath = join(dirname(spec.path), 'eval.md')
517
- let source: string | null
518
- if (side === 'base') source = baseTree.get(evalPath) ?? null
519
- else if (options.overlay) {
520
- if (!Object.hasOwn(options.overlay.evalSources, evalPath)) {
521
- throw new SessionImpactUnavailableError(`session impact overlay '${options.overlay.revision}' has no declaration snapshot for '${evalPath}'`)
522
- }
523
- source = options.overlay.evalSources[evalPath]
524
- } else source = headTree!.get(evalPath) ?? null
525
- if (source === null) return []
526
- try { return parseScenarios(source) }
527
- catch (error: any) {
528
- throw new SessionImpactUnavailableError(`session impact cannot parse ${side} declarations '${evalPath}': ${error?.message ?? String(error)}`)
529
- }
530
- }
531
- const baseScenariosById = new Map(baseSpecs.map((spec) => [spec.id, scenariosAt('base', spec)]))
532
- const headScenariosById = new Map(headSpecs.map((spec) => [spec.id, scenariosAt('head', spec)]))
533
- const baseSelectorEntries = selectorEntriesForSnapshot(baseSpecs, baseScenariosById)
534
- const headSelectorEntries = selectorEntriesForSnapshot(headSpecs, headScenariosById)
535
- await primeSelectorSources(context, base, baseSelectorEntries.map((entry) => entry.path), 'base')
536
- await primeSelectorSources(context, head, headSelectorEntries.map((entry) => entry.path), 'head')
537
- await Promise.all([
538
- ...baseSelectorEntries.map((entry) => validateSelectorEntry(context, base, entry, 'base')),
539
- ...headSelectorEntries.map((entry) => validateSelectorEntry(context, head, entry, 'head')),
540
- ])
541
- const nodes: SessionImpactNode[] = []
542
-
543
- for (const id of nodeIds) {
544
- const baseSpec = baseById.get(id)
545
- const headSpec = headById.get(id)
546
- const causes: SessionImpactNodeCause[] = []
547
- const baseSpecPath = baseSpec?.path ?? ''
548
- const headSpecPath = headSpec?.path ?? ''
549
- const specPaths = [...new Set([baseSpecPath, headSpecPath].filter(Boolean))]
550
- const specChanged = [...changedPaths].filter((path) => specPaths.some((claim) => codeClaims([claim], path)))
551
- if (specChanged.length) pushNodeCause(causes, 'spec', specChanged)
552
-
553
- if (baseSpec?.relationProblems.length || headSpec?.relationProblems.length) {
554
- throw new SessionImpactUnavailableError(`session impact node '${id}' has invalid relations: ${[
555
- ...(baseSpec?.relationProblems ?? []), ...(headSpec?.relationProblems ?? []),
556
- ].join('; ')}`)
557
- }
558
-
559
- const baseEvalPath = baseSpec ? join(dirname(baseSpec.path), 'eval.md') : ''
560
- const headEvalPath = headSpec ? join(dirname(headSpec.path), 'eval.md') : ''
561
- const baseScenarios = baseScenariosById.get(id) ?? []
562
- const headScenarios = headScenariosById.get(id) ?? []
563
- const evalPaths = [...new Set([baseEvalPath, headEvalPath].filter(Boolean))]
564
- const evalChanged = [...changedPaths].filter((path) => evalPaths.some((claim) => codeClaims([claim], path)))
565
- if (evalChanged.length) pushNodeCause(causes, 'eval', evalChanged)
566
-
567
- // no second validity gate here: relationProblems above already threw for either side, and it is the
568
- // SAME parse — a re-parse of rows minted from those entries cannot surface a problem the loader did not.
569
- const baseNodeCodeEntries = loadedRelationEntries(baseSpec, 'code')
570
- const headNodeCodeEntries = loadedRelationEntries(headSpec, 'code')
571
- const nodeCodeMoved = !!baseSpec && !!headSpec
572
- && JSON.stringify(baseNodeCodeEntries) !== JSON.stringify(headNodeCodeEntries)
573
- const nodeCodeReads = nodeCodeMoved
574
- ? await Promise.all([
575
- impactForEntries(context, baseNodeCodeEntries, { validateUnchanged: true, validationRevision: base, validationSide: 'base' }),
576
- impactForEntries(context, headNodeCodeEntries, { validateUnchanged: true, validationRevision: head, validationSide: 'head' }),
577
- ])
578
- : [await impactForEntries(context, headSpec ? headNodeCodeEntries : baseNodeCodeEntries, {
579
- validateUnchanged: !baseSpec || !headSpec,
580
- validationRevision: headSpec ? head : base,
581
- validationSide: headSpec ? 'head' : 'base',
582
- })]
583
- const nodeCodeImpact = {
584
- paths: [...new Set(nodeCodeReads.flatMap((read) => read.paths))].sort(),
585
- selectorHits: nodeCodeReads.flatMap((read) => read.selectorHits),
586
- }
587
- if (nodeCodeImpact.paths.length) pushNodeCause(causes, 'code', nodeCodeImpact.paths, [], nodeCodeImpact.selectorHits)
588
-
589
- // Related declarations belong to their own owners. Combine their parsed DATA entries after validation;
590
- // parsing one synthetic concatenated relation would turn two legitimate owners naming the same path into
591
- // a fake duplicate/mixed-form schema error.
592
- const relatedFor = (spec: SessionImpactSpecSnapshot | undefined, scenarios: readonly Scenario[]) => [
593
- ...loadedRelationEntries(spec, 'related'),
594
- ...scenarios.flatMap((scenario) => (
595
- parsedRelation(scenario.related ?? [], 'related', `scenario '${id} · ${scenario.name}'`)
596
- )),
597
- ]
598
- const baseRelatedEntries = relatedFor(baseSpec, baseScenarios)
599
- const headRelatedEntries = relatedFor(headSpec, headScenarios)
600
- const relatedMoved = !!baseSpec && !!headSpec
601
- && JSON.stringify(baseRelatedEntries) !== JSON.stringify(headRelatedEntries)
602
- const relatedReads = relatedMoved
603
- ? await Promise.all([
604
- impactForEntries(context, baseRelatedEntries, { validateUnchanged: true, validationRevision: base, validationSide: 'base' }),
605
- impactForEntries(context, headRelatedEntries, { validateUnchanged: true, validationRevision: head, validationSide: 'head' }),
606
- ])
607
- : [await impactForEntries(context, headSpec ? headRelatedEntries : baseRelatedEntries, {
608
- validateUnchanged: !baseSpec || !headSpec,
609
- validationRevision: headSpec ? head : base,
610
- validationSide: headSpec ? 'head' : 'base',
611
- })]
612
- const relatedImpact = {
613
- paths: [...new Set(relatedReads.flatMap((read) => read.paths))].sort(),
614
- selectorHits: relatedReads.flatMap((read) => read.selectorHits),
615
- }
616
- if (relatedImpact.paths.length) pushNodeCause(causes, 'related', relatedImpact.paths, [], relatedImpact.selectorHits)
617
-
618
- const baseByName = new Map(baseScenarios.map((scenario) => [scenario.name, scenario]))
619
- const headByName = new Map(headScenarios.map((scenario) => [scenario.name, scenario]))
620
- const scenarioNames = [...new Set([...baseByName.keys(), ...headByName.keys()])].sort()
621
- const measured = new Set(options.measurements?.[id] ?? [])
622
- const scenarios: SessionImpactScenario[] = []
623
- for (const name of scenarioNames) {
624
- const before = baseByName.get(name)
625
- const after = headByName.get(name)
626
- const state = !before ? 'added' : !after ? 'removed' : 'present'
627
- const baseScenarioHash = before ? scenarioHash(before) : null
628
- const headScenarioHash = after ? scenarioHash(after) : null
629
- const semantic = !before || !after || baseScenarioHash !== headScenarioHash
630
- const baseAxis = before ? scenarioCodeAxis(before.code, loadedRelationEntries(baseSpec, 'code')) : { entries: [], paths: [], problems: [] }
631
- const headAxis = after ? scenarioCodeAxis(after.code, loadedRelationEntries(headSpec, 'code')) : { entries: [], paths: [], problems: [] }
632
- if (baseAxis.problems.length || headAxis.problems.length) {
633
- throw new SessionImpactUnavailableError(`session impact scenario '${id} · ${name}' has invalid code: ${[
634
- ...baseAxis.problems, ...headAxis.problems,
635
- ].join('; ')}`)
636
- }
637
- // Metadata is the RESOLVED measurement pointer, not only bytes authored in this scenario block. A
638
- // declaration without own code inherits the node relation at each revision, so node #alpha -> #beta is
639
- // a metadata move for that scenario even though its eval.md block did not change.
640
- const metadata = !!before && !!after
641
- && scenarioMetadata(before, baseAxis.entries) !== scenarioMetadata(after, headAxis.entries)
642
- const effectiveCodeMoved = JSON.stringify(baseAxis.entries) !== JSON.stringify(headAxis.entries)
643
- const kind: SessionImpactScenarioDelta['kind'] = !before ? 'added' : !after ? 'removed'
644
- : semantic || metadata ? 'modified' : 'unchanged'
645
- const codeReads = before && after && effectiveCodeMoved
646
- ? await Promise.all([
647
- impactForEntries(context, baseAxis.entries, { validateUnchanged: true, validationRevision: base, validationSide: 'base' }),
648
- impactForEntries(context, headAxis.entries, { validateUnchanged: true, validationRevision: head, validationSide: 'head' }),
649
- ])
650
- : [await impactForEntries(context, (after ? headAxis : baseAxis).entries, {
651
- validateUnchanged: kind === 'added' || kind === 'removed',
652
- validationRevision: after ? head : base,
653
- validationSide: after ? 'head' : 'base',
654
- })]
655
- const code = {
656
- paths: [...new Set(codeReads.flatMap((read) => read.paths))].sort(),
657
- selectorHits: codeReads.flatMap((read) => read.selectorHits),
658
- }
659
- const impact: ScenarioImpactReason[] = []
660
- if (code.paths.length) impact.push('code')
661
- if (semantic) impact.push('contract')
662
- if (measured.has(name)) impact.push('measurement')
663
- if (code.paths.length) pushNodeCause(causes, 'code', code.paths, [name], code.selectorHits)
664
- if (semantic) pushNodeCause(causes, 'contract', evalChanged, [name])
665
- if (measured.has(name)) pushNodeCause(causes, 'measurement', [], [name])
666
- scenarios.push({
667
- name,
668
- state,
669
- impact,
670
- baseEffectiveCode: baseAxis.entries,
671
- headEffectiveCode: headAxis.entries,
672
- selectorHits: code.selectorHits,
673
- baseScenarioHash,
674
- headScenarioHash,
675
- delta: { kind, semantic, metadata, metadataOnly: metadata && !semantic },
676
- })
677
- }
678
-
679
- if (causes.length || scenarios.some((scenario) => scenario.delta.kind !== 'unchanged' || scenario.impact.length)) {
680
- nodes.push({ id, causes, scenarios })
681
- }
682
- }
683
-
684
- const [baseAfter, headAfter] = await Promise.all([
685
- impactCommit(root, options.base),
686
- impactCommit(root, options.head),
687
- ])
688
- if (baseAfter !== base || headAfter !== head) {
689
- throw new SessionImpactRevisionMovedError(`session impact revisions moved while projecting: base ${base.slice(0, 8)} -> ${baseAfter.slice(0, 8)}, head ${head.slice(0, 8)} -> ${headAfter.slice(0, 8)}; retry the projection`)
690
- }
691
- const revision = createHash('sha256').update(JSON.stringify({ base, head, overlay: options.overlay?.revision ?? null, nodes })).digest('hex')
692
- return { base, head, revision, nodes }
693
- }
694
-
695
- type SessionEvalReading = EvalEntry & { inSession: boolean }
696
-
697
- export function scopeSessionScenarioRows(
698
- current: Scenario[],
699
- scenarioInfo: ScenarioInfo[],
700
- evals: SessionEvalReading[],
701
- projected: readonly SessionImpactScenario[],
702
- ): { scenarios: SessionScenarioInfo[]; evals: SessionEvalReading[] } {
703
- const impactByName = new Map(projected
704
- .filter((scenario) => scenario.state !== 'removed' && scenario.impact.length)
705
- .map((scenario) => [scenario.name, scenario.impact]))
706
- const infoByName = new Map(scenarioInfo.map((scenario) => [scenario.name, scenario]))
707
- const scenarios: SessionScenarioInfo[] = current.filter((scenario) => impactByName.has(scenario.name)).map((scenario) => ({
708
- ...(infoByName.get(scenario.name) ?? {
709
- name: scenario.name, expected: scenario.expected,
710
- ...(scenario.tags?.length ? { tags: scenario.tags } : {}),
711
- ...(scenario.test ? { test: scenario.test } : {}),
712
- ...(scenario.code?.length ? { code: scenario.code } : {}),
713
- }),
714
- impact: impactByName.get(scenario.name)!,
715
- }))
716
- const names = new Set(scenarios.map((scenario) => scenario.name))
717
- return { scenarios, evals: evals.filter((reading) => names.has(reading.scenario)) }
718
- }
719
-
720
- export function completeExportNodeIds(
721
- changedNodeIds: Iterable<string>,
722
- scopedNodeIds: Iterable<string>,
723
- ): string[] {
724
- return [...new Set([...changedNodeIds, ...scopedNodeIds])]
725
- }
726
-
727
- // one eval reading rendered for the export: the latest measurement of one scenario, with its evidence
728
- // resolved to inline bytes (an image data-URI, or transcript text) so the document is self-contained.
729
- export type ExportReading = {
730
- scenario: string
731
- expected: string
732
- impact: ScenarioImpactReason[]
733
- verdict?: EvalEntry['verdict']
734
- fresh: boolean
735
- staleAxes: string[]
736
- score: ScoreState
737
- // legacy instrument tag ('manual@1') — present on old readings only.
738
- evaluator?: string
739
- ts: string
740
- evidence:
741
- | { kind: 'image'; dataUri: string }
742
- | { kind: 'video'; dataUri: string }
743
- | { kind: 'transcript'; text: string }
744
- | { kind: 'data'; text: string }
745
- | { kind: 'miss' }
746
- | { kind: 'none' }
747
- }
748
-
749
- export type ExportUnmeasured = {
750
- scenario: string
751
- expected: string
752
- impact: ScenarioImpactReason[]
753
- }
754
-
755
- // patch ''/old·new null = nothing to show (added → no old, deleted → no new), past the enrichment cap (omitted), or too large (truncated)
756
- export type ExportFile = ReviewDiffFile & {
757
- patch: string
758
- oldText: string | null
759
- newText: string | null
760
- truncated: boolean
761
- omitted: boolean
762
- }
763
-
764
- // one changed spec node: its diff slice (the files this node owns that the session touched) joined with its
765
- // measured loss (latest reading per scenario). A frontend node with no eval.md is an honest blind spot.
766
- export type ExportNode = {
767
- id: string
768
- title: string
769
- hue: number
770
- desc: string
771
- files: ExportFile[]
772
- additions: number
773
- deletions: number
774
- hasEvalFile: boolean
775
- uncoveredFrontend: boolean
776
- affectedScenarios: number
777
- score: ScoreState
778
- readings: ExportReading[]
779
- unmeasured: ExportUnmeasured[]
780
- }
781
-
782
- export type ExportGate = { label: string; ok: boolean; detail: string }
783
-
784
- export type ExportModel = {
785
- id: string
786
- node: string | null
787
- branch: string | null
788
- title: string // DERIVED headline (the node, else the branch) — no agent-authored claim
789
- generatedAt: string
790
- ahead: number
791
- dirtyNonRuntime: number
792
- gates: ExportGate[]
793
- score: { passed: number; total: number; fresh: number } // the eval summary across all nodes
794
- impact: SessionImpactProjection
795
- nodes: ExportNode[]
796
- otherFiles: ExportFile[] // changed files no spec node claims
797
- }
798
-
799
- // null when no session has that id (route → 404).
800
- export async function buildExportModel(id: string): Promise<ExportModel | null> {
801
- const payload = await reviewPayload(id)
802
- if (!payload) return null
803
- // root EVERYTHING at the SESSION's worktree — readings, freshness, AND the spec tree itself. The
804
- // worktree's .spec is the branch's pending proposal ([[source-of-truth]]): a node the branch ADDED
805
- // exists only there, so a trunk-rooted loadSpecs would silently drop it from the model (the 0fca
806
- // family's node-existence layer). No worktree → the backend checkout, unchanged.
807
- const wtPath = worktreePathForBranch(payload.branch)
808
- const ctxRoot = wtPath ?? repoRoot()
809
- const specs = await loadSpecs(ctxRoot)
810
- const specById = new Map(specs.map((s) => [s.id, s]))
811
- const [didx, hidx] = await Promise.all([driftIndex(ctxRoot), historyIndex(ctxRoot)])
812
- const ctx = await evalContext(ctxRoot, specs, didx, hidx)
813
-
814
- // enrich each changed file with its unified diff + full before/after content (derived from the session
815
- // worktree at the merge-base ↔ HEAD), so the proof can drill summary → diff → whole-file comparison with no
816
- // extra fetch. Capped at MAX_ENRICHED_FILES so a huge changeset can't bloat the page; the rest keep their
817
- // row but say so (omitted), never silently blank.
818
- const { impact, shas } = await sessionImpactForContext(id, ctx, wtPath)
819
- const base = impact.base
820
- const scopedNodes = await sessionScopeNodes(id, ctx, impact, shas)
821
- const enriched = new Map<string, ExportFile>()
822
- let budget = MAX_ENRICHED_FILES
823
- for (const f of payload.diff) {
824
- if (wtPath && base && budget > 0) { enriched.set(f.path, await enrichFile(wtPath, base, f)); budget-- }
825
- else enriched.set(f.path, { ...f, patch: '', oldText: null, newText: null, truncated: false, omitted: !!(wtPath && base) })
826
- }
827
-
828
- // group the session's real changes (merge-base diff) by the spec node that owns each file.
829
- const byNode = new Map<string, ExportFile[]>()
830
- const otherFiles: ExportFile[] = []
831
- for (const f of payload.diff) {
832
- const nid = nodeForFile(f.path, specs, payload.node)
833
- const pf = enriched.get(f.path)!
834
- if (nid) { const arr = byNode.get(nid) ?? []; arr.push(pf); byNode.set(nid, arr) }
835
- else otherFiles.push(pf)
836
- }
837
- const nodes: ExportNode[] = []
838
- let passed = 0, total = 0, fresh = 0
839
- const scopedById = new Map(scopedNodes.map((node) => [node.id, node]))
840
- const evalById = new Map(ctx.ynodes.map((node) => [node.id, node]))
841
- const nodeIds = completeExportNodeIds(byNode.keys(), scopedById.keys())
842
- for (const id of nodeIds) {
843
- const scoped = scopedById.get(id)
844
- const spec = specById.get(id)!
845
- const files = byNode.get(id) ?? []
846
- const projection = scoped ? scopedScenarioReadings(scoped.scenarios, scoped.evals) : { latest: [], unmeasured: [] }
847
- const impactByName = new Map(scoped?.scenarios.map((scenario) => [scenario.name, scenario.impact]) ?? [])
848
- const readings = await Promise.all(projection.latest.map((reading) => toExportReading(reading, impactByName.get(reading.scenario) ?? [])))
849
- const unmeasured = projection.unmeasured.map((scenario) => ({
850
- scenario: scenario.name,
851
- expected: scenario.expected,
852
- impact: scenario.impact,
853
- }))
854
- total += scoped?.scenarios.length ?? 0
855
- for (const r of projection.latest) {
856
- if (r.fresh) fresh++
857
- if (r.fresh && r.verdict?.status === 'pass') passed++
858
- }
859
- nodes.push({
860
- id,
861
- title: scoped?.title ?? spec.title,
862
- hue: scoped?.hue ?? spec.hue,
863
- desc: scoped?.desc ?? spec.desc,
864
- files,
865
- additions: files.reduce((a, f) => a + f.additions, 0),
866
- deletions: files.reduce((a, f) => a + f.deletions, 0),
867
- hasEvalFile: scoped?.hasEvalFile ?? evalById.has(id),
868
- uncoveredFrontend: scoped?.uncoveredFrontend ?? false,
869
- affectedScenarios: scoped?.scenarios.length ?? 0,
870
- score: nodeScore(scoped?.hasEvalFile ?? evalById.has(id), projection.latest, scoped?.scenarios.length ?? 0),
871
- readings,
872
- unmeasured,
873
- })
874
- }
875
- // affected scenarios first, then by amount changed — review work leads while every changed file remains.
876
- nodes.sort((a, b) => (b.affectedScenarios - a.affectedScenarios) || ((b.additions + b.deletions) - (a.additions + a.deletions)))
877
-
878
- // the headline is DERIVED — the node the session is on, else its branch, else the id. No agent claim.
879
- const primary = payload.node && specById.has(payload.node) ? specById.get(payload.node)!.title : null
880
- const title = primary || payload.node || payload.branch || id.slice(0, 8)
881
-
882
- return {
883
- id,
884
- node: payload.node,
885
- branch: payload.branch,
886
- title,
887
- generatedAt: new Date().toISOString(),
888
- ahead: payload.ahead,
889
- dirtyNonRuntime: payload.dirtyNonRuntime,
890
- gates: gateRows(payload),
891
- score: { passed, total, fresh },
892
- impact,
893
- nodes,
894
- otherFiles,
895
- }
896
- }
897
-
898
- // the gate checklist, derived from the cockpit payload's gates (the SAME numbers `spex session review` prints).
899
- function gateRows(p: NonNullable<Awaited<ReturnType<typeof reviewPayload>>>): ExportGate[] {
900
- const g = p.gates
901
- return [
902
- { label: 'lint', ok: g.lint.errorCount === 0, detail: `${g.lint.errorCount} error(s), ${g.lint.warningCount} warning(s)` },
903
- { label: 'merge', ok: !g.conflictsWithMain, detail: g.conflictsWithMain ? 'conflicts with main' : 'no conflict' },
904
- { label: 'ahead', ok: p.ahead > 0, detail: `${p.ahead} commit(s) ahead of main` },
905
- { label: 'committed', ok: p.dirtyNonRuntime === 0, detail: p.dirtyNonRuntime === 0 ? 'nothing uncommitted' : `${p.dirtyNonRuntime} uncommitted file(s)` },
906
- ]
907
- }
908
-
909
- // gitA returns '' for a missing path — exactly the added/deleted (and best-effort rename) side; each side capped to MAX_FILE_BYTES
910
- const MAX_ENRICHED_FILES = 60
911
- const MAX_FILE_BYTES = 200_000
912
- async function enrichFile(wtPath: string, base: string, f: ReviewDiffFile): Promise<ExportFile> {
913
- const run = (args: string[]) => gitA(['-C', wtPath, '-c', 'core.quotePath=false', ...args])
914
- const paths = f.oldPath ? [f.oldPath, f.path] : [f.path]
915
- const [patchRaw, oldRaw, newRaw] = await Promise.all([
916
- run(['diff', '-M', `${base}..HEAD`, '--', ...paths]),
917
- f.status === 'added' ? Promise.resolve('') : run(['show', `${base}:${f.oldPath ?? f.path}`]),
918
- f.status === 'deleted' ? Promise.resolve('') : run(['show', `HEAD:${f.path}`]),
919
- ])
920
- const cap = (s: string) => (s.length > MAX_FILE_BYTES ? { text: s.slice(0, MAX_FILE_BYTES), cut: true } : { text: s, cut: false })
921
- const p = cap(patchRaw), o = cap(oldRaw), nw = cap(newRaw)
922
- return {
923
- ...f,
924
- patch: p.text,
925
- oldText: f.status === 'added' ? null : o.text,
926
- newText: f.status === 'deleted' ? null : nw.text,
927
- truncated: p.cut || o.cut || nw.cut,
928
- omitted: false,
929
- }
930
- }
931
-
932
- // resolve a reading's evidence to inline bytes so the proof is a self-contained file: an image → a base64
933
- // data-URI; a transcript → its text; the cache miss / no-capture states pass through. the eval cache owns the bytes
934
- // (the content-addressed cache) — the proof only asks for them by hash.
935
- async function toExportReading(r: EvalEntry, impact: ScenarioImpactReason[]): Promise<ExportReading> {
936
- const base = {
937
- scenario: r.scenario, expected: r.expected, impact, verdict: r.verdict, fresh: r.fresh,
938
- staleAxes: r.staleAxes, score: readingScore(r), evaluator: r.evaluator, ts: r.ts,
939
- }
940
- if (r.blobState !== 'present' || !r.blob) return { ...base, evidence: { kind: r.blobState === 'miss' ? 'miss' : 'none' } }
941
- const blob = readBlobByHash(r.blob)
942
- if (!blob.ok) return { ...base, evidence: { kind: 'miss' } }
943
- if (blob.mime.startsWith('image/')) return { ...base, evidence: { kind: 'image', dataUri: `data:${blob.mime};base64,${blob.bytes.toString('base64')}` } }
944
- if (blob.mime.startsWith('video/')) return { ...base, evidence: { kind: 'video', dataUri: `data:${blob.mime};base64,${blob.bytes.toString('base64')}` } }
945
- // structured data ([[evidence-kind-taxonomy]]): pretty-print so the self-contained proof shows a
946
- // validatable data block, not one flat line; invalid JSON falls back to the raw bytes rather than hiding.
947
- if (blob.mime.startsWith('application/json')) {
948
- let text = blob.bytes.toString('utf8')
949
- try { text = JSON.stringify(JSON.parse(text), null, 2) } catch { /* keep raw — invalid JSON still shows */ }
950
- return { ...base, evidence: { kind: 'data', text } }
951
- }
952
- return { ...base, evidence: { kind: 'transcript', text: blob.bytes.toString('utf8') } }
953
- }
954
-
955
- // the latest reading per scenario from a newest-first timeline (first seen wins) — the eval tab / score
956
- // badge convention, so the proof shows each scenario's CURRENT loss, not its whole history.
957
- function latestPerScenario(readings: EvalEntry[]): EvalEntry[] {
958
- const seen = new Set<string>()
959
- const out: EvalEntry[] = []
960
- for (const r of readings) if (!seen.has(r.scenario)) { seen.add(r.scenario); out.push(r) }
961
- return out
962
- }
963
-
964
- export function scopedScenarioReadings(
965
- scenarios: SessionScenarioInfo[],
966
- readings: EvalEntry[],
967
- ): { latest: EvalEntry[]; unmeasured: SessionScenarioInfo[] } {
968
- const latestByName = new Map(latestPerScenario(readings).map((reading) => [reading.scenario, reading]))
969
- const latest: EvalEntry[] = []
970
- const unmeasured: SessionScenarioInfo[] = []
971
- for (const scenario of scenarios) {
972
- const reading = latestByName.get(scenario.name)
973
- if (reading) latest.push(reading)
974
- else unmeasured.push(scenario)
975
- }
976
- return { latest, unmeasured }
977
- }
978
-
979
- // the DECLARED scenarios' latest reading — the SAME declared-bounded computation every other eval face reads
980
- // (score.jsx's scenarioStates for the node badge and the eval tab). A reading whose scenario is no longer in
981
- // eval.md is residual: the append-only sidecar still carries it, but it is not current loss, so it must not
982
- // become a proof reading card, a passed/total tick, or a node score. The proof was the one face driven by the
983
- // readings that happen to exist rather than the scenarios that are declared — this bounds it like the rest, so
984
- // a retired scenario's stale reading can't make the proof disagree with the dashboard (phantom card, off ribbon).
985
- export function declaredLatest(tl: EvalTimeline): EvalEntry[] {
986
- const declared = new Set(tl.scenarios.map((s) => s.name))
987
- return latestPerScenario(tl.readings).filter((r) => declared.has(r.scenario))
988
- }
989
-
990
- // ---- scoring (mirrors the dashboard's score.jsx vocabulary, on the EvalEntry shape) ----
991
-
992
- const verdictMark = (r: { verdict?: EvalEntry['verdict'] }) =>
993
- r.verdict?.status === 'pass' ? 'check' : r.verdict?.status === 'fail' ? 'cross' : null
994
-
995
- function readingScore(r: EvalEntry): ScoreState {
996
- const m = verdictMark(r)
997
- if (!m) return 'empty'
998
- if (!r.fresh) return m === 'cross' ? 'staleFail' : 'stalePass'
999
- return m === 'cross' ? 'fail' : 'pass'
1000
- }
1001
-
1002
- // worst-first aggregate over the latest reading per scenario: any fresh fail → fail; else any stale → grey
1003
- // (✗ if any stale last-failed, else ✓); else any unscored scenario → empty; else every scenario fresh-passes.
1004
- export function nodeScore(hasEvalFile: boolean, latest: EvalEntry[], affectedScenarios = latest.length): ScoreState {
1005
- if (!hasEvalFile) return null
1006
- if (!affectedScenarios || !latest.length) return 'empty'
1007
- if (latest.some((r) => r.fresh && verdictMark(r) === 'cross')) return 'fail'
1008
- const stale = latest.filter((r) => !r.fresh && verdictMark(r))
1009
- if (stale.length) return stale.some((r) => verdictMark(r) === 'cross') ? 'staleFail' : 'stalePass'
1010
- if (latest.length < affectedScenarios || latest.some((r) => !verdictMark(r))) return 'empty'
1011
- return 'pass'
1012
- }
1013
-
1014
- // ---- file → node mapping ----
1015
-
1016
- // which spec node owns a changed file: a file inside a node's directory (its spec.md / eval.md / sidecar)
1017
- // belongs to the NEAREST such node; otherwise the node whose governed `code:` claims it (exact path,
1018
- // directory prefix, or `*` glob — the same matching `spex eval lint --changed` uses). A shared file is
1019
- // governed by MANY nodes (ordinary composition); when the session has a primary node that also governs it,
1020
- // attribute it THERE so a node/<id> session's stake in cli.ts/index.ts groups under its own node, not
1021
- // whichever sibling sorts first.
1022
- // null = unclaimed.
1023
- function nodeForFile(file: string, specs: Awaited<ReturnType<typeof loadSpecs>>, primary: string | null): string | null {
1024
- let best: string | null = null, bestLen = -1
1025
- for (const s of specs) {
1026
- const dir = dirname(s.path)
1027
- if ((file === dir || file.startsWith(dir + '/')) && dir.length > bestLen) { best = s.id; bestLen = dir.length }
1028
- }
1029
- if (best) return best
1030
- if (primary) { const ps = specs.find((s) => s.id === primary); if (ps && codeClaims(ps.code, file)) return primary }
1031
- for (const s of specs) if (codeClaims(s.code, file)) return s.id
1032
- return null
1033
- }
1034
-
1035
- function codeClaims(code: string[], file: string): boolean {
1036
- return code.some((claim) => relationClaimsPath(claim, file))
1037
- }
1038
-
1039
- // ---- worktree resolution (no sessions.ts edit: read git's own worktree list) ----
1040
-
1041
- // the worktree path whose checked-out branch matches — so the eval context is rooted at the SESSION's
1042
- // worktree (its readings + git freshness), not the backend's checkout. `git worktree list --porcelain` emits
1043
- // `worktree <path>` then `branch refs/heads/<b>`.
1044
- function worktreePathForBranch(branch: string | null): string | null {
1045
- if (!branch) return null
1046
- let out = ''
1047
- try { out = git(['worktree', 'list', '--porcelain']) } catch { return null }
1048
- let curPath: string | null = null
1049
- for (const line of out.split('\n')) {
1050
- if (line.startsWith('worktree ')) curPath = line.slice('worktree '.length)
1051
- else if (line.startsWith('branch ') && line.slice('branch '.length) === `refs/heads/${branch}`) return curPath
1052
- }
1053
- return null
1054
- }
1055
-
1056
- export function parsePorcelainPaths(out: string): Set<string> {
1057
- const paths = new Set<string>()
1058
- const records = out.split('\0')
1059
- for (let i = 0; i < records.length; i++) {
1060
- const record = records[i]
1061
- if (!record) continue
1062
- const status = record.slice(0, 2)
1063
- const path = record.slice(3)
1064
- if (path) paths.add(path)
1065
- if ((status.includes('R') || status.includes('C')) && records[i + 1]) paths.add(records[++i])
1066
- }
1067
- return paths
1068
- }
1069
-
1070
- async function worktreeDirtyState(wtPath: string): Promise<{ paths: Set<string>; status: string }> {
1071
- const out = await impactGit(
1072
- wtPath,
1073
- ['-c', 'core.quotePath=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
1074
- 'snapshot worktree status',
1075
- )
1076
- return { paths: parsePorcelainPaths(out), status: out }
1077
- }
1078
-
1079
- // Capture one immutable description of the live worktree overlay. One rename-aware change set supplies both
1080
- // path images; untracked files are wholly new result ranges. The canonical anchor parser
1081
- // turns those patches into ranges, and projectSessionImpact consumes the snapshot beside base..HEAD. The
1082
- // outer session content double-read fences concurrent edits before this result can publish.
1083
- export async function sessionImpactOverlay(
1084
- wtPath: string,
1085
- dirty: { paths: ReadonlySet<string>; status: string },
1086
- ): Promise<SessionImpactOverlay | undefined> {
1087
- if (!dirty.paths.size) return undefined
1088
- const untracked = new Set(untrackedPaths(dirty.status))
1089
- const paths = [...dirty.paths].sort()
1090
- const baseRanges: Record<string, [number, number][]> = {}
1091
- const ranges: Record<string, [number, number][]> = {}
1092
- const files: Record<string, string | null> = {}
1093
- const fingerprints: string[] = []
1094
- const bytesByPath = new Map<string, Buffer | null>()
1095
- for (const path of paths) {
1096
- let bytes: Buffer | null = null
1097
- try { bytes = await readFile(join(wtPath, path)) }
1098
- catch (error: any) {
1099
- if (error?.code !== 'ENOENT') throw new SessionImpactUnavailableError(`session impact cannot snapshot '${path}': ${error?.message ?? String(error)}`)
1100
- }
1101
- bytesByPath.set(path, bytes)
1102
- files[path] = bytes?.toString('utf8') ?? null
1103
- baseRanges[path] = []
1104
- ranges[path] = []
1105
- fingerprints.push(`${path}\0${bytes ? createHash('sha256').update(bytes).digest('hex') : '<gone>'}`)
1106
- }
1107
- const indexDir = await mkdtemp(join(tmpdir(), 'spex-impact-index-'))
1108
- const indexFile = join(indexDir, 'index')
1109
- try {
1110
- await impactIndexGit(wtPath, indexFile, ['read-tree', 'HEAD'], 'seed the isolated worktree index')
1111
- await impactIndexGit(wtPath, indexFile, ['add', '-A', '--', ...paths], 'snapshot dirty paths in the isolated worktree index')
1112
- const trackedChanges = parseNameStatusChanges(await impactIndexGit(
1113
- wtPath,
1114
- indexFile,
1115
- ['-c', 'core.quotePath=false', 'diff', '--cached', 'HEAD', '--name-status', '-z', '-M'],
1116
- 'snapshot worktree change identities',
1117
- ))
1118
- for (const change of trackedChanges) {
1119
- if (!Object.hasOwn(baseRanges, change.before) || !Object.hasOwn(ranges, change.after))
1120
- throw new SessionImpactUnavailableError(`session impact dirty snapshot omitted '${change.before}' -> '${change.after}'`)
1121
- const patch = await impactIndexGit(
1122
- wtPath,
1123
- indexFile,
1124
- ['-c', 'core.quotePath=false', 'diff', '--cached', 'HEAD', '--unified=0', '--no-ext-diff', '-M', '--', ...new Set([change.before, change.after])],
1125
- `snapshot worktree patch '${change.before}' -> '${change.after}'`,
1126
- )
1127
- baseRanges[change.before] = diffHunkRanges(patch, 'old')
1128
- ranges[change.after] = diffHunkRanges(patch, 'new')
1129
- fingerprints.push(`${change.status}\0${change.before}\0${change.after}\0${createHash('sha256').update(patch).digest('hex')}`)
1130
- }
1131
- } finally {
1132
- await rm(indexDir, { recursive: true, force: true })
1133
- }
1134
- for (const path of untracked) fingerprints.push(`untracked\0${path}\0${bytesByPath.get(path)?.length ?? 0}`)
1135
- const loaded = await loadSpecs(wtPath, { history: null, drift: null })
1136
- const specs: SessionImpactSpecSnapshot[] = loaded.map((spec) => ({
1137
- id: spec.id,
1138
- path: spec.path,
1139
- code: spec.code,
1140
- codeEntries: spec.codeEntries,
1141
- codeScoped: spec.codeScoped,
1142
- related: spec.related,
1143
- relatedEntries: spec.relatedEntries,
1144
- relatedScoped: spec.relatedScoped,
1145
- relationProblems: spec.relationProblems,
1146
- }))
1147
- const evalSources: Record<string, string | null> = {}
1148
- for (const spec of specs) {
1149
- const evalPath = join(dirname(spec.path), 'eval.md')
1150
- try { evalSources[evalPath] = await readFile(join(wtPath, evalPath), 'utf8') }
1151
- catch (error: any) {
1152
- if (error?.code === 'ENOENT') evalSources[evalPath] = null
1153
- else throw new SessionImpactUnavailableError(`session impact cannot snapshot '${evalPath}': ${error?.message ?? String(error)}`)
1154
- }
1155
- }
1156
- const revision = createHash('sha256')
1157
- .update([dirty.status, ...fingerprints, JSON.stringify(specs), JSON.stringify(evalSources)].join('\0'))
1158
- .digest('hex')
1159
- return { revision, paths, baseRanges, ranges, specs, evalSources, files }
1160
- }
1161
-
1162
- // ---- the renderer ----
1163
-
1164
- // escape interpolated text for HTML (the proof inlines derived data — file paths, scenarios, expected — so
1165
- // every value is escaped; there is no agent-authored markdown to render).
1166
- function esc(s: string): string {
1167
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
1168
- }
1169
-
1170
- const SCORE_GLYPH: Record<string, string> = { pass: '✓', fail: '✗', stalePass: '✓', staleFail: '✗', empty: '' }
1171
- function scoreBadge(state: ScoreState, title?: string): string {
1172
- if (!state) return ''
1173
- return `<span class="score ${state}" title="${esc(title ?? state)}">${SCORE_GLYPH[state] ?? ''}</span>`
1174
- }
1175
- function verdictBadge(v: EvalEntry['verdict']): string {
1176
- if (!v) return `<span class="verdict legacy">legacy</span>`
1177
- if (v.status === 'pass') return `<span class="verdict pass">✓ pass</span>`
1178
- if (v.status === 'fail') return `<span class="verdict fail">✗ fail</span>`
1179
- return `<span class="verdict note" title="${esc(v.note ?? '')}">≈ note</span>`
1180
- }
1181
-
1182
- function renderReading(r: ExportReading): string {
1183
- const ev = r.evidence
1184
- const body =
1185
- ev.kind === 'image' ? `<img class="shot" src="${ev.dataUri}" alt="${esc(r.scenario)}">`
1186
- : ev.kind === 'video' ? `<video class="shot" src="${ev.dataUri}" controls preload="metadata"></video>`
1187
- : ev.kind === 'transcript' ? `<pre class="transcript">${esc(ev.text)}</pre>`
1188
- : ev.kind === 'data' ? `<pre class="transcript data">${esc(ev.text)}</pre>`
1189
- : ev.kind === 'miss' ? `<div class="noev">⌀ miss original file — the evidence bytes were pruned</div>`
1190
- : `<div class="noev">attested without a capture</div>`
1191
- const stale = r.fresh ? '' : `<span class="stale" title="${esc(r.staleAxes.join(', '))} changed since this eval">stale</span>`
1192
- const note = r.verdict?.note ? `<div class="rnote"><b>note</b> ${esc(r.verdict.note)}</div>` : ''
1193
- return `<div class="eval-entry">
1194
- <div class="rhead">
1195
- ${scoreBadge(r.score, r.fresh ? undefined : `stale: ${r.staleAxes.join(', ')}`)}
1196
- <span class="scenario">${esc(r.scenario)}</span>
1197
- <span class="impact">${esc(r.impact.join(' + '))}</span>
1198
- ${verdictBadge(r.verdict)}
1199
- ${stale}
1200
- <span class="rmeta">${r.evaluator ? `${esc(r.evaluator)} · ` : ''}${esc(r.ts)}</span>
1201
- </div>
1202
- ${r.expected ? `<div class="expected"><b>expected</b> ${esc(r.expected)}</div>` : ''}
1203
- ${note}
1204
- <figure class="evidence">${body}</figure>
1205
- </div>`
1206
- }
1207
-
1208
- function renderUnmeasured(scenario: ExportUnmeasured): string {
1209
- return `<div class="eval-entry unmeasured">
1210
- <div class="rhead">
1211
- ${scoreBadge('empty', 'unmeasured')}
1212
- <span class="scenario">${esc(scenario.scenario)}</span>
1213
- <span class="impact">${esc(scenario.impact.join(' + '))}</span>
1214
- <span class="verdict legacy">unmeasured</span>
1215
- </div>
1216
- ${scenario.expected ? `<div class="expected"><b>expected</b> ${esc(scenario.expected)}</div>` : ''}
1217
- </div>`
1218
- }
1219
-
1220
- // each diff line is its own block so a long diff scrolls inside its box
1221
- function renderPatch(patch: string): string {
1222
- return patch.split('\n').map((ln) => {
1223
- const cls = /^@@/.test(ln) ? 'h'
1224
- : /^(diff |index |--- |\+\+\+ |rename |similarity |new file|deleted file|old mode|new mode|Binary )/.test(ln) ? 'm'
1225
- : ln[0] === '+' ? 'a' : ln[0] === '-' ? 'd' : ''
1226
- return `<span class="dl ${cls}">${esc(ln) || ' '}</span>`
1227
- }).join('')
1228
- }
1229
-
1230
- function renderFile(f: ExportFile): string {
1231
- const row = `<span class="fstatus ${esc(f.status)}">${esc(f.status)}</span> <span class="fpath">${esc(f.path)}</span> <span class="fnum"><span class="add">+${f.additions}</span> <span class="del">−${f.deletions}</span></span>`
1232
- if (f.omitted) return `<div class="file flat"><div class="frow">${row}<span class="note">diff omitted — large changeset</span></div></div>`
1233
- if (!f.patch && f.oldText == null && f.newText == null) return `<div class="file flat"><div class="frow">${row}</div></div>`
1234
- const side = (label: string, text: string | null, absent: string) =>
1235
- `<div class="side"><div class="side-h">${label}</div><pre>${text == null ? `<span class="abs">${absent}</span>` : (esc(text) || '<span class="abs">(empty)</span>')}</pre></div>`
1236
- const cmp = (f.oldText != null || f.newText != null)
1237
- ? `<details class="fullfile"><summary>full file · original ↔ new</summary><div class="cmp">${side('original (merge-base)', f.oldText, '— added —')}${side('new (HEAD)', f.newText, '— deleted —')}</div></details>`
1238
- : ''
1239
- return `<details class="file"><summary>${row}${f.truncated ? '<span class="note">truncated</span>' : ''}</summary>
1240
- <div class="file-body">${f.patch ? `<div class="patch">${renderPatch(f.patch)}</div>` : '<div class="note">no textual diff</div>'}${cmp}</div></details>`
1241
- }
1242
-
1243
- function renderNode(n: ExportNode): string {
1244
- const stat = `<span class="diffstat"><span class="add">+${n.additions}</span> <span class="del">−${n.deletions}</span> · ${n.files.length} file(s)</span>`
1245
- const fileList = n.files.length ? `<div class="files">${n.files.map(renderFile).join('')}</div>` : ''
1246
- let proof: string
1247
- if (n.affectedScenarios) proof = [...n.unmeasured.map(renderUnmeasured), ...n.readings.map(renderReading)].join('')
1248
- else if (n.uncoveredFrontend) proof = `<div class="blindspot">⚠ a frontend node with no eval.md — its loss is unmeasured. Give it a scenario so this change can be verified.</div>`
1249
- else if (n.hasEvalFile) proof = `<div class="noev">no declared scenario is affected by this worktree</div>`
1250
- else proof = `<div class="noev">no measurable surface (no eval.md)</div>`
1251
- return `<article class="node" style="--hue:${n.hue}">
1252
- <div class="nhead">
1253
- <span class="huedot"></span>
1254
- <span class="ntitle">${esc(n.title)}</span>
1255
- <span class="nid">${esc(n.id)}</span>
1256
- ${scoreBadge(n.score, n.score ?? undefined)}
1257
- ${stat}
1258
- </div>
1259
- ${n.desc ? `<div class="ndesc">${esc(n.desc)}</div>` : ''}
1260
- ${fileList}
1261
- <div class="eval-list">${proof}</div>
1262
- </article>`
1263
- }
1264
-
1265
- export function renderExportHtml(m: ExportModel): string {
1266
- const idShort = m.id.slice(0, 8)
1267
- const ribbon = [
1268
- ...m.gates.map((g) => `<span class="chip ${g.ok ? 'ok' : 'bad'}" title="${esc(g.detail)}">${g.ok ? '✓' : '✗'} ${esc(g.label)}</span>`),
1269
- m.score.total ? `<span class="chip ${m.score.passed === m.score.total ? 'ok' : 'warn'}" title="affected scenarios fresh-passing; ${m.score.fresh}/${m.score.total} have a fresh measurement">★ ${m.score.passed}/${m.score.total} passing</span>` : `<span class="chip warn" title="no scenario is affected by this worktree">★ no affected scenarios</span>`,
1270
- ].join('')
1271
- const gates = m.gates.map((g) => `<li class="${g.ok ? 'ok' : 'bad'}"><span class="gmark">${g.ok ? '✓' : '✗'}</span><span class="glabel">${esc(g.label)}</span><span class="gdetail">${esc(g.detail)}</span></li>`).join('')
1272
- const otherBlock = m.otherFiles.length
1273
- ? `<article class="node other"><div class="nhead"><span class="ntitle">other files</span><span class="nid">unclaimed by any node</span></div>
1274
- <div class="files">${m.otherFiles.map(renderFile).join('')}</div></article>`
1275
- : ''
1276
- return `<!doctype html>
1277
- <html lang="en"><head>
1278
- <meta charset="utf-8">
1279
- <meta name="viewport" content="width=device-width, initial-scale=1">
1280
- <title>evals · ${esc(m.title)}</title>
1281
- <style>${STYLE}</style>
1282
- </head><body>
1283
- <main class="evals">
1284
- <header class="masthead">
1285
- <div class="eyebrow">SpexCode · session eval export</div>
1286
- <h1 class="claim">${esc(m.title)}</h1>
1287
- <div class="meta">session <code>${esc(idShort)}</code>${m.branch ? ` · <code>${esc(m.branch)}</code>` : ''}${m.node ? ` · node <code>${esc(m.node)}</code>` : ''} · ${m.ahead} commit(s) · ${m.nodes.length} node(s) · <span class="ts">${esc(m.generatedAt)}</span></div>
1288
- <div class="ribbon">${ribbon}</div>
1289
- </header>
1290
- <section class="evidence-section">
1291
- <h2>Evidence — measured loss</h2>
1292
- ${m.nodes.map(renderNode).join('')}
1293
- ${otherBlock}
1294
- </section>
1295
- <section class="gates-section">
1296
- <h2>Merge gates</h2>
1297
- <ul class="gates">${gates}</ul>
1298
- </section>
1299
- <footer>Generated by <code>spex eval ls --session ${esc(idShort)} --export</code> — the optimizer's measured loss, presented for the merge decision. A spec is the loss; commits are the optimizer; eval keeps the score.</footer>
1300
- </main>
1301
- </body></html>`
1302
- }
1303
-
1304
- // the document's inline stylesheet — dark, matching the board's palette and the eval score colours, so the
1305
- // proof reads as one surface with the dashboard. Self-contained (no external font/asset).
1306
- const STYLE = `
1307
- :root{--bg:#0b0e14;--panel:#11161f;--panel2:#0e131b;--ink:#c9d4e3;--dim:#7c899c;--line:#1e2733;--accent:#4cc2a0;--green:#3fb950;--red:#f85149;--grey:#6e7b8c;--amber:#d29922}
1308
- *{box-sizing:border-box}
1309
- body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
1310
- code,pre,.mono{font-family:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace}
1311
- code{background:#0006;padding:.05em .35em;border-radius:4px;font-size:.88em;color:#aee1d2}
1312
- .evals{max-width:920px;margin:0 auto;padding:40px 24px 80px}
1313
- .masthead{padding:30px 30px 26px;border:1px solid var(--line);border-radius:16px;background:radial-gradient(1200px 240px at 0% 0%,#16352c66,transparent),linear-gradient(160deg,#141b26,#0d121a);box-shadow:0 20px 60px -30px #000}
1314
- .eyebrow{font:600 11px/1 ui-monospace,monospace;letter-spacing:.18em;text-transform:uppercase;color:var(--accent)}
1315
- .claim{margin:14px 0 10px;font-size:30px;line-height:1.2;font-weight:700;color:#eef3fa;letter-spacing:-.01em}
1316
- .meta{color:var(--dim);font-size:13px}
1317
- .meta code{background:#0008;color:#9fb3c8}
1318
- .ribbon{margin-top:18px;display:flex;flex-wrap:wrap;gap:8px}
1319
- .chip{display:inline-flex;align-items:center;gap:.4em;font:600 12px/1 ui-monospace,monospace;padding:6px 10px;border-radius:999px;border:1px solid var(--line);background:#0c1118}
1320
- .chip.ok{color:var(--green);border-color:#1c3a26}
1321
- .chip.bad{color:var(--red);border-color:#3a1f1f}
1322
- .chip.warn{color:var(--amber);border-color:#3a3320}
1323
- h2{margin:42px 0 16px;font-size:14px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);font-weight:700}
1324
- .node{margin:14px 0;padding:18px 20px;border:1px solid var(--line);border-radius:12px;background:var(--panel);border-left:3px solid hsl(var(--hue,210),55%,55%)}
1325
- .node.other{border-left-color:var(--grey)}
1326
- .nhead{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
1327
- .huedot{width:11px;height:11px;border-radius:3px;background:hsl(var(--hue,210),60%,55%);flex:none}
1328
- .ntitle{font-weight:700;color:#e7eef7;font-size:16px}
1329
- .nid{font:12px/1 ui-monospace,monospace;color:var(--dim)}
1330
- .ndesc{margin:8px 0 4px;color:var(--dim);font-size:13px}
1331
- .diffstat{margin-left:auto;font:12px/1 ui-monospace,monospace;color:var(--dim)}
1332
- .add{color:var(--green)}.del{color:var(--red)}
1333
- .files{margin:12px 0 0;border-top:1px solid var(--line)}
1334
- .file{border-bottom:1px solid #0c1117}
1335
- .file>summary,.frow{display:flex;align-items:center;gap:10px;padding:6px 2px;font:12px/1.4 ui-monospace,monospace}
1336
- .file>summary{cursor:pointer;list-style:none}
1337
- .file>summary::-webkit-details-marker{display:none}
1338
- .file>summary::before{content:'▸ ';color:var(--dim)}
1339
- .file[open]>summary::before{content:'▾ '}
1340
- .file.flat .frow{padding-left:14px}
1341
- .fstatus{flex:none;width:84px;color:var(--dim);text-transform:uppercase;font-size:10px;letter-spacing:.06em}
1342
- .fstatus.added{color:var(--green)}.fstatus.deleted{color:var(--red)}.fstatus.modified{color:var(--amber)}
1343
- .fpath{color:#aebccd;overflow:hidden;text-overflow:ellipsis}.fnum{margin-left:auto;flex:none}
1344
- .note{color:var(--dim);font-style:italic;font-size:11px;margin-left:8px}
1345
- .file-body{padding:2px 0 12px 14px}
1346
- .patch{font:12px/1.5 ui-monospace,monospace;background:#05080d;border:1px solid var(--line);border-radius:8px;overflow:auto;max-height:480px;white-space:pre}
1347
- .dl{display:block;padding:0 10px;min-height:1.5em}
1348
- .dl.a{background:#11331f;color:#86e2ad}.dl.d{background:#3a1616;color:#f3a3a0}.dl.h{color:#74a6f7;background:#0c1830}.dl.m{color:var(--dim)}
1349
- .fullfile{margin-top:10px}
1350
- .fullfile>summary{cursor:pointer;color:var(--accent);font:600 11px/1 ui-monospace,monospace;padding:6px 0}
1351
- .cmp{display:flex;gap:10px;flex-wrap:wrap;margin-top:6px}
1352
- .side{flex:1;min-width:300px}
1353
- .side-h{font:600 10px/1 ui-monospace,monospace;text-transform:uppercase;letter-spacing:.08em;color:var(--dim);padding:0 0 6px}
1354
- .side pre{margin:0;padding:10px 12px;background:#05080d;border:1px solid var(--line);border-radius:8px;max-height:440px;overflow:auto;font:11px/1.5 ui-monospace,monospace;color:#aebccd;white-space:pre}
1355
- .abs{color:var(--dim);font-style:italic}
1356
- .eval-list{margin-top:8px}
1357
- .eval-entry{margin-top:14px;padding:14px 16px;border:1px solid var(--line);border-radius:10px;background:var(--panel2)}
1358
- .rhead{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
1359
- .scenario{font-weight:600;color:#dde7f1}
1360
- .impact{font:600 10px/1 ui-monospace,monospace;color:var(--accent)}
1361
- .rmeta{margin-left:auto;font:11px/1 ui-monospace,monospace;color:var(--dim)}
1362
- .verdict{font:600 11px/1 ui-monospace,monospace;padding:3px 8px;border-radius:6px;border:1px solid var(--line)}
1363
- .verdict.pass{color:var(--green);border-color:#1c3a26}.verdict.fail{color:var(--red);border-color:#3a1f1f}
1364
- .verdict.note{color:var(--amber)}.verdict.legacy{color:var(--grey)}
1365
- .stale{font:600 10px/1 ui-monospace,monospace;color:var(--amber);border:1px solid #3a3320;border-radius:6px;padding:3px 7px}
1366
- .score{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:2px solid var(--grey);font-size:11px;font-weight:700;flex:none}
1367
- .score.pass{border-color:var(--green);color:var(--green)}
1368
- .score.fail{border-color:var(--red);color:var(--red)}
1369
- .score.stalePass,.score.staleFail{border-color:var(--grey);color:var(--grey)}
1370
- .score.empty{border-style:dashed}
1371
- .expected{margin:10px 0 0;color:var(--dim);font-size:13px}.expected b{color:#9fb3c8;font-weight:600}
1372
- .rnote{margin:8px 0 0;color:var(--amber);font-size:13px}.rnote b{font-weight:600}
1373
- .evidence{margin:12px 0 0}
1374
- .shot{max-width:100%;border:1px solid var(--line);border-radius:8px;box-shadow:0 14px 40px -24px #000;display:block}
1375
- .transcript{max-height:420px;overflow:auto;margin:0;padding:12px 14px;background:#05080d;border:1px solid var(--line);border-radius:8px;font-size:12px;color:#9fdcc6;white-space:pre-wrap;word-break:break-word}
1376
- .transcript.data{color:#cbb6ff;border-left:3px solid #6b46c1}
1377
- .noev,.blindspot{margin-top:10px;padding:10px 12px;border-radius:8px;font-size:13px;color:var(--dim);background:#0a0e15;border:1px dashed var(--line)}
1378
- .blindspot{color:var(--amber);border-color:#3a3320}
1379
- .gates{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:12px;overflow:hidden}
1380
- .gates li{display:flex;align-items:center;gap:14px;padding:12px 18px;border-bottom:1px solid var(--line);background:var(--panel)}
1381
- .gates li:last-child{border-bottom:0}
1382
- .gmark{font-weight:700}.gates li.ok .gmark{color:var(--green)}.gates li.bad .gmark{color:var(--red)}
1383
- .glabel{font-weight:600;width:120px;color:#dbe6f2}.gdetail{color:var(--dim);font:12px/1 ui-monospace,monospace}
1384
- footer{margin-top:48px;padding-top:20px;border-top:1px solid var(--line);color:var(--dim);font-size:12px;text-align:center}
1385
- `
1386
-
1387
- // ---- the session EVAL model ([[session-eval]]'s interactive face) ----
1388
- // The lean, TIERED counterpart of buildExportModel: the same worktree-rooted marshaling, but rows only —
1389
- // no diff enrichment, no inlined evidence bytes (the dashboard's Eval tab rides the shared eval
1390
- // components: blobs stream lazily from /api/evidence on open). Each reading carries `inSession`
1391
- // (this session filed it, or its codeSha is one of the branch's own commits — a diagnostic session
1392
- // that changed no code still owns the readings it filed at the merge-base) so the tab can lead with
1393
- // what THIS session measured, ✦-marked, over the inherited baseline.
1394
- export type SessionEvalNode = {
1395
- id: string
1396
- title: string
1397
- hue: number
1398
- desc: string
1399
- hasEvalFile: boolean
1400
- uncoveredFrontend: boolean
1401
- // Changed frontend code that no declared scenario covers. This is node-level UNKNOWN coverage, never a
1402
- // synthetic scenario: it stays outside scenario totals and filters while remaining visible to consumers.
1403
- unknownCoverage: string[]
1404
- // Node-level review context from the SAME exact impact projection. Related movement lives here and never
1405
- // becomes a synthetic scenario reason.
1406
- causes: SessionImpactNodeCause[]
1407
- // Already scoped by the canonical exact impact projection. Consumers must not infer impact from node
1408
- // membership, freshness, or the full eval.md again.
1409
- scenarios: SessionScenarioInfo[]
1410
- // each reading carries the trunk eval-concern thread for its (node, scenario) ([[remark-teeth]] / directive
1411
- // 3): the server-side join (attached by evalTimeline as `EvalEntry.thread`), so the session tab's event
1412
- // detail reads the comment/remark track directly instead of re-matching a concern key client-side. Absent
1413
- // until the pair has its first remark.
1414
- evals: (EvalEntry & { inSession: boolean })[]
1415
- }
1416
- export type SessionEvals = {
1417
- id: string
1418
- node: string | null
1419
- branch: string | null
1420
- title: string
1421
- nodes: SessionEvalNode[]
1422
- impact: SessionImpactProjection
1423
- // the whole scope's seven counts. A FOCUSED build cannot honestly produce them — it measured six rows,
1424
- // not the scope — so it carries the summary only when the cut already holds one, and otherwise omits it
1425
- // rather than publishing a fold over the window. `evalRevision.content` is the stronger identity anyway:
1426
- // equal content revision IS the same evaluation cut, so a consumer fencing on it needs no counts.
1427
- summary?: SessionEvalSummary
1428
- // the LIST page's chrome, and only its. A focused build renders no gates strip and no branch counters, so
1429
- // it does not buy them — see `order` below for what marks such a model partial.
1430
- gates?: ExportGate[]
1431
- ahead?: number
1432
- dirtyNonRuntime?: number
1433
- evalRevision: SessionEvalRevision
1434
- // present ONLY on a focused build: the whole population's identity+sequence facts, because `nodes` then
1435
- // holds just the few the response will render. Its presence is exactly what marks a model as PARTIAL —
1436
- // such a model may never enter the shared cut, or the list page would read the scope as those few nodes.
1437
- order?: SessionEvalOrderRow[]
1438
- }
1439
-
1440
- export type SessionEvalSummary = {
1441
- measured: number
1442
- total: number
1443
- pass: number
1444
- fail: number
1445
- review: number
1446
- blind: number
1447
- unknown: number
1448
- }
1449
-
1450
- export type SessionEvalRevision = {
1451
- epoch: string
1452
- generation: number
1453
- content: string
1454
- }
1455
-
1456
- export type SessionEvalProjection = {
1457
- epoch: string
1458
- generation: number
1459
- phase: 'loading' | 'updating' | 'ready' | 'error'
1460
- revision?: string
1461
- value?: SessionEvalSummary
1462
- lastKnown?: { generation: number; revision: string; value: SessionEvalSummary }
1463
- }
1464
-
1465
- // The one count projection over the already-affected rows. This is the backend source both the graph
1466
- // glance and the demand full model carry; consumers never repeat impact selection or score classification.
1467
- export function sessionEvalSummary(nodes: SessionEvalNode[]): SessionEvalSummary {
1468
- let total = 0, measured = 0, pass = 0, fail = 0, unknown = 0
1469
- for (const node of nodes) {
1470
- total += node.scenarios.length
1471
- unknown += node.unknownCoverage.length
1472
- const latest = new Map(latestPerScenario(node.evals).map((reading) => [reading.scenario, reading]))
1473
- for (const scenario of node.scenarios) {
1474
- const reading = latest.get(scenario.name)
1475
- if (!reading) continue
1476
- measured++
1477
- if (reading.fresh && reading.verdict?.status === 'pass') pass++
1478
- else if (reading.fresh && reading.verdict?.status === 'fail') fail++
1479
- }
1480
- }
1481
- return {
1482
- measured,
1483
- total,
1484
- pass,
1485
- fail,
1486
- review: measured - pass - fail,
1487
- blind: Math.max(0, total - measured),
1488
- unknown,
1489
- }
1490
- }
1491
-
1492
- async function sessionScopeNodes(
1493
- id: string,
1494
- ctx: Awaited<ReturnType<typeof evalContext>>,
1495
- impact: SessionImpactProjection,
1496
- shas: ReadonlySet<string>,
1497
- freshness: { order?: boolean; only?: ReadonlySet<string> } = {},
1498
- ): Promise<SessionEvalNode[]> {
1499
- const evalById = new Map(ctx.ynodes.map((node) => [node.id, node]))
1500
- const specById = new Map(ctx.specs.map((spec) => [spec.id, spec]))
1501
- const nodes: SessionEvalNode[] = []
1502
-
1503
- // @@@one prime pass for the whole scope - evalTimelines unions the off-history content probes and the
1504
- // anchor probes across every id it is given, so asking it once per scope issues one child per probe kind
1505
- // instead of one per node. Reading the timelines inside the loop instead cost 74% of a warm open.
1506
- const timelineIds = impact.nodes
1507
- .filter((projected) => specById.has(projected.id) && evalById.has(projected.id))
1508
- .filter((projected) => !freshness.only || freshness.only.has(projected.id))
1509
- .map((projected) => projected.id)
1510
- const timelineById = new Map((await evalTimelines(timelineIds, ctx, { order: freshness.order }))
1511
- .map((timeline, i) => [timelineIds[i], timeline]))
1512
-
1513
- for (const projected of impact.nodes) {
1514
- if (freshness.only && !freshness.only.has(projected.id)) continue
1515
- const spec = specById.get(projected.id)
1516
- if (!spec) continue // removed nodes remain fully explained by impact.nodes; they have no live eval rows.
1517
- const evalNode = evalById.get(spec.id)
1518
- const current = evalNode?.scenarios ?? []
1519
- // Unknown means the node has no measurement contract at all. A node that has eval.md is known even
1520
- // when individual scenarios narrow their code axes; partial scenario ownership is not a synthetic gap.
1521
- const unknownCoverage = evalNode ? [] : [...new Set(projected.causes
1522
- .filter((cause) => cause.kind === 'code')
1523
- .flatMap((cause) => cause.paths)
1524
- .filter(isUiPath))]
1525
-
1526
- if (!evalNode) {
1527
- if (unknownCoverage.length) {
1528
- nodes.push({
1529
- id: spec.id, title: spec.title, hue: spec.hue, desc: spec.desc,
1530
- hasEvalFile: false, uncoveredFrontend: true, unknownCoverage,
1531
- causes: projected.causes,
1532
- scenarios: [], evals: [],
1533
- })
1534
- }
1535
- continue
1536
- }
1537
-
1538
- const timeline = timelineById.get(spec.id)!
1539
- // A reading is this session's own when the session filed it OR its anchor is a branch commit. This is
1540
- // the same marker the UI and CLI render; measurement impact consumes that marker instead of inventing
1541
- // another attribution rule.
1542
- const evals = timeline.readings.map((reading) => ({
1543
- ...reading,
1544
- inSession: readingInSession(reading, id, shas),
1545
- }))
1546
- const scoped = scopeSessionScenarioRows(current, timeline.scenarios, evals, projected.scenarios)
1547
- if (!scoped.scenarios.length && !unknownCoverage.length && !projected.causes.length) continue
1548
-
1549
- nodes.push({
1550
- id: spec.id, title: spec.title, hue: spec.hue, desc: spec.desc,
1551
- hasEvalFile: timeline.hasEvalFile,
1552
- uncoveredFrontend: !timeline.hasEvalFile && unknownCoverage.length > 0,
1553
- unknownCoverage,
1554
- causes: projected.causes,
1555
- scenarios: scoped.scenarios,
1556
- // Preserve the whole A/B history for selected scenarios. Fresh, stale, legacy and missing remain
1557
- // honest downstream states; impact selection never removes a row because its reading is stale.
1558
- evals: scoped.evals,
1559
- })
1560
- }
1561
-
1562
- return nodes
1563
- }
1564
-
1565
- function readingInSession(reading: { by?: string; codeSha: string }, id: string, shas: ReadonlySet<string>): boolean {
1566
- return reading.by === id || shas.has(reading.codeSha)
1567
- }
1568
-
1569
- function sessionMeasurements(
1570
- id: string,
1571
- ctx: Awaited<ReturnType<typeof evalContext>>,
1572
- shas: ReadonlySet<string>,
1573
- ): Record<string, string[]> {
1574
- const measurements: Record<string, string[]> = {}
1575
- for (const node of ctx.ynodes) {
1576
- const names = [...new Set(readReadings(node.sidecarPath)
1577
- .filter((reading) => readingInSession(reading, id, shas))
1578
- .map((reading) => reading.scenario))]
1579
- if (names.length) measurements[node.id] = names
1580
- }
1581
- return measurements
1582
- }
1583
-
1584
- async function sessionImpactForContext(
1585
- id: string,
1586
- ctx: Awaited<ReturnType<typeof evalContext>>,
1587
- wtPath: string | null,
1588
- ): Promise<{ impact: SessionImpactProjection; shas: Set<string> }> {
1589
- const root = wtPath ?? ctx.root
1590
- if (!wtPath) {
1591
- const head = await impactCommit(root, 'HEAD')
1592
- const impact = await projectSessionImpact(root, {
1593
- base: head,
1594
- head,
1595
- measurements: sessionMeasurements(id, ctx, new Set()),
1596
- })
1597
- return { impact, shas: new Set() }
1598
- }
1599
- const [base, head, shaRows, dirty] = await Promise.all([
1600
- impactGit(wtPath, ['merge-base', mainBranch(), 'HEAD'], 'resolve session merge-base').then((out) => out.trim()),
1601
- impactCommit(wtPath, 'HEAD'),
1602
- impactGit(wtPath, ['rev-list', `${mainBranch()}..HEAD`], 'read session commits'),
1603
- worktreeDirtyState(wtPath),
1604
- ])
1605
- const shas = new Set(shaRows.split('\n').filter(Boolean))
1606
- const overlay = await sessionImpactOverlay(wtPath, dirty)
1607
- const impact = await projectSessionImpact(wtPath, {
1608
- base,
1609
- head,
1610
- overlay,
1611
- measurements: sessionMeasurements(id, ctx, shas),
1612
- })
1613
- return { impact, shas }
1614
- }
1615
-
1616
- type ReviewPayloadValue = NonNullable<Awaited<ReturnType<typeof reviewPayload>>>
1617
- type SessionEvalModel = Omit<SessionEvals, 'summary' | 'evalRevision'>
1618
-
1619
- async function buildSessionEvalModel(
1620
- id: string,
1621
- payload: ReviewPayloadValue | ReviewIdentity,
1622
- wtPath: string | null,
1623
- pick?: SessionEvalFocus,
1624
- ): Promise<SessionEvalModel> {
1625
- // spec tree from the session worktree, same root as readings/indexes — a branch-NEW node must exist
1626
- // in this model or the Eval tab/deep link can never reach its readings (see buildExportModel above).
1627
- const ctxRoot = wtPath ?? repoRoot()
1628
- const specs = await loadSpecs(ctxRoot)
1629
- const specById = new Map(specs.map((s) => [s.id, s]))
1630
- const [didx, hidx] = await Promise.all([driftIndex(ctxRoot), historyIndex(ctxRoot)])
1631
- const ctx = await evalContext(ctxRoot, specs, didx, hidx)
1632
- const { impact, shas } = await sessionImpactForContext(id, ctx, wtPath)
1633
- // @@@ TWO passes, ONE context - a detail open renders one scenario and at most five neighbours, but it
1634
- // still owes the full population's sequence (its `index` and `total`). Sequence is freshness-free, so the
1635
- // first pass reads every node's rows with no probes at all (~0.4s of the 25s), the caller names the few
1636
- // nodes whose verdicts will actually be published, and only those pay the freshness pass. The context and
1637
- // the impact projection are built once and shared, so the cheap pass adds no second projection.
1638
- let order: SessionEvalOrderRow[] | undefined
1639
- let only: ReadonlySet<string> | undefined
1640
- if (pick) {
1641
- const draft = await sessionScopeNodes(id, ctx, impact, shas, { order: true })
1642
- order = orderRowsOf(draft)
1643
- only = new Set(pick(order))
1644
- }
1645
- const nodes = await sessionScopeNodes(id, ctx, impact, shas, only ? { only } : {})
1646
- // nodes with in-session measurements lead, then the most-measured — the session's own evidence first.
1647
- nodes.sort((a, b) => (b.evals.filter((e) => e.inSession).length - a.evals.filter((e) => e.inSession).length)
1648
- || (b.scenarios.length - a.scenarios.length) || (b.unknownCoverage.length - a.unknownCoverage.length))
1649
-
1650
- const primary = payload.node && specById.has(payload.node) ? specById.get(payload.node)!.title : null
1651
- const full = 'gates' in payload ? payload : null
1652
- return {
1653
- id,
1654
- node: payload.node,
1655
- branch: payload.branch,
1656
- title: primary || payload.node || payload.branch || id.slice(0, 8),
1657
- ...(full ? { ahead: full.ahead, dirtyNonRuntime: full.dirtyNonRuntime, gates: gateRows(full) } : {}),
1658
- nodes,
1659
- impact,
1660
- ...(order ? { order } : {}),
1661
- }
1662
- }
1663
-
1664
- // the identity+sequence facts a detail open needs about scenarios it will NOT render: which exist, whether
1665
- // they carry a filed reading, and when. Deliberately not an EvalEntry — there is no verdict here to leak.
1666
- export type SessionEvalOrderRow = { node: string; scenario: string; ts: string | null }
1667
- export type SessionEvalFocus = (order: SessionEvalOrderRow[]) => readonly string[]
1668
-
1669
- export function orderRowsOf(nodes: SessionEvalNode[]): SessionEvalOrderRow[] {
1670
- const rows: SessionEvalOrderRow[] = []
1671
- for (const node of nodes) {
1672
- const latest = new Map<string, string>()
1673
- for (const reading of node.evals) if (!latest.has(reading.scenario)) latest.set(reading.scenario, reading.ts)
1674
- for (const scenario of node.scenarios)
1675
- rows.push({ node: node.id, scenario: scenario.name, ts: latest.get(scenario.name) ?? null })
1676
- }
1677
- return rows
1678
- }
1679
-
1680
- function untrackedPaths(status: string): string[] {
1681
- const out: string[] = []
1682
- const records = status.split('\0')
1683
- for (let i = 0; i < records.length; i++) {
1684
- const record = records[i]
1685
- if (!record) continue
1686
- const code = record.slice(0, 2)
1687
- const path = record.slice(3)
1688
- if (code === '??' && path) out.push(path)
1689
- if ((code.includes('R') || code.includes('C')) && records[i + 1]) i++
1690
- }
1691
- return out.sort()
1692
- }
1693
-
1694
- // One content fingerprint over every axis that can alter the scoped summary. Committed declarations,
1695
- // sidecars and governed code are covered by HEAD; the moving comparison base by the base ref;
1696
- // index/worktree/rename content by the HEAD-relative binary diff; untracked bytes are folded explicitly.
1697
- // Remark tracks are folded directly as well as through main: the disposable plain-file issue store used by
1698
- // controlled runs has no ref move, but it is still the same freshness input and must obey the same fence.
1699
- export async function sessionEvalContentRevision(wtPath: string): Promise<string> {
1700
- const base = mainBranch()
1701
- const [mainSha, headSha, mergeBase, status, dirtyDiff] = await Promise.all([
1702
- gitA(['-C', wtPath, 'rev-parse', base]).then((out) => out.trim()),
1703
- gitA(['-C', wtPath, 'rev-parse', 'HEAD']).then((out) => out.trim()),
1704
- gitA(['-C', wtPath, 'merge-base', base, 'HEAD']).then((out) => out.trim()),
1705
- gitA(['-C', wtPath, '-c', 'core.quotePath=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all']),
1706
- gitA(['-C', wtPath, 'diff', 'HEAD', '--binary', '--no-ext-diff', '--']),
1707
- ])
1708
- const untracked = await Promise.all(untrackedPaths(status).map(async (path) => {
1709
- try {
1710
- const bytes = await readFile(join(wtPath, path))
1711
- return `${path}\0${createHash('sha256').update(bytes).digest('hex')}`
1712
- } catch {
1713
- return `${path}\0<gone>`
1714
- }
1715
- }))
1716
- const remarks = [...loadEvalRemarkTracks()]
1717
- .sort(([a], [b]) => a.localeCompare(b))
1718
- .map(([key, track]) => [key, track.thread])
1719
- return createHash('sha256')
1720
- .update([mainSha, headSha, mergeBase, status, dirtyDiff, ...untracked, JSON.stringify(remarks)].join('\0'))
1721
- .digest('hex')
1722
- }
1723
-
1724
- type SummaryBuildResult =
1725
- | { kind: 'stable'; revision: string; summary: SessionEvalSummary }
1726
- | { kind: 'unstable' }
1727
- | { kind: 'missing' }
1728
-
1729
- export type SessionEvalSummaryBuilder = (id: string, path: string) => Promise<SummaryBuildResult>
1730
-
1731
- type DemandJob<T> = {
1732
- id: string
1733
- run: () => Promise<T>
1734
- resolve: (value: T) => void
1735
- reject: (error: unknown) => void
1736
- }
1737
-
1738
- type ProjectionEntry = {
1739
- id: string
1740
- path: string
1741
- liveness: string
1742
- generation: number
1743
- phase: SessionEvalProjection['phase']
1744
- current?: { generation: number; revision: string; value: SessionEvalSummary }
1745
- scheduled: number | null
1746
- running: number | null
1747
- demandCancelledGeneration: number | null
1748
- observerHolds: Set<string>
1749
- }
1750
-
1751
- type StagedProjection = {
1752
- entry: ProjectionEntry
1753
- generation: number
1754
- result: SummaryBuildResult
1755
- }
1756
-
1757
- type ProjectionCohortRow = Pick<StagedProjection, 'entry' | 'generation'>
1758
-
1759
- type ProjectionTarget = 'all' | { id?: string; path?: string }
1760
-
1761
- // Summary builds touch a session worktree's diff, history, and eval sidecars. Running one job per row
1762
- // multiplies those git children and their parsed indexes by the retained session count, so the shared
1763
- // projection queue has one bounded capacity for every project. A deployment can tune the capacity, but the
1764
- // default is deliberately serial: board assembly remains responsive and memory has a natural settle point.
1765
- const configuredProjectionConcurrency = Number(process.env.SPEXCODE_SESSION_EVAL_CONCURRENCY || 1)
1766
- const PROJECTION_CONCURRENCY = Number.isFinite(configuredProjectionConcurrency)
1767
- ? Math.max(1, Math.floor(configuredProjectionConcurrency))
1768
- : 1
1769
-
1770
- // Pure generation coordinator around an injected stable builder. Snapshot construction only serializes
1771
- // entries and authorizes the newest dirty generations; the async batch runs after that snapshot has captured
1772
- // `updating(lastKnown)`, then emits one completion nudge for all stable/error results in the batch.
1773
- export class SessionEvalProjectionCache {
1774
- readonly epoch: string
1775
- private readonly entries = new Map<string, ProjectionEntry>()
1776
- private readonly observerHolds = new Map<string, ProjectionTarget>()
1777
- private readonly observerWaiters = new Set<() => void>()
1778
- private batch: Promise<void> | null = null
1779
- private notify: () => void
1780
- private precompute: boolean
1781
- private readonly demandQueue: DemandJob<any>[] = []
1782
- private readonly demands = new Map<string, Promise<unknown>>()
1783
-
1784
- constructor(
1785
- private readonly build: SessionEvalSummaryBuilder,
1786
- notify: () => void = () => {},
1787
- epoch: string = randomUUID(),
1788
- precompute = true,
1789
- ) {
1790
- this.notify = notify
1791
- this.epoch = epoch
1792
- this.precompute = precompute
1793
- }
1794
-
1795
- setNotify(notify: () => void): void { this.notify = notify }
1796
-
1797
- setPrecompute(enabled: boolean): void {
1798
- if (this.precompute === enabled) return
1799
- this.precompute = enabled
1800
- for (const entry of this.entries.values()) {
1801
- if (!enabled) {
1802
- // A running build is allowed to settle; dropping only queued work prevents a last subscriber's
1803
- // departure from starting another historical walk after the era has ended.
1804
- if (entry.running == null) entry.scheduled = null
1805
- continue
1806
- }
1807
- this.authorize(entry)
1808
- }
1809
- if (enabled) queueMicrotask(() => this.startBatch())
1810
- }
1811
-
1812
- private authorize(entry: ProjectionEntry): void {
1813
- if (!this.precompute || entry.liveness === 'offline' || entry.observerHolds.size) return
1814
- if (entry.demandCancelledGeneration === entry.generation) return
1815
- if ((entry.phase === 'loading' || entry.phase === 'updating')
1816
- && entry.running !== entry.generation && entry.scheduled !== entry.generation)
1817
- entry.scheduled = entry.generation
1818
- }
1819
-
1820
- private ensureEntry(id: string, path: string): ProjectionEntry {
1821
- let entry = this.entries.get(id)
1822
- if (entry) {
1823
- entry.path = path || entry.path
1824
- return entry
1825
- }
1826
- entry = {
1827
- id,
1828
- path,
1829
- liveness: 'offline',
1830
- generation: 0,
1831
- phase: 'loading',
1832
- scheduled: null,
1833
- running: null,
1834
- demandCancelledGeneration: null,
1835
- observerHolds: new Set(),
1836
- }
1837
- this.entries.set(id, entry)
1838
- return entry
1839
- }
1840
-
1841
- snapshot(sessions: { id: string; path: string; liveness?: string }[]): Map<string, SessionEvalProjection> {
1842
- const live = new Set(sessions.map((session) => session.id))
1843
- for (const id of this.entries.keys()) if (!live.has(id)) this.entries.delete(id)
1844
- const out = new Map<string, SessionEvalProjection>()
1845
- for (const session of sessions) {
1846
- let entry = this.entries.get(session.id)
1847
- if (!entry) {
1848
- entry = {
1849
- id: session.id,
1850
- path: session.path,
1851
- // Unit tests and direct callers omit liveness; those callers retain the historical eager default.
1852
- liveness: session.liveness ?? 'online',
1853
- generation: 0,
1854
- phase: 'loading',
1855
- scheduled: null,
1856
- running: null,
1857
- demandCancelledGeneration: null,
1858
- observerHolds: new Set(),
1859
- }
1860
- this.entries.set(session.id, entry)
1861
- } else {
1862
- entry.path = session.path
1863
- entry.liveness = session.liveness ?? 'online'
1864
- }
1865
- entry.observerHolds = new Set([...this.observerHolds]
1866
- .filter(([, target]) => this.matches(entry!, target))
1867
- .map(([observer]) => observer))
1868
- if (entry.observerHolds.size) entry.phase = 'updating'
1869
- // Dormant history is demand-only. The graph still exposes a loading/last-known projection for an
1870
- // offline row, but does not fan out a summary build for every retained session. Selecting that row's
1871
- // eval calls buildSessionEvals directly; live rows are eager only during a delta stream era.
1872
- if (session.liveness === 'offline' && entry.running == null) entry.scheduled = null
1873
- this.authorize(entry)
1874
- out.set(session.id, this.project(entry))
1875
- }
1876
- queueMicrotask(() => this.startBatch())
1877
- return out
1878
- }
1879
-
1880
- invalidate(target: ProjectionTarget = 'all'): number {
1881
- let changed = 0
1882
- for (const entry of this.entries.values()) {
1883
- if (target !== 'all' && target.id !== entry.id && target.path !== entry.path) continue
1884
- entry.generation++
1885
- entry.phase = 'updating'
1886
- entry.scheduled = null
1887
- entry.demandCancelledGeneration = null
1888
- changed++
1889
- }
1890
- return changed
1891
- }
1892
-
1893
- holdObserver(observer: string, target: ProjectionTarget = 'all'): boolean {
1894
- if (this.observerHolds.has(observer)) return false
1895
- this.observerHolds.set(observer, target)
1896
- for (const entry of this.entries.values()) {
1897
- if (!this.matches(entry, target)) continue
1898
- entry.observerHolds.add(observer)
1899
- entry.generation++
1900
- entry.phase = 'updating'
1901
- entry.scheduled = null
1902
- entry.demandCancelledGeneration = null
1903
- }
1904
- return true
1905
- }
1906
-
1907
- releaseObserver(observer: string): boolean {
1908
- if (!this.observerHolds.delete(observer)) return false
1909
- for (const entry of this.entries.values()) {
1910
- if (!entry.observerHolds.delete(observer)) continue
1911
- entry.generation++
1912
- entry.phase = 'updating'
1913
- entry.scheduled = null
1914
- entry.demandCancelledGeneration = null
1915
- }
1916
- for (const check of [...this.observerWaiters]) check()
1917
- return true
1918
- }
1919
-
1920
- isObserverHeld(id: string, path: string): boolean {
1921
- const entry = this.entries.get(id)
1922
- if (entry?.observerHolds.size) return true
1923
- return [...this.observerHolds.values()].some((target) => this.matches({ id, path }, target))
1924
- }
1925
-
1926
- waitUntilObservable(id: string, path: string, timeoutMs: number): Promise<boolean> {
1927
- if (!this.isObserverHeld(id, path)) return Promise.resolve(true)
1928
- return new Promise((resolve) => {
1929
- let timer: ReturnType<typeof setTimeout> | null = null
1930
- const finish = (observable: boolean) => {
1931
- if (timer) clearTimeout(timer)
1932
- this.observerWaiters.delete(check)
1933
- resolve(observable)
1934
- }
1935
- const check = () => {
1936
- if (!this.isObserverHeld(id, path)) finish(true)
1937
- }
1938
- this.observerWaiters.add(check)
1939
- timer = setTimeout(() => finish(false), Math.max(0, timeoutMs))
1940
- timer.unref?.()
1941
- check()
1942
- })
1943
- }
1944
-
1945
- get(id: string): SessionEvalProjection | null {
1946
- const entry = this.entries.get(id)
1947
- return entry ? this.project(entry) : null
1948
- }
1949
-
1950
- async demand<T>(id: string, path: string, run: () => Promise<T>): Promise<T> {
1951
- const existing = this.demands.get(id)
1952
- if (existing) return existing as Promise<T>
1953
- const entry = this.ensureEntry(id, path)
1954
- // A queued summary for this same generation is superseded by the full demand build. If that demand
1955
- // rejects, snapshots must not recreate the cancelled eager work until a later invalidation advances g.
1956
- // A running summary is left alone; the priority job waits for it to settle before taking the slot.
1957
- if (entry.running == null && entry.scheduled === entry.generation) {
1958
- entry.scheduled = null
1959
- entry.demandCancelledGeneration = entry.generation
1960
- }
1961
- let resolve!: (value: T) => void
1962
- let reject!: (error: unknown) => void
1963
- const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
1964
- this.demands.set(id, promise)
1965
- this.demandQueue.push({ id, run, resolve, reject })
1966
- promise.finally(() => {
1967
- if (this.demands.get(id) === promise) this.demands.delete(id)
1968
- }).catch(() => {})
1969
- queueMicrotask(() => this.startBatch())
1970
- return promise
1971
- }
1972
-
1973
- async idle(): Promise<void> {
1974
- await Promise.resolve()
1975
- while (this.batch) await this.batch
1976
- }
1977
-
1978
- accept(id: string, generation: number, revision: string, value: SessionEvalSummary): boolean {
1979
- const entry = this.entries.get(id)
1980
- if (!entry || entry.generation !== generation || entry.observerHolds.size) return false
1981
- const changed = entry.phase !== 'ready' || entry.current?.revision !== revision
1982
- entry.current = { generation, revision, value }
1983
- entry.phase = 'ready'
1984
- entry.scheduled = null
1985
- if (changed) this.notify()
1986
- return true
1987
- }
1988
-
1989
- private project(entry: ProjectionEntry): SessionEvalProjection {
1990
- const stable = entry.current
1991
- return {
1992
- epoch: this.epoch,
1993
- generation: entry.generation,
1994
- phase: entry.phase,
1995
- ...(entry.phase === 'ready' && stable
1996
- ? { revision: stable.revision, value: stable.value }
1997
- : stable ? { lastKnown: stable } : {}),
1998
- }
1999
- }
2000
-
2001
- private matches(entry: { id: string; path: string }, target: ProjectionTarget): boolean {
2002
- return target === 'all' || target.id === entry.id || target.path === entry.path
2003
- }
2004
-
2005
- private hasPending(): boolean {
2006
- return this.demandQueue.length > 0
2007
- || [...this.entries.values()].some((entry) => entry.scheduled != null && entry.running == null)
2008
- }
2009
-
2010
- private publishCohort(staged: StagedProjection[]): boolean {
2011
- let changed = false
2012
- for (const { entry, generation, result } of staged) {
2013
- if (this.entries.get(entry.id) !== entry || entry.generation !== generation || entry.observerHolds.size) continue
2014
- if (result.kind === 'unstable') {
2015
- entry.generation++
2016
- entry.phase = 'updating'
2017
- entry.scheduled = null
2018
- entry.demandCancelledGeneration = null
2019
- this.authorize(entry)
2020
- changed = true
2021
- continue
2022
- }
2023
- if (result.kind === 'missing') {
2024
- changed = changed || entry.phase !== 'error'
2025
- entry.phase = 'error'
2026
- entry.scheduled = null
2027
- continue
2028
- }
2029
- changed = changed || entry.phase !== 'ready' || entry.current?.revision !== result.revision
2030
- entry.current = { generation, revision: result.revision, value: result.summary }
2031
- entry.phase = 'ready'
2032
- entry.scheduled = null
2033
- }
2034
- return changed
2035
- }
2036
-
2037
- private startBatch(): void {
2038
- if (this.batch) return
2039
- if (!this.hasPending()) return
2040
- this.batch = (async () => {
2041
- const demand = this.demandQueue.shift()
2042
- if (demand) {
2043
- try { demand.resolve(await demand.run()) }
2044
- catch (error) { demand.reject(error) }
2045
- return
2046
- }
2047
- // Freeze this finite cohort. Inputs that arrive later remain scheduled for the next batch, so a
2048
- // busy stream cannot keep a completed cohort unpublished forever.
2049
- const cohort = [...this.entries.values()]
2050
- .filter((entry) => entry.scheduled != null && entry.running == null)
2051
- .map((entry) => ({ entry, generation: entry.scheduled! }))
2052
- const staged: StagedProjection[] = []
2053
- for (let offset = 0; offset < cohort.length && !this.demandQueue.length; offset += PROJECTION_CONCURRENCY) {
2054
- const chunk = cohort.slice(offset, offset + PROJECTION_CONCURRENCY)
2055
- const results = await Promise.all(chunk.map((row) => this.runEntry(row)))
2056
- for (const result of results) if (result) staged.push(result)
2057
- }
2058
- if (this.publishCohort(staged)) this.notify()
2059
- })().finally(() => {
2060
- this.batch = null
2061
- if (this.hasPending()) this.startBatch()
2062
- })
2063
- }
2064
-
2065
- private async runEntry({ entry, generation }: ProjectionCohortRow): Promise<StagedProjection | null> {
2066
- if (this.entries.get(entry.id) !== entry || entry.generation !== generation
2067
- || entry.scheduled !== generation || entry.running != null) return null
2068
- entry.scheduled = null
2069
- entry.running = generation
2070
- let result: SummaryBuildResult
2071
- try { result = await this.build(entry.id, entry.path) }
2072
- catch (error) {
2073
- console.warn(`spec-eval: session summary build failed for ${entry.id}: ${error instanceof Error ? error.message : String(error)}`)
2074
- result = { kind: 'missing' }
2075
- }
2076
- entry.running = null
2077
- if (this.entries.get(entry.id) !== entry || entry.generation !== generation || entry.scheduled !== null) return null
2078
- return { entry, generation, result }
2079
- }
2080
- }
2081
-
2082
- async function buildSummaryAttempt(id: string, _path: string): Promise<SummaryBuildResult> {
2083
- const payload = await reviewPayload(id)
2084
- if (!payload) return { kind: 'missing' }
2085
- const wtPath = worktreePathForBranch(payload.branch)
2086
- const ctxPath = wtPath ?? repoRoot()
2087
- const before = await sessionEvalContentRevision(ctxPath)
2088
- const cacheKey = `${id}\0${before}`
2089
- const cached = summaryByContent.get(cacheKey)
2090
- if (cached) {
2091
- const after = await sessionEvalContentRevision(ctxPath)
2092
- return before === after
2093
- ? { kind: 'stable', revision: after, summary: cached.summary }
2094
- : { kind: 'unstable' }
2095
- }
2096
- const model = await buildSessionEvalModel(id, payload, wtPath)
2097
- const after = await sessionEvalContentRevision(ctxPath)
2098
- if (before !== after) return { kind: 'unstable' }
2099
- const summary = sessionEvalSummary(model.nodes)
2100
- // Keep one content-addressed stable value per session. Revisions, not elapsed time, decide reuse.
2101
- // This fold IS the demand's fold, so it deposits the model too and a later open replays it.
2102
- depositStableCut(id, after, { summary, model })
2103
- return { kind: 'stable', revision: after, summary }
2104
- }
2105
-
2106
- // ONE content-addressed cut per session, keyed by id + content revision, carrying the summary the graph
2107
- // reads and the full model a repeat open replays.
2108
- // @@@one builder, not two - these used to be separate folds: the graph's built latestOnly (latest reading
2109
- // per scenario) and deposited counts alone, so the demand path re-derived the WHOLE thing to get history
2110
- // the graph fold had held one line earlier and thrown away. The trim never made the fold cheaper — the
2111
- // expensive part is the freshness pass over every node in scope, and it ran identically either way — and
2112
- // it never mattered to the counts, because sessionEvalSummary folds latestPerScenario itself. So the trim
2113
- // bought nothing and cost a second full build per session per revision. The price of dropping it is
2114
- // MEMORY: a cut now retains complete A/B history rather than latest-per-scenario, bounded by the one-cut-
2115
- // per-session rule below.
2116
- type StableCut = { summary: SessionEvalSummary; model?: SessionEvalModel }
2117
- const summaryByContent = new Map<string, StableCut>()
2118
-
2119
- // Content addressing IS the invalidation: a moved input yields a different key. Keeping only the newest key
2120
- // per session bounds the map at one cut per session and drops summary and model together, so the two can
2121
- // never disagree about which revision they describe.
2122
- function depositStableCut(id: string, revision: string, cut: StableCut): void {
2123
- const key = `${id}\0${revision}`
2124
- const existing = summaryByContent.get(key)
2125
- for (const other of [...summaryByContent.keys()]) if (other.startsWith(`${id}\0`)) summaryByContent.delete(other)
2126
- summaryByContent.set(key, { summary: cut.summary, model: cut.model ?? existing?.model })
2127
- }
2128
- const projectionCache = new SessionEvalProjectionCache(buildSummaryAttempt, () => {}, randomUUID(), false)
2129
- const OBSERVER_RECOVERY_TIMEOUT_MS = 10_000
2130
-
2131
- async function awaitObservableInputs(id: string, path: string): Promise<void> {
2132
- if (await projectionCache.waitUntilObservable(id, path, OBSERVER_RECOVERY_TIMEOUT_MS)) return
2133
- throw new SessionEvalUnavailableError('session eval inputs remain temporarily unobservable')
2134
- }
2135
-
2136
- export function setSessionEvalProjectionNotify(notify: () => void): void { projectionCache.setNotify(notify) }
2137
- export function setSessionEvalProjectionWarmup(enabled: boolean): void { projectionCache.setPrecompute(enabled) }
2138
- export function sessionEvalProjections(sessions: { id: string; path: string; liveness?: string }[]): Map<string, SessionEvalProjection> {
2139
- return projectionCache.snapshot(sessions)
2140
- }
2141
- // The single-session READ of the same projection: no entry is minted, no build is scheduled, no generation
2142
- // moves. `null` means this cache has never held that session — a caller that must distinguish "not computed"
2143
- // from "computed and empty" gets to; one that builds instead goes through buildSessionEvals.
2144
- export function sessionEvalProjection(id: string): SessionEvalProjection | null {
2145
- return projectionCache.get(id)
2146
- }
2147
- export function invalidateSessionEvalProjections(target: 'all' | { id?: string; path?: string } = 'all'): number {
2148
- return projectionCache.invalidate(target)
2149
- }
2150
- export function holdSessionEvalProjectionObserver(
2151
- observer: string,
2152
- target: 'all' | { id?: string; path?: string } = 'all',
2153
- ): boolean {
2154
- return projectionCache.holdObserver(observer, target)
2155
- }
2156
- export function releaseSessionEvalProjectionObserver(observer: string): boolean {
2157
- return projectionCache.releaseObserver(observer)
2158
- }
2159
- export async function awaitSessionEvalProjectionIdle(): Promise<void> { await projectionCache.idle() }
2160
-
2161
- // `pick` makes this a FOCUSED build: the caller names, from the population's sequence, the few nodes whose
2162
- // verdicts its response will publish, and only those pay the freshness pass. A focused build is PARTIAL, so
2163
- // it never deposits — but it still prefers a cached FULL model when one exists, because a complete answer
2164
- // already paid for beats a cheap incomplete one.
2165
- export async function buildSessionEvals(id: string, pick?: SessionEvalFocus): Promise<SessionEvals | null> {
2166
- // A full model is demand-only, but it still runs through the projection queue. This gives a selected session
2167
- // priority over unrelated queued summaries without opening a second git/build lane.
2168
- for (;;) {
2169
- const attempt = await projectionCache.demand(id, '', async () => {
2170
- // a focused open renders no gates strip, so it reads the session's IDENTITY (a free store read)
2171
- // instead of its review payload (ahead count + dirty scan + merge-tree conflict probe).
2172
- const payload = pick ? reviewIdentity(id) : await reviewPayload(id)
2173
- if (!payload) return { kind: 'missing' as const }
2174
- const wtPath = worktreePathForBranch(payload.branch)
2175
- const ctxPath = wtPath ?? repoRoot()
2176
- const known = projectionCache.get(id)
2177
- const generation = known?.generation ?? 0
2178
- await awaitObservableInputs(id, ctxPath)
2179
- const before = await sessionEvalContentRevision(ctxPath)
2180
- // A repeat open at an unmoved revision replays the cut this same owner already published, instead of
2181
- // re-deriving it from Git. The stability, observer and generation fences below still decide whether the
2182
- // answer may be published, so a replay is certified exactly like a fresh fold.
2183
- // @@@a replay cannot hide a dead selector - the validation that raises 503 reads the declarations and
2184
- // trees the content revision already covers, so an identical revision has an identical verdict; and a
2185
- // failing fold deposits nothing, so an unavailable projection always re-derives and re-raises.
2186
- const replay = summaryByContent.get(`${id}\0${before}`)
2187
- if (replay?.model) {
2188
- const settled = await sessionEvalContentRevision(ctxPath)
2189
- const live = projectionCache.get(id)
2190
- if (before === settled && !projectionCache.isObserverHeld(id, ctxPath)
2191
- && !(live && live.generation !== generation)) {
2192
- return { kind: 'ready' as const, model: replay.model, summary: replay.summary, generation, revision: settled }
2193
- }
2194
- if (before !== settled) projectionCache.invalidate({ id })
2195
- return { kind: 'retry' as const }
2196
- }
2197
- const model = await buildSessionEvalModel(id, payload, wtPath, pick)
2198
- const after = await sessionEvalContentRevision(ctxPath)
2199
- const current = projectionCache.get(id)
2200
- if (before !== after || projectionCache.isObserverHeld(id, ctxPath)
2201
- || (current && current.generation !== generation)) {
2202
- if (before !== after) projectionCache.invalidate({ id })
2203
- return { kind: 'retry' as const }
2204
- }
2205
- // A focused model holds only the nodes it was asked to publish, so its counts are NOT the scope's and
2206
- // its nodes are NOT the scope's. Neither may be deposited or accepted: doing so would tell the list
2207
- // page and the graph that the session's whole evaluation is those few nodes.
2208
- if (model.order)
2209
- return { kind: 'ready' as const, model, summary: known?.value, generation, revision: after }
2210
- const summary = sessionEvalSummary(model.nodes)
2211
- // Only a settled fold deposits, and only here does a model enter the cut — a thrown build reaches
2212
- // neither line, so a failure can never poison the entry.
2213
- depositStableCut(id, after, { summary, model })
2214
- if (current) projectionCache.accept(id, generation, after, summary)
2215
- return { kind: 'ready' as const, model, summary, generation, revision: after }
2216
- })
2217
- if (attempt.kind === 'missing') return null
2218
- if (attempt.kind === 'retry') continue
2219
- return {
2220
- ...attempt.model,
2221
- // absent on a focused build whose cut holds no summary — never a fold over the rendered window
2222
- ...(attempt.summary ? { summary: attempt.summary } : {}),
2223
- evalRevision: { epoch: projectionCache.epoch, generation: attempt.generation, content: attempt.revision },
2224
- }
2225
- }
2226
- }