@namewta/skills-hub 0.1.49 → 0.1.52

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 (254) hide show
  1. package/README.md +4 -1
  2. package/THIRD_PARTY_NOTICES.md +19 -7
  3. package/cli.mjs +2 -2
  4. package/install.mjs +11 -4
  5. package/package.json +1 -1
  6. package/scripts/persistence/home.md +1 -1
  7. package/skills/dev/dev-build/SKILL.md +2 -0
  8. package/skills/dev/dev-build/references/implement-request.md +7 -2
  9. package/skills/dev/dev-formal-verify/SKILL.md +2 -1
  10. package/skills/dev/dev-formal-verify/references/create-check.md +3 -1
  11. package/skills/dev/dev-formal-verify/references/example.md +1 -1
  12. package/skills/dev/dev-formal-verify/references/tool-choice.md +1 -1
  13. package/skills/dev/dev-help/references/capabilities.md +6 -6
  14. package/skills/dev/dev-help/references/guide-verification.md +7 -1
  15. package/skills/dev/dev-help/references/help-method.md +7 -1
  16. package/skills/dev/dev-issue/SKILL.md +1 -0
  17. package/skills/dev/dev-issue/references/github-operations.md +8 -0
  18. package/skills/dev/dev-plan/references/plan-template.md +1 -0
  19. package/skills/dev/dev-plan/references/vertical-slicing.md +2 -0
  20. package/skills/dev/dev-pr/references/pull-request-evidence.md +2 -0
  21. package/skills/dev/dev-review/references/host-parity.md +12 -0
  22. package/skills/dev/dev-review/references/review-baseline.md +2 -0
  23. package/skills/dev/dev-setup/references/formal-options.md +1 -1
  24. package/skills/dev/dev-statechart/SKILL.md +17 -19
  25. package/skills/dev/dev-statechart/agents/openai.yaml +3 -3
  26. package/skills/dev/dev-statechart/assets/theme.css +135 -0
  27. package/skills/dev/dev-statechart/references/lean-proof.md +47 -0
  28. package/skills/dev/dev-statechart/references/render.md +15 -83
  29. package/skills/dev/dev-statechart/references/runtime.md +21 -1
  30. package/skills/dev/dev-statechart/scripts/lean/backends/lemma-chart.mjs +285 -0
  31. package/skills/dev/dev-statechart/scripts/lean/backends/mermaid.mjs +174 -0
  32. package/skills/dev/dev-statechart/scripts/lean/backends/proof-chart.mjs +540 -0
  33. package/skills/dev/dev-statechart/scripts/lean/backends/report.mjs +242 -0
  34. package/skills/dev/dev-statechart/scripts/lean/frontends/facts.mjs +234 -0
  35. package/skills/dev/dev-statechart/scripts/lean/frontends/view.mjs +217 -0
  36. package/skills/dev/dev-statechart/scripts/lean/ir.mjs +226 -0
  37. package/skills/dev/dev-statechart/scripts/lean/passes/attribute.mjs +148 -0
  38. package/skills/dev/dev-statechart/scripts/lean/passes/blocks.mjs +32 -0
  39. package/skills/dev/dev-statechart/scripts/lean/passes/budget.mjs +167 -0
  40. package/skills/dev/dev-statechart/scripts/lean/passes/check.mjs +70 -0
  41. package/skills/dev/dev-statechart/scripts/lean/passes/contract.mjs +160 -0
  42. package/skills/dev/dev-statechart/scripts/lean/passes/fold.mjs +206 -0
  43. package/skills/dev/dev-statechart/scripts/lean/passes/inline.mjs +84 -0
  44. package/skills/dev/dev-statechart/scripts/lean/passes/mark.mjs +432 -0
  45. package/skills/dev/dev-statechart/scripts/lean/passes/reduce.mjs +73 -0
  46. package/skills/dev/dev-statechart/scripts/lean/passes/trust.mjs +111 -0
  47. package/skills/dev/dev-statechart/scripts/lean/passes/view-lemmas.mjs +155 -0
  48. package/skills/dev/dev-statechart/scripts/lean/pipeline.mjs +164 -0
  49. package/skills/dev/dev-statechart/scripts/lean/run.mjs +168 -0
  50. package/skills/dev/dev-statechart/scripts/statechart.mjs +42 -23
  51. package/skills/dev/dev-statechart/scripts/worker.mjs +33 -7
  52. package/skills/dev/dev-ui-design/SKILL.md +2 -2
  53. package/skills/dev/dev-ui-design/references/interaction-review.md +9 -0
  54. package/skills/dev/dev-verify/SKILL.md +1 -1
  55. package/skills/dev/dev-verify/references/evidence-storage.md +12 -0
  56. package/skills/dev/dev-workflow/SKILL.md +6 -6
  57. package/skills/dev/dev-workflow/references/method-handoffs.md +7 -1
  58. package/skills/dev/dev-writing/SKILL.md +2 -0
  59. package/skills/dev/dev-writing/references/library-docs.md +37 -0
  60. package/skills/home/home-doctor/references/diagnosis.md +2 -2
  61. package/skills/home/home-doctor/scripts/doctor.mjs +68 -38
  62. package/skills/home/home-project-changelog/SKILL.md +7 -7
  63. package/skills/home/home-project-changelog/assets/project-changelog.example.json +188 -0
  64. package/skills/home/home-project-changelog/assets/project-changelog.schema.json +156 -0
  65. package/skills/home/home-project-changelog/assets/worker-brief.md +1 -1
  66. package/skills/home/home-project-changelog/references/git-ranges.md +2 -2
  67. package/skills/home/home-project-changelog/references/schema.md +61 -0
  68. package/skills/home/home-project-changelog/references/tools.md +28 -22
  69. package/skills/home/home-project-changelog/references/workflow.md +12 -9
  70. package/skills/home/home-project-changelog/references/writing.md +5 -3
  71. package/skills/home/home-project-changelog/scripts/changelog.mjs +42 -38
  72. package/skills/home/home-project-changelog/scripts/contract.mjs +40 -3
  73. package/skills/home/home-project-changelog/scripts/legacy-markdown.mjs +116 -0
  74. package/skills/home/home-project-changelog/scripts/migrate.mjs +122 -0
  75. package/skills/home/home-project-changelog/scripts/revision.mjs +2 -196
  76. package/skills/home/home-project-changelog/scripts/storage.mjs +120 -125
  77. package/skills/home/home-project-changelog/scripts/summary.mjs +0 -60
  78. package/skills/home/home-route/SKILL.md +2 -2
  79. package/skills/home/home-route/references/routing.md +3 -1
  80. package/skills/home/home-route/scripts/route.mjs +79 -11
  81. package/skills/home/home-setup/SKILL.md +2 -1
  82. package/skills/home/home-setup/assets/repos.schema.json +10 -0
  83. package/skills/home/home-setup/references/registry.md +18 -1
  84. package/skills/home/home-setup/scripts/registry.mjs +67 -7
  85. package/skills/home/home-website/SKILL.md +13 -9
  86. package/skills/home/home-website/assets/website/scripts/inputs.mjs +143 -128
  87. package/skills/home/home-website/assets/website/scripts/render.mjs +8 -6
  88. package/skills/home/home-website/assets/website/scripts/site.mjs +21 -10
  89. package/skills/home/home-website/assets/website/site/public/home-assets/app.js +81 -34
  90. package/skills/home/home-website/assets/website/site/public/home-assets/site.css +92 -70
  91. package/skills/home/home-website/assets/website/site/templates/favicon.png +0 -0
  92. package/skills/home/home-website/assets/website/site/templates/layout.mjs +13 -10
  93. package/skills/home/home-website/assets/website/site/templates/ledger.mjs +51 -46
  94. package/skills/home/home-website/assets/website/site/templates/model.mjs +58 -14
  95. package/skills/home/home-website/assets/website/site/templates/pages.mjs +28 -30
  96. package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +3 -107
  97. package/skills/home/home-website/assets/website/site.config.json +1 -1
  98. package/skills/home/home-website/references/website.md +64 -46
  99. package/skills/home/home-website/scripts/activate.mjs +106 -0
  100. package/skills/home/home-website/scripts/init.mjs +98 -11
  101. package/skills/home/home-workflow/SKILL.md +6 -4
  102. package/skills/system/system-clash-proxy-config/SKILL.md +21 -0
  103. package/skills/system/system-clash-proxy-config/agents/openai.yaml +4 -0
  104. package/skills/system/system-clash-proxy-config/assets/clash-override.js +328 -0
  105. package/skills/system/{system-proxy → system-clash-proxy-config}/references/browser-privacy.md +2 -2
  106. package/skills/system/{system-config → system-clash-proxy-config}/references/changes.md +2 -2
  107. package/skills/system/{system-proxy → system-clash-proxy-config}/references/clash-verge.md +1 -1
  108. package/skills/system/{system-proxy → system-clash-proxy-config}/references/diagnosis.md +1 -1
  109. package/skills/system/system-clash-proxy-config/references/dns-workflow.md +42 -0
  110. package/skills/system/system-clash-proxy-config/references/egress-macos.md +31 -0
  111. package/skills/system/system-clash-proxy-config/references/egress-windows.md +37 -0
  112. package/skills/system/system-clash-proxy-config/references/egress.md +12 -0
  113. package/skills/system/{system-proxy → system-clash-proxy-config}/references/flclash.md +1 -1
  114. package/skills/system/{system-proxy → system-clash-proxy-config}/references/index.md +1 -1
  115. package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/linux-cutover.md +29 -0
  116. package/skills/system/system-clash-proxy-config/references/locale-workflow.md +9 -0
  117. package/skills/system/{system-proxy → system-clash-proxy-config}/references/mihomo.md +1 -25
  118. package/skills/system/system-clash-proxy-config/references/session.md +34 -0
  119. package/skills/system/system-clash-proxy-config/references/subscription.md +29 -0
  120. package/skills/system/{system-proxy → system-clash-proxy-config}/references/troubleshooting.md +7 -7
  121. package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/verification.md +2 -0
  122. package/skills/system/system-clash-proxy-config/scripts/prepare-session.mjs +155 -0
  123. package/skills/system/system-clash-proxy-config/scripts/run-session.mjs +138 -0
  124. package/skills/system/system-inspect/SKILL.md +1 -1
  125. package/skills/system/system-inspect/references/health-audit.md +1 -1
  126. package/upstream-skills/zh-archify/SKILL.md +11 -11
  127. package/upstream-skills/zh-archify/assets/template.html +6 -3
  128. package/upstream-skills/zh-archify/bin/archify.mjs +67 -4
  129. package/upstream-skills/zh-archify/modules/code-analysis/ARCHITECTURE.md +7 -1
  130. package/upstream-skills/zh-archify/modules/code-analysis/bin/analyze-run.mjs +2 -1
  131. package/upstream-skills/zh-archify/modules/code-analysis/bin/check.mjs +29 -15
  132. package/upstream-skills/zh-archify/modules/code-analysis/bin/drift.mjs +3 -3
  133. package/upstream-skills/zh-archify/modules/code-analysis/bin/prepare.mjs +5 -6
  134. package/upstream-skills/zh-archify/modules/code-analysis/bin/serve.mjs +66 -36
  135. package/upstream-skills/zh-archify/modules/code-analysis/bin/verify-change.mjs +43 -13
  136. package/upstream-skills/zh-archify/modules/code-analysis/docs/TECH-GUIDE.md +1 -1
  137. package/upstream-skills/zh-archify/modules/code-analysis/docs/USAGE.md +37 -4
  138. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/functions.mjs +7 -5
  139. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/index.mjs +4 -1
  140. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/snapshot-host.mjs +9 -0
  141. package/upstream-skills/zh-archify/modules/code-analysis/lib/architecture-drift.mjs +28 -7
  142. package/upstream-skills/zh-archify/modules/code-analysis/lib/drift-capture.mjs +4 -3
  143. package/upstream-skills/zh-archify/modules/code-analysis/lib/git-sources.mjs +5 -3
  144. package/upstream-skills/zh-archify/modules/code-analysis/lib/output.mjs +272 -0
  145. package/upstream-skills/zh-archify/modules/code-analysis/lib/pull-request.mjs +34 -4
  146. package/upstream-skills/zh-archify/modules/code-analysis/lib/task.mjs +4 -2
  147. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification-context.mjs +13 -1
  148. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification-history.mjs +112 -0
  149. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification.mjs +6 -2
  150. package/upstream-skills/zh-archify/modules/code-analysis/overlay/atlas.mjs +71 -5
  151. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas.css +16 -2
  152. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas.js +121 -5
  153. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas3d.js +38 -1
  154. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/overlay.css +14 -1
  155. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/overlay.js +187 -27
  156. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/verification.js +1 -1
  157. package/upstream-skills/zh-archify/modules/code-analysis/overlay/i18n.mjs +9 -0
  158. package/upstream-skills/zh-archify/modules/code-analysis/overlay/inject.mjs +1 -1
  159. package/upstream-skills/zh-archify/modules/code-analysis/overlay/page.mjs +11 -6
  160. package/upstream-skills/zh-archify/modules/code-analysis/overlay/pull-request.mjs +1 -1
  161. package/upstream-skills/zh-archify/modules/code-analysis/schemas/ai-task.schema.json +1 -0
  162. package/upstream-skills/zh-archify/modules/code-analysis/test/atlas.test.mjs +88 -0
  163. package/upstream-skills/zh-archify/modules/code-analysis/test/duplicates.test.mjs +1 -1
  164. package/upstream-skills/zh-archify/modules/code-analysis/test/external-workflow.test.mjs +1 -1
  165. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/boundary.task.json +1 -0
  166. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/boundary.task.missing.json +1 -0
  167. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/complexity.task.json +1 -0
  168. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/complexity.task.valid.json +1 -0
  169. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/import-cycle.task.changed.json +1 -0
  170. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/import-cycle.task.json +1 -0
  171. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/module-cycle.task.json +1 -0
  172. package/upstream-skills/zh-archify/modules/code-analysis/test/function-source-range.test.mjs +10 -0
  173. package/upstream-skills/zh-archify/modules/code-analysis/test/output-recovery.test.mjs +626 -0
  174. package/upstream-skills/zh-archify/modules/code-analysis/test/pull-request.test.mjs +98 -2
  175. package/upstream-skills/zh-archify/modules/code-analysis/test/review.test.mjs +37 -0
  176. package/upstream-skills/zh-archify/modules/code-analysis/test/source-panel.test.mjs +2 -1
  177. package/upstream-skills/zh-archify/modules/code-analysis/test/task.test.mjs +3 -2
  178. package/upstream-skills/zh-archify/modules/code-analysis/test/verification-history.test.mjs +216 -0
  179. package/upstream-skills/zh-archify/modules/code-analysis/test/verification.test.mjs +122 -0
  180. package/upstream-skills/zh-archify/package-lock.json +2 -2
  181. package/upstream-skills/zh-archify/package.json +1 -1
  182. package/upstream-skills/zh-archify/references/authoring-contract.md +2 -0
  183. package/upstream-skills/zh-archify/references/explainer-authoring.md +1 -1
  184. package/upstream-skills/zh-archify/renderers/architecture/render-architecture.mjs +1 -0
  185. package/upstream-skills/zh-archify/renderers/class/render-class.mjs +1 -0
  186. package/upstream-skills/zh-archify/renderers/dataflow/render-dataflow.mjs +2 -1
  187. package/upstream-skills/zh-archify/renderers/erd/render-erd.mjs +1 -0
  188. package/upstream-skills/zh-archify/renderers/lifecycle/render-lifecycle.mjs +4 -2
  189. package/upstream-skills/zh-archify/renderers/sequence/render-sequence.mjs +4 -2
  190. package/upstream-skills/zh-archify/renderers/shared/cli.mjs +7 -1
  191. package/upstream-skills/zh-archify/renderers/timeline/render-timeline.mjs +1 -0
  192. package/upstream-skills/zh-archify/renderers/tree/render-tree.mjs +1 -0
  193. package/upstream-skills/zh-archify/renderers/waterfall/render-waterfall.mjs +1 -0
  194. package/upstream-skills/zh-archify/renderers/workflow/render-workflow.mjs +3 -2
  195. package/upstream-skills/zh-archify/renderers/workflow/workflow-compiler.mjs +68 -7
  196. package/upstream-skills/zh-archify/skill-release.json +1 -1
  197. package/upstream-skills/zh-modern-web-guidance/SKILL.md +4 -11
  198. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/language-detection.md +20 -0
  199. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/language-model.md +22 -0
  200. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/prompt-api.md +22 -0
  201. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/summarizer.md +20 -0
  202. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/translator.md +22 -0
  203. package/upstream-skills/zh-modern-web-guidance/guides/performance/custom-ml-model-inference.md +342 -0
  204. package/upstream-skills/zh-modern-web-guidance/guides/performance/data-parallel-computation.md +337 -0
  205. package/upstream-skills/zh-modern-web-guidance/guides/performance/improve-next-page-load-performance.md +4 -1
  206. package/upstream-skills/zh-modern-web-guidance/guides/performance/large-scene-rendering.md +350 -0
  207. package/upstream-skills/zh-modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md +9 -0
  208. package/upstream-skills/zh-modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md +9 -0
  209. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md +9 -0
  210. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md +9 -0
  211. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md +9 -0
  212. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/scroll-target-on-load.md +29 -0
  213. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/sortable-table.md +1 -0
  214. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/app-menus.md +9 -0
  215. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/context-menu.md +9 -0
  216. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/copy-button.md +9 -0
  217. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/dialog.md +10 -1
  218. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/hovercard.md +9 -0
  219. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/menu.md +9 -0
  220. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/navbar.md +9 -0
  221. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/persistent-app-tours.md +9 -0
  222. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/persistent-toast-notifications.md +9 -0
  223. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/toolbar.md +9 -0
  224. package/upstream-skills/zh-modern-web-guidance/guides/user-experience/content-first-noise-reduction.md +9 -0
  225. package/upstream-skills/zh-modern-web-guidance/guides/user-experience/natural-interactions.md +9 -0
  226. package/upstream-skills/zh-modern-web-guidance/guides/webmcp/agentic-javascript-tools.md +27 -0
  227. package/skills/home/home-project-changelog/assets/project-changelog.md +0 -35
  228. package/skills/system/system-clash-tun-egress/SKILL.md +0 -22
  229. package/skills/system/system-clash-tun-egress/agents/openai.yaml +0 -4
  230. package/skills/system/system-config/SKILL.md +0 -37
  231. package/skills/system/system-config/agents/openai.yaml +0 -4
  232. package/skills/system/system-config/references/ai-cli-config.md +0 -75
  233. package/skills/system/system-config/references/ai-cli-optimization.md +0 -37
  234. package/skills/system/system-config/references/index.md +0 -12
  235. package/skills/system/system-config/references/locale-workflow.md +0 -33
  236. package/skills/system/system-config/references/locale.md +0 -50
  237. package/skills/system/system-proxy/SKILL.md +0 -40
  238. package/skills/system/system-proxy/agents/openai.yaml +0 -4
  239. package/skills/system/system-proxy/assets/protected-rules.yaml +0 -7
  240. package/skills/system/system-proxy/references/dns-workflow.md +0 -152
  241. /package/skills/system/{system-config → system-clash-proxy-config}/assets/configuration.md +0 -0
  242. /package/skills/system/{system-proxy → system-clash-proxy-config}/assets/network.md +0 -0
  243. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/acceptance.md +0 -0
  244. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/dns-fields.md +0 -0
  245. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/dns-misconceptions.md +0 -0
  246. /package/skills/system/{system-clash-tun-egress/references/troubleshooting.md → system-clash-proxy-config/references/egress-troubleshooting.md} +0 -0
  247. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-linux.md +0 -0
  248. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-macos.md +0 -0
  249. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-windows.md +0 -0
  250. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/network-performance.md +0 -0
  251. /package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/nodes-and-dns.md +0 -0
  252. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/platform-dns.md +0 -0
  253. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/platforms.md +0 -0
  254. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/tun-dns.md +0 -0
