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