@@ -0,0 +1,272 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash, randomBytes } from 'node:crypto';
5
+ import { DiagnosticError, fail } from '../core/index.mjs';
6
+
7
+ const RECOVERY_REQUIRED = 'analysis/output-recovery-required';
8
+ export const OUTPUT_BUSY = 'analysis/output-busy';
9
+ // Read older labels for rollback diagnostics, without using them to prove ownership.
10
+ const OWNER = /^(?<version>v2-)?(?<scope>[0-9a-f]{16}|unknown)-(?<pid>[1-9][0-9]{0,9})-[0-9a-f]{16}(?:-(?<started>[0-9]{1,20}))?$/;
11
+ const MOVE_PLAN = 'move-plan.json';
12
+ const ROLLBACK_FAILED = 'rollback-failed';
13
+ const unmarkedRollbacks = new Set();
14
+ const RECOVERY_FIXES = ['retain the output and backups for recovery', 'use another --out directory for a new run'];
15
+
16
+ export function needsOutputRecovery(error) {
17
+ return error instanceof DiagnosticError && error.diagnostics.some(diagnostic => diagnostic.code === RECOVERY_REQUIRED);
18
+ }
19
+
20
+ // The claimant owns this directory from reading the comparison through publish.
21
+ // Keep backups when a rollback cannot finish, so a retry cannot use mixed data.
22
+ export async function withAnalysisOutput(out, run) {
23
+ fs.mkdirSync(out, { recursive: true });
24
+ const lock = path.join(out, '.archify-analysis.lock');
25
+ const workspace = claimOutput(lock);
26
+ let preserve = false;
27
+ try {
28
+ return await run(workspace);
29
+ } catch (error) {
30
+ preserve = needsOutputRecovery(error);
31
+ throw error;
32
+ } finally {
33
+ if (!preserve) {
34
+ try {
35
+ fs.rmSync(workspace, { recursive: true, force: true });
36
+ removeVacantLock(lock);
37
+ } catch (error) {
38
+ // Cleanup can warn about a retained lock without changing a committed gate result.
39
+ process.emitWarning(`Could not remove the analysis output lock ${JSON.stringify(lock)} (${error.code || 'unknown error'}).`, { code: 'ARCHIFY_ANALYSIS_LOCK_CLEANUP' });
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+ function busy(lock, pid = null) {
46
+ fail(OUTPUT_BUSY, 'An analysis already owns this output directory.', {
47
+ subject: { out: path.dirname(lock), lock }, evidence: { pid },
48
+ supportedFixes: ['retry after the other analysis finishes or choose another --out directory'],
49
+ });
50
+ }
51
+
52
+ function removeVacantLock(lock) {
53
+ try {
54
+ fs.rmdirSync(lock);
55
+ } catch (error) {
56
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
57
+ }
58
+ }
59
+
60
+ function claimOutput(lock) {
61
+ const claimant = processIdentity();
62
+ const generation = claimant.started ? `-${claimant.started}` : '';
63
+ const label = `v2-${claimant.scope ?? 'unknown'}-${process.pid}-${randomBytes(8).toString('hex')}${generation}`;
64
+ const workspace = path.join(lock, label);
65
+ const candidate = fs.mkdtempSync(path.join(path.dirname(lock), '.archify-analysis.claim-'));
66
+ const claim = () => {
67
+ try {
68
+ // mkdir is exclusive even on Windows, where renaming a directory over
69
+ // an existing regular file can replace that file.
70
+ fs.mkdirSync(lock, { mode: 0o700 });
71
+ } catch (error) {
72
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES', 'ENOTDIR'].includes(error.code)) throw error;
73
+ return false;
74
+ }
75
+ let installed = false;
76
+ try {
77
+ fs.renameSync(path.join(candidate, label), workspace);
78
+ installed = true;
79
+ // Older versions can replace the empty lock before the owner is named.
80
+ // Continue only if this is the sole owner in the installed directory.
81
+ const owners = fs.readdirSync(lock);
82
+ if (owners.length !== 1 || owners[0] !== label) busy(lock);
83
+ } catch (error) {
84
+ if (installed) fs.rmSync(workspace, { recursive: true, force: true });
85
+ removeVacantLock(lock);
86
+ throw error;
87
+ }
88
+ return true;
89
+ };
90
+ try {
91
+ fs.mkdirSync(path.join(candidate, label));
92
+ if (claim()) return workspace;
93
+ let owners = [];
94
+ try {
95
+ if (outputEntry(lock, { directory: true })) owners = fs.readdirSync(lock, { withFileTypes: true });
96
+ } catch (error) {
97
+ if (error.code !== 'ENOENT') throw error;
98
+ }
99
+ // Another claimant may have created the lock but not its owner yet. An
100
+ // unowned empty directory cannot safely be reclaimed automatically.
101
+ if (owners.length === 0) busy(lock);
102
+ const [owner] = owners;
103
+ const identity = owners.length === 1 && owner.isDirectory() ? OWNER.exec(owner.name)?.groups : null;
104
+ const pid = identity ? Number(identity.pid) : null;
105
+ if (!identity || pid > 0x7fffffff) busy(lock, pid);
106
+
107
+ const abandoned = path.join(lock, owner.name);
108
+ const plan = path.join(abandoned, MOVE_PLAN);
109
+ // A workbench can stay alive after its publication has stopped.
110
+ const rollbackFailed = unmarkedRollbacks.has(owner.name) || outputEntry(path.join(abandoned, ROLLBACK_FAILED));
111
+ if (!rollbackFailed && !ownerExited(identity, pid, claimant)) busy(lock, pid);
112
+ if (rollbackFailed || outputEntry(plan)) {
113
+ const message = rollbackFailed
114
+ ? 'An analysis publication still needs recovery after a failed rollback.'
115
+ : 'An interrupted analysis left a publication that needs recovery.';
116
+ fail(RECOVERY_REQUIRED, message, {
117
+ subject: { out: path.dirname(lock), lock, plan }, evidence: { pid },
118
+ supportedFixes: RECOVERY_FIXES,
119
+ });
120
+ }
121
+ try {
122
+ // Claim this exact abandoned owner. If two retries race, only one can
123
+ // move its unique name, and the public lock never becomes vacant.
124
+ fs.renameSync(abandoned, workspace);
125
+ } catch (error) {
126
+ if (error.code === 'ENOENT') busy(lock);
127
+ throw error;
128
+ }
129
+ try {
130
+ for (const entry of fs.readdirSync(workspace)) fs.rmSync(path.join(workspace, entry), { recursive: true, force: true });
131
+ } catch (error) {
132
+ // The remaining staging may still be undeletable. Restore the abandoned
133
+ // owner so another attempt can reclaim it once the problem is fixed.
134
+ fs.renameSync(workspace, abandoned);
135
+ throw error;
136
+ }
137
+ return workspace;
138
+ } finally {
139
+ fs.rmSync(candidate, { recursive: true, force: true });
140
+ }
141
+ }
142
+
143
+ function ownerExited(owner, pid, claimant) {
144
+ if (!owner.version || !claimant.scope || owner.scope !== claimant.scope) return false;
145
+ try {
146
+ process.kill(pid, 0);
147
+ } catch (error) {
148
+ return error.code === 'ESRCH';
149
+ }
150
+ if (!claimant.started || !owner.started) return false;
151
+ const started = linuxStartTime(pid);
152
+ return started !== null && started !== owner.started;
153
+ }
154
+
155
+ function processIdentity() {
156
+ const { platform } = process;
157
+ const scope = [platform, os.hostname()];
158
+ let started = null;
159
+ if (platform === 'linux') {
160
+ const boot = readProc('sys/kernel/random/boot_id').trim();
161
+ const pidNamespace = linuxNamespace('pid');
162
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(boot) || !pidNamespace) return {};
163
+ // Start ticks are expressed in the reader's time namespace. A proc mount
164
+ // from an ancestor PID namespace also uses different IDs for /proc/<pid>.
165
+ const timeNamespace = linuxNamespace('time');
166
+ scope.push(boot, pidNamespace, timeNamespace);
167
+ const procPid = /^NStgid:[ \t]+([0-9]+)[ \t]*$/m.exec(readProc('self/status'))?.[1];
168
+ if (timeNamespace && procPid === String(process.pid)) started = linuxStartTime('self');
169
+ }
170
+ return { scope: createHash('sha256').update(JSON.stringify(scope)).digest('hex').slice(0, 16), started };
171
+ }
172
+
173
+ function linuxNamespace(name) {
174
+ try {
175
+ const { dev, ino } = fs.statSync(`/proc/self/ns/${name}`, { bigint: true });
176
+ return `${dev}:${ino}`;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+
182
+ function readProc(file) {
183
+ try {
184
+ return fs.readFileSync(`/proc/${file}`, 'utf8');
185
+ } catch {
186
+ return '';
187
+ }
188
+ }
189
+
190
+ function linuxStartTime(pid) {
191
+ const stat = readProc(`${pid}/stat`);
192
+ const commandEnd = stat.lastIndexOf(') ');
193
+ if (commandEnd < 0) return null;
194
+ // The parenthesized command may contain spaces and closing parentheses.
195
+ // Field 22 (starttime) is the twentieth field after the command.
196
+ const started = stat.slice(commandEnd + 2).trim().split(/\s+/)[19];
197
+ return /^[0-9]{1,20}$/.test(started ?? '') ? started : null;
198
+ }
199
+
200
+ export function outputEntry(target, { directory = false } = {}) {
201
+ try {
202
+ const stat = fs.lstatSync(target);
203
+ if (directory ? stat.isDirectory() : stat.isFile()) return stat;
204
+ fail('analysis/output-path-conflict', `An analysis output path is occupied by an unexpected entry: ${target}`, {
205
+ subject: { file: target }, supportedFixes: ['choose another --out directory or move the conflicting entry'],
206
+ });
207
+ } catch (error) {
208
+ if (error.code === 'ENOENT') return null;
209
+ throw error;
210
+ }
211
+ }
212
+
213
+ // All destinations have been made vacant by the time their move is applied.
214
+ // Reverse order restores both the staged candidate and any public entries.
215
+ export function publishAnalysisMoves(moves, lock) {
216
+ const plan = path.join(lock, MOVE_PLAN);
217
+ fs.writeFileSync(plan, JSON.stringify(moves, null, 2), { flag: 'wx' });
218
+ const applied = [];
219
+ try {
220
+ for (const [from, to] of moves) {
221
+ fs.renameSync(from, to);
222
+ applied.push([from, to]);
223
+ }
224
+ } catch (error) {
225
+ while (applied.length) {
226
+ const [from, to] = applied[applied.length - 1];
227
+ try {
228
+ fs.renameSync(to, from);
229
+ applied.pop();
230
+ } catch (rollback) {
231
+ const evidence = {
232
+ publishError: error.message,
233
+ rollbackError: rollback.message,
234
+ restore: applied.reverse().map(([before, after]) => ({ from: after, to: before })),
235
+ };
236
+ // The plan already protects the backups if recording the terminal state also fails.
237
+ try { fs.writeFileSync(path.join(lock, ROLLBACK_FAILED), '', { flag: 'wx' }); }
238
+ catch (markerError) {
239
+ unmarkedRollbacks.add(path.basename(lock));
240
+ evidence.recoveryMarkerError = markerError.message;
241
+ }
242
+ fail(RECOVERY_REQUIRED, 'Analysis publication failed and the previous output could not be fully restored.', {
243
+ subject: { out: path.dirname(path.dirname(lock)), lock, plan },
244
+ evidence,
245
+ supportedFixes: RECOVERY_FIXES,
246
+ });
247
+ }
248
+ }
249
+ throw error;
250
+ }
251
+ }
252
+
253
+ export function writeCheckOutputs(out, lock, files) {
254
+ const candidates = path.join(lock, 'next');
255
+ const backups = path.join(lock, 'previous');
256
+ fs.mkdirSync(candidates);
257
+ fs.mkdirSync(backups);
258
+ const moves = [];
259
+ for (const [name, contents] of files) {
260
+ const target = path.join(out, name);
261
+ const candidate = path.join(candidates, name);
262
+ const existing = outputEntry(target);
263
+ if (existing) fs.accessSync(target, fs.constants.W_OK);
264
+ fs.writeFileSync(candidate, contents, { flag: 'wx' });
265
+ if (existing) {
266
+ fs.chmodSync(candidate, existing.mode & 0o777);
267
+ moves.push([target, path.join(backups, name)]);
268
+ }
269
+ moves.push([candidate, target]);
270
+ }
271
+ publishAnalysisMoves(moves, lock);
272
+ }
@@ -120,7 +120,9 @@ export async function resolveLocalPullRequest(root, base, head, scope) {
120
120
  });
121
121
  }
122
122
  const context = await checkoutContext(root);
123
- return { root: context.root, scope: normalizeScope(scope ?? context.scope), local: { base, head } };
123
+ const resolved = { root: context.root, scope: normalizeScope(scope ?? context.scope), local: { base, head } };
124
+ await validateLocalObjectsAndScope(resolved.root, resolved.local, resolved.scope);
125
+ return resolved;
124
126
  }
125
127
 
126
128
  async function localFiles(root, base, head, scope) {
@@ -142,10 +144,11 @@ async function localFiles(root, base, head, scope) {
142
144
  return files;
143
145
  }
144
146
 
145
- async function prepareLocalPullRequest({ root, out, local, scope }) {
147
+ async function validateLocalObjectsAndScope(root, local, scope) {
146
148
  const readOptions = { noLazyFetch: true };
147
149
  const fixes = ['fetch the missing objects separately, then retry the same pinned comparison'];
148
- for (const [side, commit] of Object.entries(local)) {
150
+ const pins = Object.entries({ base: local.base, head: local.head });
151
+ for (const [side, commit] of pins) {
149
152
  let type;
150
153
  try { type = (await git(root, ['cat-file', '-t', commit], readOptions)).toString('ascii').trim(); }
151
154
  catch (error) {
@@ -156,6 +159,30 @@ async function prepareLocalPullRequest({ root, out, local, scope }) {
156
159
  }
157
160
  if (type !== 'commit') fail('pr/commit-invalid', 'A pinned object must be a commit.', { subject: { side }, evidence: { commit, type } });
158
161
  }
162
+ if (scope !== '.') {
163
+ const listings = await Promise.allSettled(pins.map(async ([side, sha]) => {
164
+ try { return await git(root, ['ls-tree', '-rz', '--full-tree', sha, '--', `${scope}/`], readOptions); }
165
+ catch (error) {
166
+ if (error.diagnostics?.[0]?.code !== 'pr/git-failed') throw error;
167
+ fail('pr/local-object-missing', 'The pinned source tree could not be read from the local Git object database.', {
168
+ subject: { side }, evidence: { commit: sha }, supportedFixes: fixes,
169
+ });
170
+ }
171
+ }));
172
+ // Report the first missing side in base/head order, regardless of Git process timing.
173
+ const entries = listings.map(listing => {
174
+ if (listing.status === 'rejected') throw listing.reason;
175
+ return listing.value;
176
+ });
177
+ if (entries.every(entry => !entry.length)) fail('pr/scope-invalid', 'The analysis scope has no entries in either pinned commit.', { subject: { scope }, evidence: { scope }, supportedFixes: ['choose a directory present in at least one pinned commit, or use --scope . for the repository root'] });
178
+ return Object.fromEntries(pins.map(([side], index) => [side, entries[index]]));
179
+ }
180
+ return null;
181
+ }
182
+
183
+ async function prepareLocalPullRequest({ root, out, local, scope }) {
184
+ const listings = await validateLocalObjectsAndScope(root, local, scope);
185
+ const fixes = ['fetch the missing objects separately, then retry the same pinned comparison'];
159
186
  const repository = path.basename(root);
160
187
  const pr = { repository, number: null, title: repository, url: null, local: true,
161
188
  baseSHA: local.base, mergeBaseSHA: local.base, headSHA: local.head, capturedAt: new Date().toISOString() };
@@ -164,7 +191,7 @@ async function prepareLocalPullRequest({ root, out, local, scope }) {
164
191
  const manifests = {};
165
192
  try {
166
193
  for (const [side, sha] of Object.entries(local)) {
167
- try { manifests[side] = await materializeTree({ cache: root, sha, scope, target: roots[side], offline: true }); }
194
+ try { manifests[side] = await materializeTree({ cache: root, sha, scope, target: roots[side], offline: true, preflightListing: listings?.[side] }); }
168
195
  catch (error) {
169
196
  const diagnostic = error.diagnostics?.[0];
170
197
  if (!diagnostic || !['pr/git-failed', 'pr/local-object-missing'].includes(diagnostic.code)) throw error;
@@ -173,6 +200,9 @@ async function prepareLocalPullRequest({ root, out, local, scope }) {
173
200
  });
174
201
  }
175
202
  }
203
+ if (scope !== '.' && Object.values(manifests).every(manifest => !manifest.files.length && !manifest.skipped.length)) {
204
+ fail('pr/scope-invalid', 'The analysis scope has no entries in either pinned commit.', { subject: { scope }, evidence: { scope }, supportedFixes: ['choose a directory present in at least one pinned commit, or use --scope . for the repository root'] });
205
+ }
176
206
  const changedFiles = await localFiles(root, local.base, local.head, scope);
177
207
  return { pr, scope, directory, roots, manifests, changedFiles, sourceGitRoot: root,
178
208
  source: side => ({ root: scope, revision: local[side], baseRevision: local.base, sourceKind: 'git-tree', url: null }) };
@@ -23,6 +23,7 @@ import { fail } from '../core/index.mjs';
23
23
  import { schemaErrors } from '../schemas/index.mjs';
24
24
  import { summarizeModule } from './module-summary.mjs';
25
25
  import { taskIdOf } from './task-id.mjs';
26
+ import { taskAnalysisDigest } from './verification-context.mjs';
26
27
 
27
28
  export const TASK_SCHEMA_VERSION = 1;
28
29
  export const KIND = 'archify-code-analysis-task';
@@ -205,7 +206,7 @@ function buildTaskWithContext({ findings, facts, ids, commands = [], review = nu
205
206
  ...(d.evidenceDigest ? { evidenceDigest: d.evidenceDigest } : {}),
206
207
  ...(d.external ? { external: d.external } : {}),
207
208
  })),
208
- source: { ...sourceOf(findings, facts), ...(external.length ? { external: externalSources } : {}) },
209
+ source: { ...sourceOf(findings, facts, context.analysisSha256 ??= taskAnalysisDigest(findings)), ...(external.length ? { external: externalSources } : {}) },
209
210
  locations,
210
211
  ...(moduleSummaries.length ? { moduleSummaries } : {}),
211
212
  facts: selected.map((d) => ({ findingId: d.id, statement: d.message, evidence: keyEvidence(d) })),
@@ -369,7 +370,7 @@ export function withExcerpt(loc, lines) {
369
370
 
370
371
  // ---- metadata ----------------------------------------------------------
371
372
 
372
- function sourceOf(findings, facts) {
373
+ function sourceOf(findings, facts, analysisSha256) {
373
374
  const repo = facts.repository || findings.repository || {};
374
375
  return {
375
376
  root: repo.root ?? null,
@@ -377,6 +378,7 @@ function sourceOf(findings, facts) {
377
378
  adapter: repo.adapter ?? null,
378
379
  sourceKind: repo.sourceKind ?? null,
379
380
  snapshotId: repo.snapshotId ?? null,
381
+ analysisSha256,
380
382
  configDigest: findings.analysis?.configDigest ?? null,
381
383
  analyzer: findings.analysis?.analyzer ?? null,
382
384
  // Context only: the analyzed text is the working tree, which may differ from HEAD.
@@ -1,6 +1,17 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { stableJson } from './analysis.mjs';
3
3
 
4
+ export function analysisDigest(doc) {
5
+ return createHash('sha256').update(stableJson(doc)).digest('hex');
6
+ }
7
+
8
+ // Supplemental source is already bound by the evidence and report digests.
9
+ // Duplicate copies of those bytes do not change a task's capture identity.
10
+ export function taskAnalysisDigest(doc) {
11
+ const { externalEvidence, ...capture } = doc;
12
+ return analysisDigest(capture);
13
+ }
14
+
4
15
  const sha = /^[a-f0-9]{64}$/;
5
16
 
6
17
  // Keep source text, commands, and finding messages out of the portable comparison input.
@@ -13,7 +24,7 @@ export function verificationContext(previous, current, review) {
13
24
 
14
25
  const snapshot = (doc) => ({
15
26
  snapshotId: doc.repository.snapshotId,
16
- analysisSha256: createHash('sha256').update(stableJson(doc)).digest('hex'),
27
+ analysisSha256: analysisDigest(doc),
17
28
  });
18
29
  const reports = (doc) => new Map((doc.analysis?.external || []).map((source) => [source.id, source.reportSha256]));
19
30
  const beforeReports = reports(previous), afterReports = reports(current);
@@ -23,6 +34,7 @@ export function verificationContext(previous, current, review) {
23
34
  const added = new Set(comparison.new);
24
35
  return {
25
36
  before: snapshot(previous),
37
+ taskAnalysisSha256: taskAnalysisDigest(previous),
26
38
  after: snapshot(current),
27
39
  root: previous.repository.root,
28
40
  configDigest: previous.analysis?.configDigest ?? null,
@@ -0,0 +1,112 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { schemaErrors } from '../schemas/index.mjs';
4
+ import { createHash } from 'node:crypto';
5
+ import { stableJson, loadPrevious } from './analysis.mjs';
6
+ import { reviewFindings } from './review.mjs';
7
+ import { taskAnalysisDigest, verificationContext } from './verification-context.mjs';
8
+
9
+ const name = 'verification-history.json';
10
+ const maxCaptures = 6;
11
+ const maxBytes = 4 * 1024 * 1024;
12
+ const ownerName = 'verification-owner.json';
13
+
14
+ function repositoryIdentity(root) {
15
+ const resolved = fs.realpathSync.native(root);
16
+ const canonical = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
17
+ const { dev, ino, birthtimeNs } = fs.statSync(resolved, { bigint: true });
18
+ // Some filesystems can reuse an inode within one creation-time tick.
19
+ // Leave new directories unattributed until the clock has advanced.
20
+ if (ino === 0n || birthtimeNs <= 0n || BigInt(Date.now() - 1000) * 1_000_000n <= birthtimeNs) return null;
21
+ return createHash('sha256').update(JSON.stringify([canonical, String(dev), String(ino), String(birthtimeNs)])).digest('hex');
22
+ }
23
+
24
+ export function sameVerificationRepository(currentDir, previousDir) {
25
+ try {
26
+ const read = dir => JSON.parse(fs.readFileSync(path.join(dir, ownerName), 'utf8')).identity;
27
+ const identity = read(currentDir);
28
+ return /^[a-f0-9]{64}$/.test(identity) && identity === read(previousDir);
29
+ } catch { return false; }
30
+ }
31
+
32
+ // An adjacent PR head is eligible only when both saved views identify the
33
+ // same PR and pins. The merge-base remains the ordinary comparison baseline.
34
+ export function matchingPreviousPullRequest(previousDir, current, currentPR) {
35
+ try {
36
+ const old = JSON.parse(fs.readFileSync(path.join(previousDir, 'view-context.json'), 'utf8')).run.pullRequest;
37
+ const previous = loadPrevious(path.join(previousDir, 'findings.json'));
38
+ if (!old || !currentPR || !previous || old.local || currentPR.local || !Number.isInteger(old.number) || old.number < 1
39
+ || old.number !== currentPR.number || typeof old.repository !== 'string' || typeof currentPR.repository !== 'string'
40
+ || old.repository.toLowerCase() !== currentPR.repository.toLowerCase()
41
+ || old.scope !== currentPR.scope || !/^[a-f0-9]{40}$/.test(old.baseSHA || '') || old.baseSHA !== currentPR.baseSHA
42
+ || !/^[a-f0-9]{40}$/.test(old.headSHA || '') || !/^[a-f0-9]{40}$/.test(currentPR.headSHA || '')
43
+ || previous.repository.revision !== old.headSHA || current.repository.revision !== currentPR.headSHA) return null;
44
+ return previous;
45
+ } catch { return null; }
46
+ }
47
+
48
+ function readHistory(dir) {
49
+ try {
50
+ const owner = JSON.parse(fs.readFileSync(path.join(dir, ownerName), 'utf8'));
51
+ if (!/^[a-f0-9]{64}$/.test(owner.identity)) return [];
52
+ const file = path.join(dir, name);
53
+ const stat = fs.statSync(file);
54
+ if (!stat.isFile() || stat.size > maxBytes) return [];
55
+ const history = JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ if (!Array.isArray(history) || history.length > maxCaptures) return [];
57
+ return history.filter((capture) => capture && !schemaErrors('findings', capture).length);
58
+ } catch { return []; }
59
+ }
60
+
61
+ function distinctCaptures(current, captures) {
62
+ const seen = new Set();
63
+ return captures.filter((capture) => {
64
+ if (!capture || capture.repository.root !== current.repository.root
65
+ || (capture.repository.sourceKind ?? 'working-tree') !== (current.repository.sourceKind ?? 'working-tree')) return false;
66
+ const digest = taskAnalysisDigest(capture);
67
+ if (seen.has(digest)) return false;
68
+ seen.add(digest);
69
+ return true;
70
+ });
71
+ }
72
+
73
+ // Write inside the staged run. Unchanged runs occupy one slot, and a failed
74
+ // scan never updates the published history.
75
+ export function retainVerificationBaselines(dir, previousDir, previous, current, root) {
76
+ const identity = repositoryIdentity(root);
77
+ fs.writeFileSync(path.join(dir, ownerName), JSON.stringify({ identity }));
78
+ const same = identity !== null && sameVerificationRepository(dir, previousDir);
79
+ const history = same ? readHistory(previousDir) : [];
80
+ // Keep the earlier byte-exact representative for an existing task identity.
81
+ // Checks exported against that capture must survive supplemental-only edits.
82
+ const priorIdentity = previous && taskAnalysisDigest(previous);
83
+ const retainedDuplicate = priorIdentity && history.find(capture => taskAnalysisDigest(capture) === priorIdentity);
84
+ const captures = same ? [retainedDuplicate || previous, previous, ...history] : [];
85
+ const saved = [];
86
+ const seen = new Set();
87
+ let bytes = 2;
88
+ for (const capture of captures) {
89
+ if (!capture || capture.repository.root !== current.repository.root ||
90
+ (capture.repository.sourceKind ?? 'working-tree') !== (current.repository.sourceKind ?? 'working-tree')) continue;
91
+ const digest = taskAnalysisDigest(capture);
92
+ if (seen.has(digest)) continue;
93
+ const size = Buffer.byteLength(JSON.stringify(capture)) + 1;
94
+ if (bytes + size > maxBytes) continue;
95
+ bytes += size;
96
+ saved.push(capture);
97
+ seen.add(digest);
98
+ if (saved.length === maxCaptures) break;
99
+ }
100
+ if (saved.length) fs.writeFileSync(path.join(dir, name), JSON.stringify(saved));
101
+ return saved;
102
+ }
103
+
104
+ export function verificationContexts(dir, previous, current, facts, history = readHistory(dir)) {
105
+ if (!current) return null;
106
+ const files = [...facts.files, ...(current.externalEvidence || [])].map((file) => file.path);
107
+ const contexts = distinctCaptures(current, [...history, previous]).map((capture) => {
108
+ const review = reviewFindings(current.diagnostics, { previous: capture, analysis: current.analysis, files });
109
+ return verificationContext(capture, current, review);
110
+ }).filter(Boolean);
111
+ return contexts.length ? contexts : null;
112
+ }
@@ -8,8 +8,12 @@ export async function evaluateVerification(context, task, reported, identifyTask
8
8
  if (task?.schema_version !== 1 || task.kind !== 'archify-code-analysis-task'
9
9
  || typeof task.taskId !== 'string' || !/^TASK-[a-f0-9]{12}$/.test(task.taskId) || !Array.isArray(task.findings)
10
10
  || !task.findings.length || task.findings.length > 100) return bad('invalid-task');
11
- if (task.source?.snapshotId !== context.before.snapshotId || task.source?.root !== context.root
12
- || (task.source?.configDigest ?? null) !== context.configDigest) return bad('wrong-task-snapshot');
11
+ const contexts = Array.isArray(context) ? context : [context];
12
+ const matches = contexts.filter((capture) => task.source?.snapshotId === capture.before.snapshotId
13
+ && task.source?.root === capture.root && (task.source?.configDigest ?? null) === capture.configDigest
14
+ && (!Object.hasOwn(task.source, 'analysisSha256') || task.source.analysisSha256 === capture.taskAnalysisSha256));
15
+ if (matches.length !== 1) return bad('wrong-task-snapshot');
16
+ context = matches[0];
13
17
 
14
18
  const selected = [], ids = new Set();
15
19
  for (const finding of task.findings) {
@@ -20,9 +20,58 @@
20
20
  // coupling; the side panel states the unresolved counts. Source text stays in
21
21
  // the Classic view, which the Atlas links to for any finding's evidence.
22
22
  import fs from 'node:fs';
23
+ import { createHash } from 'node:crypto';
24
+ import { createRequire } from 'node:module';
23
25
  import { clientAsset } from './client-assets.mjs';
24
26
 
25
27
  const compareText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
28
+ const require = createRequire(import.meta.url);
29
+
30
+ // A function expression's measured range does not include its binding. Only
31
+ // accept a uniquely bound top-level anonymous expression whose captured range
32
+ // still matches the parsed source; otherwise its apparent name may be local
33
+ // to the expression or ambiguous across scopes.
34
+ function boundExpressions(facts) {
35
+ const wanted = new Set((facts.functions || []).filter(fn => fn.syntaxKind === 'FunctionExpression').map(fn => fn.file));
36
+ const result = new Map();
37
+ if (!wanted.size) return result;
38
+ const ts = require('../vendor/typescript.cjs');
39
+ for (const file of facts.files || []) {
40
+ if (!wanted.has(file.path) || typeof file.sourceText !== 'string') continue;
41
+ const source = ts.createSourceFile(file.path, file.sourceText, ts.ScriptTarget.Latest, true);
42
+ if (source.parseDiagnostics.length) continue;
43
+ const declarations = new Map(), expressions = [], pending = [source];
44
+ while (pending.length) {
45
+ const node = pending.pop();
46
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
47
+ const name = node.name.text;
48
+ declarations.set(name, (declarations.get(name) || 0) + 1);
49
+ let init = node.initializer;
50
+ while (init && (ts.isParenthesizedExpression(init) || ts.isAsExpression(init) || ts.isSatisfiesExpression?.(init) || ts.isTypeAssertionExpression(init))) init = init.expression;
51
+ if (init && ts.isFunctionExpression(init) && !init.name && node.parent?.parent?.parent === source) expressions.push({ name, init });
52
+ }
53
+ ts.forEachChild(node, child => { pending.push(child); });
54
+ }
55
+ for (const { name, init } of expressions) {
56
+ if (declarations.get(name) !== 1) continue;
57
+ const start = init.getStart(source), end = init.getEnd(), pos = source.getLineAndCharacterOfPosition(start);
58
+ const digest = createHash('sha256').update(file.sourceText.slice(start, end)).digest('hex');
59
+ result.set(`${file.path}\0${pos.line + 1}\0${pos.character + 1}`, { name, digest });
60
+ }
61
+ }
62
+ return result;
63
+ }
64
+
65
+ function stableFunctionName(fn, expressions) {
66
+ if (fn.syntaxKind === 'FunctionExpression') {
67
+ const binding = expressions.get(`${fn.file}\0${fn.line}\0${fn.sourceRange?.column}`);
68
+ if (!binding || binding.name !== fn.name || binding.digest !== fn.sourceRange?.sha256) return false;
69
+ }
70
+ const name = fn.qualname || fn.name;
71
+ const owner = /^(?:MethodDeclaration|GetAccessor|SetAccessor)$/.test(fn.syntaxKind || '') && fn.name && name.endsWith(fn.name)
72
+ ? name.slice(0, -fn.name.length) : name;
73
+ return !/<(?:callback of |anonymous(?:#\d+)?>|(?:static|instance) initializer>)/.test(owner);
74
+ }
26
75
 
27
76
  // Shortest unambiguous label for each module: the fewest trailing path
28
77
  // segments that no other module shares (`executor`, `cache/decorators`).
@@ -75,7 +124,8 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) {
75
124
  (byModule.get(id) || byModule.set(id, []).get(id)).push(f);
76
125
  }
77
126
  const modules = graphModules.filter((m) => byModule.has(m.id));
78
- const labels = moduleLabels(modules.map((m) => m.path));
127
+ // A file at the selected scope root can form its own module with an empty directory path.
128
+ const labels = moduleLabels(modules.map((m) => m.path || (m.label === '(root)' ? '' : m.label)));
79
129
  const moduleIndex = new Map(modules.map((m, i) => [m.id, i]));
80
130
  const labelOf = (id) => (moduleIndex.has(id) ? labels[moduleIndex.get(id)] : id);
81
131
 
@@ -100,6 +150,10 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) {
100
150
 
101
151
  const accepted = new Set(Object.entries(review?.findings || {}).filter(([, r]) => r.status === 'accepted').map(([id]) => id));
102
152
  const listed = [];
153
+ // A qualified name can identify multiple declarations in the same file.
154
+ // Link only a unique finding and function with the same declaration range.
155
+ const functionKey = (file, name, line, endLine) => file && name && Number.isInteger(line) && Number.isInteger(endLine) && endLine >= line
156
+ ? JSON.stringify([file, name, line, endLine]) : null;
103
157
  const functionFinding = new Map();
104
158
  for (const f of findings) {
105
159
  const s = f.subject || {};
@@ -113,7 +167,8 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) {
113
167
  }
114
168
  } else if (f.code === 'complexity/function' && fileIndex.has(s.file)) {
115
169
  entry.kind = 'function';
116
- functionFinding.set(`${s.file}\u0000${s.function}`, listed.length);
170
+ const key = functionKey(s.file, s.function, s.line, s.endLine);
171
+ if (key) functionFinding.set(key, functionFinding.has(key) ? -1 : listed.length);
117
172
  } else if (f.code === 'coupling/import-cycle' && Array.isArray(s.files)) {
118
173
  entry.kind = 'cycle';
119
174
  entry.files = s.files.filter((p) => fileIndex.has(p)).map((p) => fileIndex.get(p));
@@ -147,11 +202,22 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) {
147
202
  }
148
203
 
149
204
  // [file, name, line, complexity, nesting, length, finding index or -1]
205
+ const expressions = boundExpressions(facts);
206
+ const functionCounts = new Map();
207
+ for (const fn of facts.functions || []) {
208
+ const key = functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine);
209
+ if (key) functionCounts.set(key, (functionCounts.get(key) || 0) + 1);
210
+ }
150
211
  const functions = (facts.functions || [])
151
212
  .filter((fn) => fileIndex.has(fn.file))
152
213
  .map((fn) => [fileIndex.get(fn.file), fn.qualname || fn.name, fn.line, fn.complexity, fn.nesting ?? 0, (fn.endLine ?? fn.line) - fn.line + 1,
153
- functionFinding.has(`${fn.file}\u0000${fn.qualname}`) ? functionFinding.get(`${fn.file}\u0000${fn.qualname}`) : -1,
154
- fn.sourceRange ? { column: fn.sourceRange.column, endLine: fn.sourceRange.endLine, endColumn: fn.sourceRange.endColumn } : null])
214
+ functionCounts.get(functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine)) === 1
215
+ ? functionFinding.get(functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine)) ?? -1 : -1,
216
+ fn.sourceRange ? { column: fn.sourceRange.column, endLine: fn.sourceRange.endLine, endColumn: fn.sourceRange.endColumn } : null,
217
+ fn.definition ? fn.definition.sourceRange?.sha256 || null : fn.sourceRange?.sha256 || null,
218
+ // Display names of callbacks and Java anonymous owners are numbered by
219
+ // source order. A quoted JS method named <anonymous> is a real name.
220
+ stableFunctionName(fn, expressions)])
155
221
  .sort((a, b) => a[0] - b[0] || a[2] - b[2] || compareText(a[1], b[1]));
156
222
  for (const [i, fn] of functions.entries()) if (fn[6] !== -1) listed[fn[6]].fn = i;
157
223
 
@@ -159,7 +225,7 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) {
159
225
  return {
160
226
  language: facts.repository?.language ?? null,
161
227
  measured: Array.isArray(facts.functions),
162
- modules: modules.map((m, i) => ({ id: m.id, label: labels[i], path: m.path, fanIn: m.fanIn, fanOut: m.fanOut })),
228
+ modules: modules.map((m, i) => ({ id: m.id, label: labels[i], path: m.path, rootGroup: m.path === '' && m.label === '(root)', fanIn: m.fanIn, fanOut: m.fanOut })),
163
229
  files: files.map((f) => [f.path, f.module, f.loc]),
164
230
  edges,
165
231
  functions,