self-evolving-workflow 0.0.0-stage → 0.1.4

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 (375) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +195 -2
  3. package/dist/agent-memory-prompts.d.ts +13 -0
  4. package/dist/agent-memory-prompts.js +55 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +6 -0
  7. package/dist/closeout.d.ts +105 -0
  8. package/dist/closeout.js +473 -0
  9. package/dist/code.d.ts +39 -0
  10. package/dist/code.js +124 -0
  11. package/dist/codex-memory.d.ts +24 -0
  12. package/dist/codex-memory.js +217 -0
  13. package/dist/common.d.ts +16 -0
  14. package/dist/common.js +52 -0
  15. package/dist/context-envelope.d.ts +59 -0
  16. package/dist/context-envelope.js +23 -0
  17. package/dist/host-adapters.d.ts +34 -0
  18. package/dist/host-adapters.js +151 -0
  19. package/dist/http.d.ts +3 -0
  20. package/dist/http.js +90 -0
  21. package/dist/index.d.ts +16 -0
  22. package/dist/index.js +13 -0
  23. package/dist/knowledge-cli.d.ts +198 -0
  24. package/dist/knowledge-cli.js +761 -0
  25. package/dist/knowledge-reads.d.ts +72 -0
  26. package/dist/knowledge-reads.js +201 -0
  27. package/dist/memory-config.d.ts +44 -0
  28. package/dist/memory-config.js +204 -0
  29. package/dist/memory-evidence.d.ts +13 -0
  30. package/dist/memory-evidence.js +40 -0
  31. package/dist/memory-history.d.ts +46 -0
  32. package/dist/memory-history.js +432 -0
  33. package/dist/memory.d.ts +96 -0
  34. package/dist/memory.js +362 -0
  35. package/dist/retrospective.d.ts +57 -0
  36. package/dist/retrospective.js +240 -0
  37. package/dist/search.d.ts +36 -0
  38. package/dist/search.js +112 -0
  39. package/dist/skill-addition.d.ts +25 -0
  40. package/dist/skill-addition.js +89 -0
  41. package/dist/skill-design.d.ts +96 -0
  42. package/dist/skill-design.js +226 -0
  43. package/dist/skill-replay.d.ts +55 -0
  44. package/dist/skill-replay.js +448 -0
  45. package/dist/skill-route.d.ts +30 -0
  46. package/dist/skill-route.js +75 -0
  47. package/dist/transcript-evidence.d.ts +3 -0
  48. package/dist/transcript-evidence.js +58 -0
  49. package/dist/upstream/chunker.d.ts +24 -0
  50. package/dist/upstream/chunker.js +96 -0
  51. package/dist/upstream/file-protocol.d.ts +45 -0
  52. package/dist/upstream/file-protocol.js +117 -0
  53. package/dist/upstream/frontmatter.d.ts +47 -0
  54. package/dist/upstream/frontmatter.js +86 -0
  55. package/dist/upstream/graph-search.d.ts +33 -0
  56. package/dist/upstream/graph-search.js +67 -0
  57. package/dist/upstream/l1-extraction.d.ts +26 -0
  58. package/dist/upstream/l1-extraction.js +405 -0
  59. package/dist/upstream/llm.d.ts +8 -0
  60. package/dist/upstream/llm.js +1 -0
  61. package/dist/upstream/merge.d.ts +50 -0
  62. package/dist/upstream/merge.js +153 -0
  63. package/dist/upstream/prompts.d.ts +53 -0
  64. package/dist/upstream/prompts.js +181 -0
  65. package/dist/upstream/search-utils.d.ts +34 -0
  66. package/dist/upstream/search-utils.js +55 -0
  67. package/dist/upstream/slug.d.ts +26 -0
  68. package/dist/upstream/slug.js +103 -0
  69. package/dist/upstream/template.d.ts +29 -0
  70. package/dist/upstream/template.js +80 -0
  71. package/dist/upstream/tokenize.d.ts +4 -0
  72. package/dist/upstream/tokenize.js +29 -0
  73. package/dist/wiki-change.d.ts +76 -0
  74. package/dist/wiki-change.js +299 -0
  75. package/dist/wiki-entry.d.ts +26 -0
  76. package/dist/wiki-entry.js +93 -0
  77. package/dist/wiki-ingest.d.ts +12 -0
  78. package/dist/wiki-ingest.js +126 -0
  79. package/dist/wiki-migration.d.ts +16 -0
  80. package/dist/wiki-migration.js +268 -0
  81. package/dist/wiki-tokens.d.ts +1 -0
  82. package/dist/wiki-tokens.js +46 -0
  83. package/dist/wiki.d.ts +103 -0
  84. package/dist/wiki.js +330 -0
  85. package/dist/workflow-cli.d.ts +2 -0
  86. package/dist/workflow-cli.js +319 -0
  87. package/dist/workflow-install.d.ts +37 -0
  88. package/dist/workflow-install.js +148 -0
  89. package/dist/workflow-knowledge.d.ts +18 -0
  90. package/dist/workflow-knowledge.js +32 -0
  91. package/dist/workflow-mcp.d.ts +2 -0
  92. package/dist/workflow-mcp.js +137 -0
  93. package/dist/workflow-names.d.ts +4 -0
  94. package/dist/workflow-names.js +31 -0
  95. package/dist/workflow-runtime.d.ts +735 -0
  96. package/dist/workflow-runtime.js +747 -0
  97. package/dist/workflow-skills.d.ts +48 -0
  98. package/dist/workflow-skills.js +141 -0
  99. package/docs/images/impeccable-skill.png +0 -0
  100. package/docs/images/workflow-overview.png +0 -0
  101. package/docs/images/workflow-skills.png +0 -0
  102. package/package.json +77 -4
  103. package/skills/ew-impeccable/LICENSE +191 -0
  104. package/skills/ew-impeccable/NOTICE.md +19 -0
  105. package/skills/ew-impeccable/SKILL.md +91 -0
  106. package/skills/ew-impeccable/UPSTREAM.md +23 -0
  107. package/skills/ew-impeccable/reference/adapt.md +314 -0
  108. package/skills/ew-impeccable/reference/adapt.native.md +60 -0
  109. package/skills/ew-impeccable/reference/android.md +46 -0
  110. package/skills/ew-impeccable/reference/animate.md +91 -0
  111. package/skills/ew-impeccable/reference/audit.md +138 -0
  112. package/skills/ew-impeccable/reference/audit.native.md +141 -0
  113. package/skills/ew-impeccable/reference/bolder.md +35 -0
  114. package/skills/ew-impeccable/reference/clarify.md +96 -0
  115. package/skills/ew-impeccable/reference/colorize.md +88 -0
  116. package/skills/ew-impeccable/reference/craft-floor.md +44 -0
  117. package/skills/ew-impeccable/reference/craft.md +5 -0
  118. package/skills/ew-impeccable/reference/critique.md +808 -0
  119. package/skills/ew-impeccable/reference/degraded/asset-producer.md +36 -0
  120. package/skills/ew-impeccable/reference/degraded/documenter.md +23 -0
  121. package/skills/ew-impeccable/reference/degraded/finish-reviewer.md +72 -0
  122. package/skills/ew-impeccable/reference/degraded/manual-edit-applier.md +91 -0
  123. package/skills/ew-impeccable/reference/delight.md +72 -0
  124. package/skills/ew-impeccable/reference/distill.md +113 -0
  125. package/skills/ew-impeccable/reference/doctor.md +56 -0
  126. package/skills/ew-impeccable/reference/document.md +418 -0
  127. package/skills/ew-impeccable/reference/extract.md +68 -0
  128. package/skills/ew-impeccable/reference/harden.md +338 -0
  129. package/skills/ew-impeccable/reference/hooks.md +113 -0
  130. package/skills/ew-impeccable/reference/init.md +133 -0
  131. package/skills/ew-impeccable/reference/ios.md +51 -0
  132. package/skills/ew-impeccable/reference/layout.md +86 -0
  133. package/skills/ew-impeccable/reference/live-setup.md +102 -0
  134. package/skills/ew-impeccable/reference/live.md +326 -0
  135. package/skills/ew-impeccable/reference/new-work.md +209 -0
  136. package/skills/ew-impeccable/reference/onboard.md +236 -0
  137. package/skills/ew-impeccable/reference/operate.md +61 -0
  138. package/skills/ew-impeccable/reference/optimize.md +260 -0
  139. package/skills/ew-impeccable/reference/overdrive.md +127 -0
  140. package/skills/ew-impeccable/reference/polish.md +105 -0
  141. package/skills/ew-impeccable/reference/quieter.md +101 -0
  142. package/skills/ew-impeccable/reference/routing.md +20 -0
  143. package/skills/ew-impeccable/reference/shape.md +59 -0
  144. package/skills/ew-impeccable/reference/typeset.md +82 -0
  145. package/skills/ew-impeccable/reference/visualize.md +46 -0
  146. package/skills/ew-impeccable/scripts/build-phase.mjs +1022 -0
  147. package/skills/ew-impeccable/scripts/command-metadata.json +94 -0
  148. package/skills/ew-impeccable/scripts/comp-diff.mjs +391 -0
  149. package/skills/ew-impeccable/scripts/comp-spec.mjs +513 -0
  150. package/skills/ew-impeccable/scripts/concept-seed.mjs +814 -0
  151. package/skills/ew-impeccable/scripts/context-signals.mjs +325 -0
  152. package/skills/ew-impeccable/scripts/context.mjs +1521 -0
  153. package/skills/ew-impeccable/scripts/critique-storage.mjs +473 -0
  154. package/skills/ew-impeccable/scripts/data/font-index-failures.json +121 -0
  155. package/skills/ew-impeccable/scripts/data/font-index.json +1 -0
  156. package/skills/ew-impeccable/scripts/detect-csp.mjs +246 -0
  157. package/skills/ew-impeccable/scripts/detect.mjs +30 -0
  158. package/skills/ew-impeccable/scripts/detector/browser/injected/index.mjs +2580 -0
  159. package/skills/ew-impeccable/scripts/detector/cli/main.mjs +498 -0
  160. package/skills/ew-impeccable/scripts/detector/design-system.mjs +1311 -0
  161. package/skills/ew-impeccable/scripts/detector/detect-antipatterns-browser.js +9486 -0
  162. package/skills/ew-impeccable/scripts/detector/detect-antipatterns.mjs +51 -0
  163. package/skills/ew-impeccable/scripts/detector/engines/browser/detect-url.mjs +434 -0
  164. package/skills/ew-impeccable/scripts/detector/engines/regex/detect-text.mjs +1439 -0
  165. package/skills/ew-impeccable/scripts/detector/engines/static-html/css-cascade.mjs +1242 -0
  166. package/skills/ew-impeccable/scripts/detector/engines/static-html/detect-html.mjs +263 -0
  167. package/skills/ew-impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs +189 -0
  168. package/skills/ew-impeccable/scripts/detector/findings.mjs +23 -0
  169. package/skills/ew-impeccable/scripts/detector/node/file-system.mjs +225 -0
  170. package/skills/ew-impeccable/scripts/detector/profile/profiler.mjs +166 -0
  171. package/skills/ew-impeccable/scripts/detector/registry/antipatterns.mjs +636 -0
  172. package/skills/ew-impeccable/scripts/detector/rules/checks.mjs +5750 -0
  173. package/skills/ew-impeccable/scripts/detector/shared/color.mjs +596 -0
  174. package/skills/ew-impeccable/scripts/detector/shared/constants.mjs +127 -0
  175. package/skills/ew-impeccable/scripts/detector/shared/fonts.mjs +30 -0
  176. package/skills/ew-impeccable/scripts/detector/shared/inline-ignores.mjs +148 -0
  177. package/skills/ew-impeccable/scripts/detector/shared/page.mjs +7 -0
  178. package/skills/ew-impeccable/scripts/detector/vendor/MDN-DATA-LICENSE +116 -0
  179. package/skills/ew-impeccable/scripts/detector/vendor/THIRD_PARTY_LICENSES.md +227 -0
  180. package/skills/ew-impeccable/scripts/detector/vendor/static-html-parser.build-entry.txt +11 -0
  181. package/skills/ew-impeccable/scripts/detector/vendor/static-html-parser.bundle.mjs +9121 -0
  182. package/skills/ew-impeccable/scripts/doctor.mjs +330 -0
  183. package/skills/ew-impeccable/scripts/embed-prompt.mjs +166 -0
  184. package/skills/ew-impeccable/scripts/font-match.mjs +457 -0
  185. package/skills/ew-impeccable/scripts/generate-image.mjs +447 -0
  186. package/skills/ew-impeccable/scripts/hook-admin.mjs +829 -0
  187. package/skills/ew-impeccable/scripts/hook-before-edit.mjs +538 -0
  188. package/skills/ew-impeccable/scripts/hook-lib.mjs +2493 -0
  189. package/skills/ew-impeccable/scripts/hook.mjs +79 -0
  190. package/skills/ew-impeccable/scripts/lib/artifact-schema.mjs +93 -0
  191. package/skills/ew-impeccable/scripts/lib/composition-catalog.mjs +200 -0
  192. package/skills/ew-impeccable/scripts/lib/concept-catalog.mjs +395 -0
  193. package/skills/ew-impeccable/scripts/lib/design-parser.mjs +880 -0
  194. package/skills/ew-impeccable/scripts/lib/font-fingerprint.mjs +564 -0
  195. package/skills/ew-impeccable/scripts/lib/font-index.mjs +130 -0
  196. package/skills/ew-impeccable/scripts/lib/hero-checks.mjs +246 -0
  197. package/skills/ew-impeccable/scripts/lib/image-metrics.mjs +306 -0
  198. package/skills/ew-impeccable/scripts/lib/impeccable-config.mjs +640 -0
  199. package/skills/ew-impeccable/scripts/lib/impeccable-paths.mjs +137 -0
  200. package/skills/ew-impeccable/scripts/lib/is-generated.mjs +72 -0
  201. package/skills/ew-impeccable/scripts/lib/live-path-globs.mjs +37 -0
  202. package/skills/ew-impeccable/scripts/lib/open-system-browser.mjs +26 -0
  203. package/skills/ew-impeccable/scripts/lib/png.mjs +281 -0
  204. package/skills/ew-impeccable/scripts/lib/provider.mjs +5 -0
  205. package/skills/ew-impeccable/scripts/lib/raster.mjs +194 -0
  206. package/skills/ew-impeccable/scripts/lib/roll-selection.mjs +369 -0
  207. package/skills/ew-impeccable/scripts/lib/staleness-deep.mjs +491 -0
  208. package/skills/ew-impeccable/scripts/lib/staleness-notice.mjs +169 -0
  209. package/skills/ew-impeccable/scripts/lib/staleness.mjs +532 -0
  210. package/skills/ew-impeccable/scripts/lib/surface-briefs.mjs +149 -0
  211. package/skills/ew-impeccable/scripts/lib/target-args.mjs +42 -0
  212. package/skills/ew-impeccable/scripts/lib/target-slug.mjs +33 -0
  213. package/skills/ew-impeccable/scripts/lib/template-extensions.mjs +146 -0
  214. package/skills/ew-impeccable/scripts/live/accept-css.mjs +617 -0
  215. package/skills/ew-impeccable/scripts/live/accept-verify.mjs +60 -0
  216. package/skills/ew-impeccable/scripts/live/browser-script-parts.mjs +84 -0
  217. package/skills/ew-impeccable/scripts/live/completion.mjs +28 -0
  218. package/skills/ew-impeccable/scripts/live/event-validation.mjs +199 -0
  219. package/skills/ew-impeccable/scripts/live/frameworks/astro.mjs +47 -0
  220. package/skills/ew-impeccable/scripts/live/frameworks/detect-utils.mjs +73 -0
  221. package/skills/ew-impeccable/scripts/live/frameworks/index.mjs +143 -0
  222. package/skills/ew-impeccable/scripts/live/frameworks/journal.mjs +197 -0
  223. package/skills/ew-impeccable/scripts/live/frameworks/nextjs.mjs +49 -0
  224. package/skills/ew-impeccable/scripts/live/frameworks/nuxt.mjs +161 -0
  225. package/skills/ew-impeccable/scripts/live/frameworks/script-src.mjs +17 -0
  226. package/skills/ew-impeccable/scripts/live/frameworks/static-html.mjs +26 -0
  227. package/skills/ew-impeccable/scripts/live/frameworks/sveltekit.mjs +71 -0
  228. package/skills/ew-impeccable/scripts/live/frameworks/tag-strategy.mjs +247 -0
  229. package/skills/ew-impeccable/scripts/live/frameworks/tanstack-start.mjs +70 -0
  230. package/skills/ew-impeccable/scripts/live/frameworks/vite-generic.mjs +42 -0
  231. package/skills/ew-impeccable/scripts/live/generation-preflight.mjs +149 -0
  232. package/skills/ew-impeccable/scripts/live/insert-ui.mjs +458 -0
  233. package/skills/ew-impeccable/scripts/live/instructions.mjs +142 -0
  234. package/skills/ew-impeccable/scripts/live/manual-apply.mjs +939 -0
  235. package/skills/ew-impeccable/scripts/live/manual-edit-routes.mjs +357 -0
  236. package/skills/ew-impeccable/scripts/live/manual-edits-buffer.mjs +152 -0
  237. package/skills/ew-impeccable/scripts/live/poll-lanes.mjs +14 -0
  238. package/skills/ew-impeccable/scripts/live/project-ignores.mjs +139 -0
  239. package/skills/ew-impeccable/scripts/live/roots.mjs +508 -0
  240. package/skills/ew-impeccable/scripts/live/session-store.mjs +563 -0
  241. package/skills/ew-impeccable/scripts/live/source-lock.mjs +105 -0
  242. package/skills/ew-impeccable/scripts/live/source-search.mjs +105 -0
  243. package/skills/ew-impeccable/scripts/live/svelte-ast.mjs +969 -0
  244. package/skills/ew-impeccable/scripts/live/svelte-component.mjs +1366 -0
  245. package/skills/ew-impeccable/scripts/live/sveltekit-adapter.mjs +304 -0
  246. package/skills/ew-impeccable/scripts/live/tanstack-adapter.mjs +259 -0
  247. package/skills/ew-impeccable/scripts/live/ui-surfaces.mjs +75 -0
  248. package/skills/ew-impeccable/scripts/live/vocabulary.mjs +171 -0
  249. package/skills/ew-impeccable/scripts/live-accept.mjs +938 -0
  250. package/skills/ew-impeccable/scripts/live-browser-dom.js +167 -0
  251. package/skills/ew-impeccable/scripts/live-browser-ignores.js +242 -0
  252. package/skills/ew-impeccable/scripts/live-browser-session.js +144 -0
  253. package/skills/ew-impeccable/scripts/live-browser.js +12851 -0
  254. package/skills/ew-impeccable/scripts/live-commit-manual-edits.mjs +1200 -0
  255. package/skills/ew-impeccable/scripts/live-complete.mjs +107 -0
  256. package/skills/ew-impeccable/scripts/live-copy-edit-agent.mjs +800 -0
  257. package/skills/ew-impeccable/scripts/live-discard-manual-edits.mjs +51 -0
  258. package/skills/ew-impeccable/scripts/live-inject.mjs +463 -0
  259. package/skills/ew-impeccable/scripts/live-insert.mjs +292 -0
  260. package/skills/ew-impeccable/scripts/live-manual-edit-evidence.mjs +368 -0
  261. package/skills/ew-impeccable/scripts/live-poll.mjs +430 -0
  262. package/skills/ew-impeccable/scripts/live-resume.mjs +123 -0
  263. package/skills/ew-impeccable/scripts/live-server.mjs +1698 -0
  264. package/skills/ew-impeccable/scripts/live-status.mjs +71 -0
  265. package/skills/ew-impeccable/scripts/live-target.mjs +30 -0
  266. package/skills/ew-impeccable/scripts/live-wrap.mjs +927 -0
  267. package/skills/ew-impeccable/scripts/live.mjs +334 -0
  268. package/skills/ew-impeccable/scripts/modern-screenshot.umd.js +14 -0
  269. package/skills/ew-impeccable/scripts/palette.mjs +628 -0
  270. package/skills/ew-impeccable/scripts/pin.mjs +352 -0
  271. package/skills/ew-impeccable/scripts/serve-question.mjs +1783 -0
  272. package/skills/ew-impeccable/scripts/surface-brief.mjs +74 -0
  273. package/skills/ew-knowledge/SKILL.md +35 -0
  274. package/skills/ew-knowledge/references/closeout-protocol.md +68 -0
  275. package/skills/ew-knowledge/references/knowledge-route.md +73 -0
  276. package/skills/ew-knowledge/references/wiki-maintenance.md +27 -0
  277. package/skills/ew-odyssey/SKILL.md +106 -0
  278. package/skills/ew-odyssey/references/audit-artifacts.md +7 -0
  279. package/skills/ew-odyssey/references/odyssey-base.md +104 -0
  280. package/skills/ew-odyssey/references/odyssey-debug.md +264 -0
  281. package/skills/ew-odyssey/references/odyssey-defensive.md +351 -0
  282. package/skills/ew-odyssey/references/odyssey-improve.md +230 -0
  283. package/skills/ew-odyssey/references/odyssey-planex.md +294 -0
  284. package/skills/ew-odyssey/references/odyssey-review.md +233 -0
  285. package/skills/ew-odyssey/references/odyssey-security.md +231 -0
  286. package/skills/ew-odyssey/references/odyssey-ui.md +232 -0
  287. package/skills/ew-odyssey/references/prepare/odyssey-debug.md +102 -0
  288. package/skills/ew-odyssey/references/prepare/odyssey-defensive.md +117 -0
  289. package/skills/ew-odyssey/references/prepare/odyssey-improve.md +95 -0
  290. package/skills/ew-odyssey/references/prepare/odyssey-planex.md +105 -0
  291. package/skills/ew-odyssey/references/prepare/odyssey-review.md +105 -0
  292. package/skills/ew-odyssey/references/prepare/odyssey-security.md +91 -0
  293. package/skills/ew-odyssey/references/prepare/odyssey-ui.md +88 -0
  294. package/skills/ew-odyssey/references/runtime-adapters.md +31 -0
  295. package/skills/ew-orchestrate/SKILL.md +89 -0
  296. package/skills/ew-orchestrate/references/auto-policy.md +66 -0
  297. package/skills/ew-orchestrate/references/boundary-grill.md +51 -0
  298. package/skills/ew-orchestrate/references/companion-route.md +40 -0
  299. package/skills/ew-orchestrate/references/ew-orchestrate.md +44 -0
  300. package/skills/ew-orchestrate/references/goal.md +51 -0
  301. package/skills/ew-orchestrate/references/orchestrator-run-loop.md +33 -0
  302. package/skills/ew-orchestrate/references/planning.md +54 -0
  303. package/skills/ew-orchestrate/steps/ew-analyze/SKILL.md +70 -0
  304. package/skills/ew-orchestrate/steps/ew-analyze/references/issue-gaps-analyze.md +24 -0
  305. package/skills/ew-orchestrate/steps/ew-analyze/references/prepare.md +8 -0
  306. package/skills/ew-orchestrate/steps/ew-analyze/references/workflow.md +138 -0
  307. package/skills/ew-orchestrate/steps/ew-auto-test/SKILL.md +80 -0
  308. package/skills/ew-orchestrate/steps/ew-auto-test/references/prepare.md +23 -0
  309. package/skills/ew-orchestrate/steps/ew-auto-test/references/workflow.md +31 -0
  310. package/skills/ew-orchestrate/steps/ew-blueprint/SKILL.md +122 -0
  311. package/skills/ew-orchestrate/steps/ew-blueprint/references/prepare.md +21 -0
  312. package/skills/ew-orchestrate/steps/ew-blueprint/references/workflow.md +28 -0
  313. package/skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md +49 -0
  314. package/skills/ew-orchestrate/steps/ew-companion/SKILL.md +50 -0
  315. package/skills/ew-orchestrate/steps/ew-debug/SKILL.md +85 -0
  316. package/skills/ew-orchestrate/steps/ew-debug/references/prepare.md +27 -0
  317. package/skills/ew-orchestrate/steps/ew-debug/references/workflow.md +31 -0
  318. package/skills/ew-orchestrate/steps/ew-execute/SKILL.md +74 -0
  319. package/skills/ew-orchestrate/steps/ew-execute/references/prepare.md +27 -0
  320. package/skills/ew-orchestrate/steps/ew-execute/references/workflow.md +87 -0
  321. package/skills/ew-orchestrate/steps/ew-grill/SKILL.md +62 -0
  322. package/skills/ew-orchestrate/steps/ew-grill/references/prepare.md +26 -0
  323. package/skills/ew-orchestrate/steps/ew-grill/references/workflow.md +31 -0
  324. package/skills/ew-orchestrate/steps/ew-init/SKILL.md +56 -0
  325. package/skills/ew-orchestrate/steps/ew-init/references/prepare.md +25 -0
  326. package/skills/ew-orchestrate/steps/ew-init/references/workflow.md +28 -0
  327. package/skills/ew-orchestrate/steps/ew-plan/SKILL.md +131 -0
  328. package/skills/ew-orchestrate/steps/ew-plan/references/prepare.md +8 -0
  329. package/skills/ew-orchestrate/steps/ew-plan/references/tdd.md +53 -0
  330. package/skills/ew-orchestrate/steps/ew-plan/references/workflow.md +100 -0
  331. package/skills/ew-orchestrate/steps/ew-retrospective/SKILL.md +68 -0
  332. package/skills/ew-orchestrate/steps/ew-retrospective/references/prepare.md +18 -0
  333. package/skills/ew-orchestrate/steps/ew-retrospective/references/workflow.md +34 -0
  334. package/skills/ew-orchestrate/steps/ew-review/SKILL.md +45 -0
  335. package/skills/ew-orchestrate/steps/ew-review/references/prepare.md +17 -0
  336. package/skills/ew-orchestrate/steps/ew-review/references/workflow.md +116 -0
  337. package/skills/ew-orchestrate/steps/ew-roadmap/SKILL.md +62 -0
  338. package/skills/ew-orchestrate/steps/ew-roadmap/references/prepare.md +27 -0
  339. package/skills/ew-orchestrate/steps/ew-roadmap/references/workflow.md +28 -0
  340. package/skills/ew-orchestrate/steps/ew-test/SKILL.md +99 -0
  341. package/skills/ew-orchestrate/steps/ew-test/references/prepare.md +23 -0
  342. package/skills/ew-orchestrate/steps/ew-test/references/workflow.md +23 -0
  343. package/skills/ew-orchestrate/steps/ew-verify/SKILL.md +73 -0
  344. package/skills/ew-orchestrate/steps/ew-verify/references/prepare.md +21 -0
  345. package/skills/ew-orchestrate/steps/ew-verify/references/workflow.md +29 -0
  346. package/skills/ew-skill-design/SKILL.md +30 -0
  347. package/skills/ew-skill-design/references/package-contract.md +40 -0
  348. package/skills/ew-skill-design/references/validation.md +21 -0
  349. package/skills/team-swarm/SKILL.md +68 -0
  350. package/skills/team-swarm/references/mcp-coordination.md +14 -0
  351. package/skills/team-swarm/roles/analyst/role.md +181 -0
  352. package/skills/team-swarm/roles/ant/role.md +149 -0
  353. package/skills/team-swarm/roles/coordinator/commands/converge.md +112 -0
  354. package/skills/team-swarm/roles/coordinator/commands/init-swarm.md +136 -0
  355. package/skills/team-swarm/roles/coordinator/commands/iterate.md +171 -0
  356. package/skills/team-swarm/roles/coordinator/role.md +170 -0
  357. package/skills/team-swarm/roles/scorer/role.md +150 -0
  358. package/skills/team-swarm/scripts/aco.py +646 -0
  359. package/skills/team-swarm/scripts/pheromone.py +144 -0
  360. package/skills/team-swarm/scripts/scoring.py +111 -0
  361. package/skills/team-swarm/scripts/test_aco.py +606 -0
  362. package/skills/team-swarm/specs/ant-output-schema.md +127 -0
  363. package/skills/team-swarm/specs/convergence-criteria.md +108 -0
  364. package/skills/team-swarm/specs/pheromone-schema.md +125 -0
  365. package/skills/team-swarm/specs/swarm-config-template.json +71 -0
  366. package/skills/team-swarm/specs/swarm-protocol.md +119 -0
  367. package/skills/workflow-evolve/SKILL.md +64 -0
  368. package/skills/workflow-evolve/references/agy-gate.md +27 -0
  369. package/skills/workflow-evolve/references/auto-loop.md +23 -0
  370. package/skills/workflow-evolve/references/history-review.md +15 -0
  371. package/skills/workflow-evolve/scripts/codex-memory-replay.mjs +86 -0
  372. package/skills/workflow-evolve/scripts/codex-replay.mjs +1 -0
  373. package/skills/workflow-evolve/scripts/evolve-loop.mjs +260 -0
  374. package/skills/workflow-evolve/scripts/memory-codex-mcp.mjs +124 -0
  375. package/workflows/index.json +33 -0
@@ -0,0 +1,2493 @@
1
+ /**
2
+ * Shared library for the Impeccable design hook.
3
+ *
4
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
5
+ * config parsing, finding filtering, dedup, render, and cache logic without
6
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
7
+ *
8
+ * Public surface (everything exported is part of the contract):
9
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
10
+ * truthy(value)
11
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
12
+ * resolveProjectPlatform(cwd) / isNativePlatform(platform)
13
+ * normalizeIgnoreValue(value)
14
+ * readCache(cwd) / persistCache(cwd, cache) / resolveCacheCwd(primaryFile, sessionCwd)
15
+ * bumpEditCount(cache, sessionId, filePath) -> number
16
+ * touchFile(cache, sessionId, filePath)
17
+ * suppressionNotice(filePath)
18
+ * filterFindings(findings, content, ext, config)
19
+ * ADVISORY_RULES / isAdvisoryFinding(finding)
20
+ * IMMEDIATE_TIER_RULES / splitFindingsByTier(findings) / perEditTieringActive(config, harness)
21
+ * matchConfiguredExtension(filePath, extensions)
22
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
23
+ * renderTemplate(findings, filePath, config, opts)
24
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
25
+ * appendDesignSystemNote(text, scanOptions) / appendDesignSystemNoteOnce(text, scanOptions, cache, sessionId, config)
26
+ * designNoteReserve(scanOptions, cache, sessionId)
27
+ * footerModeForSession(cache, sessionId) / commitFooterShown(cache, sessionId, text)
28
+ * shouldEmitAckForFile(filePath, config?)
29
+ * writeAuditLog(env, entry)
30
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
31
+ * matchesAnyGlob(filePath, globs)
32
+ * normalizeScanTargets(primaryTargets, projectCwd)
33
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
34
+ * runStopHook(deps) -> { exitCode, stdout, audit, emission? }
35
+ *
36
+ * Design notes:
37
+ * - All errors are swallowed at the runHook seam. The detector throwing must
38
+ * never break a turn. See PRD §5 "Failure modes".
39
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
40
+ * more than 8 to keep file size predictable across long-lived projects.
41
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
42
+ * this file first (built skill layout) and falls back to the repo root's
43
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
44
+ */
45
+
46
+ import crypto from 'node:crypto';
47
+ import fs from 'node:fs';
48
+ import os from 'node:os';
49
+ import path from 'node:path';
50
+ import { pathToFileURL, fileURLToPath } from 'node:url';
51
+ import { extractPlatform, loadContext } from './context.mjs';
52
+ import { IMPECCABLE_COMMAND } from './lib/provider.mjs';
53
+ // `detector.extensions` (issue #316) is shared with Live's source search, which
54
+ // needs the same answer for `.heex` / `.blade.php` when it hunts for session
55
+ // markers. lib/template-extensions.mjs owns the shape; re-exported here because
56
+ // hook-lib has been the import site for matchConfiguredExtension since #347.
57
+ import {
58
+ matchConfiguredExtension,
59
+ mergeExtensions,
60
+ } from './lib/template-extensions.mjs';
61
+
62
+ export { matchConfiguredExtension };
63
+
64
+ const __filename = fileURLToPath(import.meta.url);
65
+ const __dirname = path.dirname(__filename);
66
+
67
+ export const ENVELOPE_PREFIX = '[impeccable@1]';
68
+
69
+ export const ALLOWED_EXTS = new Set([
70
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
71
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
72
+ ]);
73
+
74
+ export const ACK_EXTS = new Set([
75
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
76
+ '.css', '.scss', '.sass', '.less',
77
+ ]);
78
+
79
+ // Hard-skip regex for sensitive files. Cannot be turned off via config.
80
+ // Match tokenized secret/credential filenames, not UI names such as
81
+ // CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
82
+ export const SENSITIVE_PATH = new RegExp([
83
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
84
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
85
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
86
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
87
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
88
+ ].join('|'), 'i');
89
+
90
+ // Hard-skip regex for generated, lock, minified, and build-output paths.
91
+ // `generated` is matched as a whole path segment so authored names such as
92
+ // `generated-utils.ts` or `CodeGenerator.tsx` still get scanned.
93
+ export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\]generated[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
94
+
95
+ export const TRUTHY = /^(1|true|yes|on)$/i;
96
+
97
+ // ── Two-tier rule surfacing ──────────────────────────────────────────────
98
+ // The per-edit PostToolUse pass surfaces only this "immediate" tier: rules
99
+ // that are mechanical, unambiguous, and worth interrupting an edit for —
100
+ // broken output the user would see (broken images, overflow, clipped
101
+ // popovers, text on the viewport edge), objective contrast/legibility
102
+ // failures, single-property slop that is trivial to fix in place (gradient
103
+ // text, glow shadows), and design-system drift (which compounds with every
104
+ // further edit if left uncorrected). Everything else — copy-cadence rules,
105
+ // palette/typography taste, layout rhythm — is deferred to the Stop-event
106
+ // deep pass (`runStopHook`), which runs the FULL rule set over every file
107
+ // touched this session and surfaces the remainder once.
108
+ //
109
+ // Rationale (measured in the eval harness): the per-edit stream fires
110
+ // overwhelmingly on copy-level rules, and that steady nag stream makes
111
+ // models more conservative, while a single full pass at completion fixes
112
+ // contrast/padding/glow just as reliably. Restore the old full per-edit
113
+ // behavior with `.impeccable/config.json` → `hook: { "perEditRules": "all" }`.
114
+ export const IMMEDIATE_TIER_RULES = new Set([
115
+ // Broken output.
116
+ 'broken-image',
117
+ 'text-overflow',
118
+ 'clipped-overflow-container',
119
+ 'body-text-viewport-edge',
120
+ // Objective contrast / legibility failures.
121
+ 'low-contrast',
122
+ 'gray-on-color',
123
+ 'tiny-text',
124
+ // Single-property mechanical slop, trivial to fix at the edit site.
125
+ 'gradient-text',
126
+ 'dark-glow',
127
+ // Design-system drift compounds if not corrected at edit time.
128
+ 'design-system-font',
129
+ 'design-system-color',
130
+ 'design-system-radius',
131
+ 'design-system-font-size',
132
+ ]);
133
+
134
+ // ── Advisory rules ────────────────────────────────────────────────────────
135
+ // Advisory rules are opt-in noise: the CLI reports them in a separate section
136
+ // and they never count as failures. The design hook skips them entirely by
137
+ // default — in both the per-edit PostToolUse pass and the Stop deep pass — so
138
+ // the agent is never nagged about a taste call a human might make on purpose.
139
+ // A project opts back in with `.impeccable/config.json`:
140
+ // { "detector": { "advisoryRules": "include" } }
141
+ // This legacy id fallback keeps older detector findings recognizable when they
142
+ // carry neither the current runtime flag nor the canonical advisory severity.
143
+ // Current findings are classified by their serialized metadata below.
144
+ export const ADVISORY_RULES = new Set([
145
+ 'em-dash-overuse',
146
+ ]);
147
+
148
+ export function isAdvisoryFinding(finding) {
149
+ const id = finding && normalizeIgnoreRule(finding.antipattern);
150
+ return Boolean(id && (
151
+ ADVISORY_RULES.has(id)
152
+ || finding.advisory === true
153
+ || finding.severity === 'advisory'
154
+ ));
155
+ }
156
+
157
+ export const DEFAULT_CONFIG = Object.freeze({
158
+ enabled: true,
159
+ quiet: false,
160
+ auditLog: null,
161
+ designSystem: { enabled: true },
162
+ ignoreRules: [],
163
+ ignoreFiles: [],
164
+ ignoreValues: [],
165
+ extensions: [],
166
+ perEditRules: 'immediate',
167
+ // Advisory rules are skipped unless a project sets detector.advisoryRules to
168
+ // "include". See ADVISORY_RULES above.
169
+ advisoryRules: 'exclude',
170
+ // maxFileBytes: not every generated artifact lives under a path we can
171
+ // recognize. Committed browser bundles and vendored detector copies sit
172
+ // next to source and run 200KB+, while genuinely authored stylesheets in
173
+ // this codebase top out under 90KB. A single file past the ceiling is a
174
+ // bundle, and findings against a bundle are never actionable.
175
+ limits: { maxFindings: 5, maxChars: 8000, maxFileBytes: 131072 },
176
+ });
177
+
178
+ export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
179
+ '.impeccable/hook.cache.json',
180
+ '.impeccable/hook.pending.json',
181
+ '.impeccable/config.local.json',
182
+ ]);
183
+
184
+ const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
185
+ const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
186
+ const CACHE_MAX_SESSIONS = 8;
187
+ export const EDIT_COUNT_THRESHOLD = 6;
188
+
189
+ export function truthy(value) {
190
+ return typeof value === 'string' && TRUTHY.test(value);
191
+ }
192
+
193
+ function depthIsSet(value) {
194
+ if (value === undefined || value === null) return false;
195
+ const text = String(value).trim();
196
+ if (!text) return false;
197
+ if (TRUTHY.test(text)) return true;
198
+ return /^\d+$/.test(text) && Number(text) > 0;
199
+ }
200
+
201
+ function safeReadJson(filePath) {
202
+ try {
203
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ export function getConfigPath(cwd) {
210
+ return path.join(cwd, '.impeccable', 'config.json');
211
+ }
212
+
213
+ export function getLocalConfigPath(cwd) {
214
+ return path.join(cwd, '.impeccable', 'config.local.json');
215
+ }
216
+
217
+ // Where mutable hook state (cache + pending) lives. Defaults to the
218
+ // project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
219
+ // relocates to a per-project subdirectory of that root instead, keyed by a
220
+ // slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
221
+ // `~/.claude/projects/` convention), so project roots stay free of tool
222
+ // artifacts (issue #422). User-authored config (config.json,
223
+ // config.local.json, design.json) deliberately stays project-local — only
224
+ // disposable state relocates.
225
+ // Read from process.env (not runHook's injected env): the cache root is a
226
+ // machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
227
+ // switch. Trim guards against stray whitespace in env files; `~/` (or the
228
+ // Windows `~\` spelling) expands via os.homedir(), and when no home dir can
229
+ // be determined the expansion is rejected — state falls back to the
230
+ // project-local default rather than anchoring under the hook process's cwd.
231
+ // Resolving both sides makes the slug deterministic when callers hand in a
232
+ // trailing separator or unnormalized cwd. The slug is the readable
233
+ // separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
234
+ // readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
235
+ // to `-x-my-app` and share state), so the digest disambiguates while keeping
236
+ // the dir name human-scannable.
237
+ function hookStateDir(cwd) {
238
+ const raw = process.env.IMPECCABLE_CACHE_ROOT;
239
+ let root = typeof raw === 'string' ? raw.trim() : '';
240
+ if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
241
+ let home = '';
242
+ try { home = os.homedir() || ''; } catch { home = ''; }
243
+ root = home ? path.join(home, root.slice(2)) : '';
244
+ }
245
+ if (root) {
246
+ const resolved = path.resolve(String(cwd));
247
+ const slug = resolved.replace(/[:\\/.]/g, '-');
248
+ const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
249
+ return path.join(path.resolve(root), `${slug}-${digest}`);
250
+ }
251
+ return path.join(cwd, '.impeccable');
252
+ }
253
+
254
+ export function getCachePath(cwd) {
255
+ return path.join(hookStateDir(cwd), 'hook.cache.json');
256
+ }
257
+
258
+ export function getPendingPath(cwd) {
259
+ return path.join(hookStateDir(cwd), 'hook.pending.json');
260
+ }
261
+
262
+ export function resolveProjectCwd(event, fallback = process.cwd()) {
263
+ return event?.cwd
264
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
265
+ || envProjectDir(fallback)
266
+ || fallback;
267
+ }
268
+
269
+ function looksLikeProjectRoot(dir) {
270
+ return ['.git', 'package.json', '.impeccable'].some((marker) => {
271
+ try { return fs.existsSync(path.join(dir, marker)); } catch { return false; }
272
+ });
273
+ }
274
+
275
+ // Where `.impeccable/` (cache + config) lives for this event. Normally the
276
+ // session cwd, untouched. But when the agent was launched from an umbrella
277
+ // directory that is not itself a project (no .git, package.json, or
278
+ // .impeccable), key to the edited file's nearest project root instead, so a
279
+ // multi-project launch dir doesn't accumulate a shared cross-project cache
280
+ // (issue #305). Climbing stops at the home dir, falling back to the session
281
+ // cwd when no marker is found.
282
+ export function resolveCacheCwd(primaryFile, sessionCwd) {
283
+ const base = path.resolve(sessionCwd || process.cwd());
284
+ if (!primaryFile || typeof primaryFile !== 'string' || hasPathTraversal(primaryFile)) return base;
285
+ if (looksLikeProjectRoot(base)) return base;
286
+ let dir;
287
+ try {
288
+ dir = path.dirname(path.resolve(primaryFile));
289
+ } catch {
290
+ return base;
291
+ }
292
+ const home = path.resolve(os.homedir());
293
+ while (true) {
294
+ if (dir === home) return base;
295
+ if (looksLikeProjectRoot(dir)) return dir;
296
+ const parent = path.dirname(dir);
297
+ if (parent === dir) return base;
298
+ dir = parent;
299
+ }
300
+ }
301
+
302
+ // The detector's rules are web rules (HTML/CSS shapes), but a React Native or
303
+ // Flutter project is made of the exact extensions the hook watches (.tsx, .ts,
304
+ // .js), so without this gate every native screen edit would draw web-shaped
305
+ // findings that contradict the native platform references. PRODUCT.md's
306
+ // `## Platform` field decides: `ios` / `android` / `adaptive` projects skip
307
+ // the scan entirely. Resolution goes through loadContext so the hook reads the
308
+ // same PRODUCT.md the skill does (alternate context dirs, monorepo fallback).
309
+ export function resolveProjectPlatform(cwd) {
310
+ try {
311
+ const ctx = loadContext(cwd);
312
+ return extractPlatform(ctx && ctx.product);
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ export function isNativePlatform(platform) {
319
+ return platform === 'ios' || platform === 'android' || platform === 'adaptive';
320
+ }
321
+
322
+ export function readConfig(cwd) {
323
+ const config = cloneDefaultConfig();
324
+ // Hook runtime settings live under `hook`; detector filters live under
325
+ // `detector`. Back-compat: older configs stored detector filters in `hook`,
326
+ // so read those first and let canonical `detector` settings win.
327
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
328
+ const raw = safeReadJson(filePath);
329
+ applyConfigSource(config, hookSection(raw));
330
+ applyDetectorConfigSource(config, detectorSection(raw));
331
+ }
332
+ return config;
333
+ }
334
+
335
+ // The hook settings subtree of a unified config.json / config.local.json.
336
+ function hookSection(raw) {
337
+ if (!raw || typeof raw !== 'object') return null;
338
+ return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
339
+ }
340
+
341
+ function detectorSection(raw) {
342
+ if (!raw || typeof raw !== 'object') return null;
343
+ return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
344
+ }
345
+
346
+ function numberOr(value, fallback) {
347
+ return Number.isFinite(value) && value > 0 ? value : fallback;
348
+ }
349
+
350
+ function cloneDefaultConfig() {
351
+ return {
352
+ ...DEFAULT_CONFIG,
353
+ ignoreRules: [],
354
+ ignoreFiles: [],
355
+ ignoreValues: [],
356
+ extensions: [],
357
+ designSystem: { ...DEFAULT_CONFIG.designSystem },
358
+ limits: { ...DEFAULT_CONFIG.limits },
359
+ };
360
+ }
361
+
362
+ function applyDetectorConfigSource(config, raw) {
363
+ if (!raw || typeof raw !== 'object') return config;
364
+ // `detector.advisoryRules: "include"` opts the hook into advisory rules
365
+ // (em-dash overuse, etc.). Any other value keeps the default "exclude".
366
+ if (raw.advisoryRules === 'include' || raw.advisoryRules === 'exclude') {
367
+ config.advisoryRules = raw.advisoryRules;
368
+ }
369
+ if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
370
+ config.designSystem = {
371
+ ...config.designSystem,
372
+ enabled: raw.designSystem.enabled === false ? false : true,
373
+ };
374
+ }
375
+ if (Array.isArray(raw.ignoreRules)) {
376
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
377
+ }
378
+ if (Array.isArray(raw.ignoreFiles)) {
379
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
380
+ }
381
+ if (Array.isArray(raw.ignoreValues)) {
382
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
383
+ }
384
+ if (Array.isArray(raw.extensions)) {
385
+ config.extensions = mergeExtensions(config.extensions, raw.extensions);
386
+ }
387
+ return config;
388
+ }
389
+
390
+ function applyConfigSource(config, raw) {
391
+ if (!raw || typeof raw !== 'object') return config;
392
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
393
+ config.enabled = raw.enabled === false ? false : true;
394
+ }
395
+ if (Object.prototype.hasOwnProperty.call(raw, 'quiet')) {
396
+ config.quiet = raw.quiet === true;
397
+ }
398
+ if (raw.perEditRules === 'all' || raw.perEditRules === 'immediate') {
399
+ config.perEditRules = raw.perEditRules;
400
+ }
401
+ if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
402
+ config.auditLog = raw.auditLog.trim();
403
+ }
404
+ applyDetectorConfigSource(config, raw);
405
+ if (raw.limits && typeof raw.limits === 'object') {
406
+ config.limits = {
407
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
408
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
409
+ maxFileBytes: numberOr(raw.limits.maxFileBytes, config.limits.maxFileBytes),
410
+ };
411
+ }
412
+ return config;
413
+ }
414
+
415
+ function uniqueStrings(values) {
416
+ return Array.from(new Set(values.map(String)));
417
+ }
418
+
419
+ export function normalizeIgnoreValue(value) {
420
+ return String(value || '')
421
+ .trim()
422
+ .replace(/^["']|["']$/g, '')
423
+ .replace(/\+/g, ' ')
424
+ .replace(/\s+/g, ' ')
425
+ .toLowerCase();
426
+ }
427
+
428
+ function normalizeIgnoreRule(rule) {
429
+ return String(rule || '').trim().toLowerCase();
430
+ }
431
+
432
+ function colorIgnoreKey(value) {
433
+ const color = parseIgnoreColor(value);
434
+ if (!color) return '';
435
+ return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
436
+ }
437
+
438
+ function parseIgnoreColor(value) {
439
+ const text = String(value || '').trim().toLowerCase();
440
+ if (!text) return null;
441
+
442
+ const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
443
+ if (hex) return parseHexIgnoreColor(hex[1]);
444
+
445
+ const rgb = text.match(/^rgba?\((.*)\)$/i);
446
+ if (rgb) {
447
+ const parts = splitColorArgs(rgb[1]);
448
+ if (parts.length < 3 || parts.length > 4) return null;
449
+ const r = parseRgbChannel(parts[0]);
450
+ const g = parseRgbChannel(parts[1]);
451
+ const b = parseRgbChannel(parts[2]);
452
+ const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
453
+ if ([r, g, b, a].some((v) => v === null)) return null;
454
+ return { r, g, b, a };
455
+ }
456
+
457
+ const hsl = text.match(/^hsla?\((.*)\)$/i);
458
+ if (hsl) {
459
+ const parts = splitColorArgs(hsl[1]);
460
+ if (parts.length < 3 || parts.length > 4) return null;
461
+ const h = parseHueChannel(parts[0]);
462
+ const s = parsePercentChannel(parts[1]);
463
+ const l = parsePercentChannel(parts[2]);
464
+ const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
465
+ if ([h, s, l, a].some((v) => v === null)) return null;
466
+ return hslToRgb(h, s, l, a);
467
+ }
468
+
469
+ return null;
470
+ }
471
+
472
+ function parseHexIgnoreColor(hex) {
473
+ if (hex.length === 3 || hex.length === 4) {
474
+ const r = parseInt(hex[0] + hex[0], 16);
475
+ const g = parseInt(hex[1] + hex[1], 16);
476
+ const b = parseInt(hex[2] + hex[2], 16);
477
+ const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
478
+ return { r, g, b, a };
479
+ }
480
+ const r = parseInt(hex.slice(0, 2), 16);
481
+ const g = parseInt(hex.slice(2, 4), 16);
482
+ const b = parseInt(hex.slice(4, 6), 16);
483
+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
484
+ return { r, g, b, a };
485
+ }
486
+
487
+ function splitColorArgs(body) {
488
+ const text = String(body || '').trim();
489
+ if (!text) return [];
490
+ if (text.includes(',')) {
491
+ const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
492
+ const last = parts[parts.length - 1];
493
+ if (last && last.includes('/')) {
494
+ const split = last.split('/').map((part) => part.trim()).filter(Boolean);
495
+ return [...parts.slice(0, -1), ...split];
496
+ }
497
+ return parts;
498
+ }
499
+ return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
500
+ }
501
+
502
+ function parseRgbChannel(raw) {
503
+ const text = String(raw || '').trim();
504
+ const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
505
+ if (!match) return null;
506
+ const value = Number.parseFloat(match[1]);
507
+ if (!Number.isFinite(value)) return null;
508
+ const scaled = match[2] ? value * 2.55 : value;
509
+ if (scaled < 0 || scaled > 255) return null;
510
+ return Math.round(scaled);
511
+ }
512
+
513
+ function parseAlphaChannel(raw) {
514
+ const text = String(raw || '').trim();
515
+ const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
516
+ if (!match) return null;
517
+ const value = Number.parseFloat(match[1]);
518
+ if (!Number.isFinite(value)) return null;
519
+ const alpha = match[2] ? value / 100 : value;
520
+ return alpha >= 0 && alpha <= 1 ? alpha : null;
521
+ }
522
+
523
+ function parseHueChannel(raw) {
524
+ const text = String(raw || '').trim();
525
+ const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
526
+ if (!match) return null;
527
+ const value = Number.parseFloat(match[1]);
528
+ if (!Number.isFinite(value)) return null;
529
+ const unit = match[2] || 'deg';
530
+ if (unit === 'turn') return value * 360;
531
+ if (unit === 'rad') return value * (180 / Math.PI);
532
+ if (unit === 'grad') return value * 0.9;
533
+ return value;
534
+ }
535
+
536
+ function parsePercentChannel(raw) {
537
+ const text = String(raw || '').trim();
538
+ const match = text.match(/^(-?\d*\.?\d+)%$/);
539
+ if (!match) return null;
540
+ const value = Number.parseFloat(match[1]);
541
+ if (!Number.isFinite(value)) return null;
542
+ return value >= 0 && value <= 100 ? value / 100 : null;
543
+ }
544
+
545
+ function hslToRgb(hue, saturation, lightness, alpha) {
546
+ const h = (((hue % 360) + 360) % 360) / 360;
547
+ if (saturation === 0) {
548
+ const gray = clampByte(Math.round(lightness * 255));
549
+ return { r: gray, g: gray, b: gray, a: alpha };
550
+ }
551
+ const q = lightness < 0.5
552
+ ? lightness * (1 + saturation)
553
+ : lightness + saturation - lightness * saturation;
554
+ const p = 2 * lightness - q;
555
+ const toRgb = (t) => {
556
+ let channel = t;
557
+ if (channel < 0) channel += 1;
558
+ if (channel > 1) channel -= 1;
559
+ if (channel < 1 / 6) return p + (q - p) * 6 * channel;
560
+ if (channel < 1 / 2) return q;
561
+ if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
562
+ return p;
563
+ };
564
+ return {
565
+ r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
566
+ g: clampByte(Math.round(toRgb(h) * 255)),
567
+ b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
568
+ a: alpha,
569
+ };
570
+ }
571
+
572
+ function clampByte(value) {
573
+ return Math.min(255, Math.max(0, value));
574
+ }
575
+
576
+ function ignoreValueMatches(rule, entryValue, findingValue) {
577
+ if (entryValue === findingValue) return true;
578
+ if (rule !== 'design-system-color') return false;
579
+ const entryColor = colorIgnoreKey(entryValue);
580
+ return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
581
+ }
582
+
583
+ export function normalizeIgnoreValueEntries(entries) {
584
+ if (!Array.isArray(entries)) return [];
585
+ const out = [];
586
+ for (const entry of entries) {
587
+ if (!entry || typeof entry !== 'object') continue;
588
+ const rule = normalizeIgnoreRule(entry.rule);
589
+ const value = normalizeIgnoreValue(entry.value);
590
+ if (!rule || !value) continue;
591
+ const normalized = { rule, value };
592
+ const files = uniqueStrings([
593
+ ...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
594
+ ...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
595
+ ]);
596
+ if (files.length > 0) normalized.files = files;
597
+ // Key order is rule, value, files, createdAt, reason and must stay that way:
598
+ // normalizing runs on every write, so emitting a different order than the one
599
+ // already on disk rewrites every untouched entry and churns the diff.
600
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
601
+ normalized.createdAt = entry.createdAt.trim();
602
+ }
603
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
604
+ normalized.reason = entry.reason.trim();
605
+ }
606
+ out.push(normalized);
607
+ }
608
+ return out;
609
+ }
610
+
611
+ function mergeIgnoreValues(existing, incoming) {
612
+ const map = new Map();
613
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
614
+ map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
615
+ }
616
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
617
+ map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
618
+ }
619
+ return Array.from(map.values());
620
+ }
621
+
622
+ function ignoreValueFilesKey(files) {
623
+ // Sort before joining: a scope is a set, so an entry already on disk in another
624
+ // order must compare equal rather than dedup as two distinct entries.
625
+ return Array.isArray(files) && files.length > 0 ? [...files].sort().join('\x1f') : '';
626
+ }
627
+
628
+ export function readCache(cwd) {
629
+ const raw = safeReadJson(getCachePath(cwd));
630
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
631
+ return { version: 1, sessions: {} };
632
+ }
633
+ return {
634
+ version: 1,
635
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
636
+ };
637
+ }
638
+
639
+ export function persistCache(cwd, cache) {
640
+ const sessions = cache.sessions || {};
641
+ const ids = Object.keys(sessions);
642
+ if (ids.length > CACHE_MAX_SESSIONS) {
643
+ // Garbage-collect oldest sessions by updatedAt.
644
+ const ordered = ids
645
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
646
+ .sort((a, b) => b[1] - a[1])
647
+ .slice(0, CACHE_MAX_SESSIONS);
648
+ const next = {};
649
+ for (const [id] of ordered) next[id] = sessions[id];
650
+ cache = { ...cache, sessions: next };
651
+ }
652
+ const target = getCachePath(cwd);
653
+ try {
654
+ ensureHookGitExcludes(cwd);
655
+ fs.mkdirSync(path.dirname(target), { recursive: true });
656
+ fs.writeFileSync(target, JSON.stringify(cache));
657
+ return true;
658
+ } catch {
659
+ return false;
660
+ }
661
+ }
662
+
663
+ export function ensureHookGitExcludes(cwd = process.cwd()) {
664
+ try {
665
+ const target = resolveHookGitExcludeTarget(cwd);
666
+ if (!target) {
667
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
668
+ }
669
+
670
+ const patterns = target.patternPrefix
671
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
672
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
673
+ const markerSuffix = target.patternPrefix || '.';
674
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
675
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
676
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
677
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
678
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
679
+
680
+ let updated;
681
+ if (markerRe.test(existing)) {
682
+ updated = existing.replace(markerRe, block);
683
+ } else {
684
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
685
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
686
+ }
687
+
688
+ if (updated !== existing) {
689
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
690
+ fs.writeFileSync(target.path, updated, 'utf-8');
691
+ }
692
+
693
+ return {
694
+ mode: 'git-info-exclude',
695
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
696
+ changed: updated !== existing,
697
+ patterns,
698
+ };
699
+ } catch {
700
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
701
+ }
702
+ }
703
+
704
+ function resolveHookGitExcludeTarget(cwd) {
705
+ const start = path.resolve(cwd);
706
+ let dir = start;
707
+ while (true) {
708
+ const dotGit = path.join(dir, '.git');
709
+ if (fs.existsSync(dotGit)) {
710
+ const gitDir = resolveGitDir(dotGit, dir);
711
+ if (!gitDir) return null;
712
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
713
+ return {
714
+ path: path.join(gitDir, 'info', 'exclude'),
715
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
716
+ };
717
+ }
718
+ const parent = path.dirname(dir);
719
+ if (parent === dir) return null;
720
+ dir = parent;
721
+ }
722
+ }
723
+
724
+ function resolveGitDir(dotGit, worktreeDir) {
725
+ const stat = fs.statSync(dotGit);
726
+ if (stat.isDirectory()) return dotGit;
727
+ if (!stat.isFile()) return null;
728
+
729
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
730
+ const match = body.match(/^gitdir:\s*(.+)$/i);
731
+ if (!match) return null;
732
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
733
+ }
734
+
735
+ function escapeRegExp(value) {
736
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
737
+ }
738
+
739
+ function ensureSession(cache, sessionId) {
740
+ if (!cache.sessions[sessionId]) {
741
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
742
+ }
743
+ return cache.sessions[sessionId];
744
+ }
745
+
746
+ function ensureFile(cache, sessionId, filePath) {
747
+ const session = ensureSession(cache, sessionId);
748
+ if (!session.files[filePath]) {
749
+ session.files[filePath] = { editCount: 0, findings: [] };
750
+ }
751
+ return session.files[filePath];
752
+ }
753
+
754
+ export function bumpEditCount(cache, sessionId, filePath) {
755
+ const fileEntry = ensureFile(cache, sessionId, filePath);
756
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
757
+ ensureSession(cache, sessionId).updatedAt = Date.now();
758
+ return fileEntry.editCount;
759
+ }
760
+
761
+ // Record that a file was scanned this session without bumping its edit count.
762
+ // The Stop deep pass reads the session's file list to know what to re-scan,
763
+ // so a file whose per-edit findings were all deferred still needs an entry.
764
+ export function touchFile(cache, sessionId, filePath) {
765
+ ensureFile(cache, sessionId, filePath);
766
+ ensureSession(cache, sessionId).updatedAt = Date.now();
767
+ }
768
+
769
+ export function suppressionNotice(filePath) {
770
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run ${IMPECCABLE_COMMAND} audit to revisit.`;
771
+ }
772
+
773
+ // Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
774
+ function globToRegex(glob) {
775
+ let re = '^';
776
+ let i = 0;
777
+ while (i < glob.length) {
778
+ const c = glob[i];
779
+ if (c === '*') {
780
+ if (glob[i + 1] === '*') {
781
+ re += '.*';
782
+ i += 2;
783
+ if (glob[i] === '/') i += 1;
784
+ } else {
785
+ re += '[^/]*';
786
+ i += 1;
787
+ }
788
+ } else if (c === '?') {
789
+ re += '[^/]';
790
+ i += 1;
791
+ } else if (c === '{') {
792
+ const end = glob.indexOf('}', i);
793
+ if (end === -1) { re += '\\{'; i += 1; continue; }
794
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
795
+ re += `(?:${parts.join('|')})`;
796
+ i = end + 1;
797
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
798
+ re += `\\${c}`;
799
+ i += 1;
800
+ } else {
801
+ re += c;
802
+ i += 1;
803
+ }
804
+ }
805
+ re += '$';
806
+ return new RegExp(re);
807
+ }
808
+
809
+ export function matchesAnyGlob(filePath, globs) {
810
+ if (!Array.isArray(globs) || globs.length === 0) return false;
811
+ const normalized = filePath.split(path.sep).join('/');
812
+ for (const glob of globs) {
813
+ try {
814
+ const re = globToRegex(String(glob));
815
+ if (re.test(normalized)) return true;
816
+ // Match against basename too for convenience: `*.generated.tsx` should
817
+ // catch `src/foo.generated.tsx` without requiring `**/`.
818
+ const base = normalized.split('/').pop();
819
+ if (re.test(base)) return true;
820
+ } catch {
821
+ /* malformed glob, skip */
822
+ }
823
+ }
824
+ return false;
825
+ }
826
+
827
+ export function filterFindings(findings, _content, _ext, config) {
828
+ if (!Array.isArray(findings) || findings.length === 0) return [];
829
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
830
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
831
+ // Advisory rules are skipped by default so the hook never nags about them;
832
+ // a project opts in with detector.advisoryRules: "include".
833
+ const includeAdvisory = (config?.advisoryRules || DEFAULT_CONFIG.advisoryRules) === 'include';
834
+ return findings.filter((f) => {
835
+ if (!f || typeof f !== 'object') return false;
836
+ if (!includeAdvisory && isAdvisoryFinding(f)) return false;
837
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
838
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
839
+ return true;
840
+ });
841
+ }
842
+
843
+ // Split filtered findings into the per-edit "immediate" tier and the tier
844
+ // deferred to the Stop deep pass. See IMMEDIATE_TIER_RULES for the tiering
845
+ // rationale.
846
+ export function splitFindingsByTier(findings) {
847
+ const immediate = [];
848
+ const deferred = [];
849
+ for (const f of Array.isArray(findings) ? findings : []) {
850
+ if (f && IMMEDIATE_TIER_RULES.has(normalizeIgnoreRule(f.antipattern))) {
851
+ immediate.push(f);
852
+ } else {
853
+ deferred.push(f);
854
+ }
855
+ }
856
+ return { immediate, deferred };
857
+ }
858
+
859
+ // Whether the per-edit pass for this harness should defer non-immediate
860
+ // findings to a Stop deep pass. Claude Code, Codex, and Grok Build dispatch
861
+ // our Stop hook; Cursor and GitHub Copilot have no deep pass wired, so
862
+ // deferring for them would silently drop the non-immediate rules entirely.
863
+ export function perEditTieringActive(config, harness) {
864
+ if (harness === 'cursor' || harness === 'github') return false;
865
+ return (config?.perEditRules || DEFAULT_CONFIG.perEditRules) !== 'all';
866
+ }
867
+
868
+ function isIgnoredFindingValue(finding, ignoreValues) {
869
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
870
+ const rule = normalizeIgnoreRule(finding.antipattern);
871
+ if (!rule) return false;
872
+ // File-scoped wildcards suppress rules with no extractable value, such as side-tab.
873
+ const value = extractFindingIgnoreValue(finding);
874
+ return ignoreValues.some((entry) => {
875
+ if (entry.rule !== rule) return false;
876
+ const wildcardValue = entry.value === '*';
877
+ if (!wildcardValue && (!value || !ignoreValueMatches(rule, entry.value, value))) return false;
878
+ if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
879
+ return findingMatchesScopedIgnoreFile(finding, entry.files);
880
+ });
881
+ }
882
+
883
+ function findingMatchesScopedIgnoreFile(finding, globs) {
884
+ const filePath = String(finding?.file || '').trim();
885
+ if (!filePath) return false;
886
+ if (matchesAnyGlob(filePath, globs)) return true;
887
+
888
+ const normalized = filePath.split(path.sep).join('/');
889
+ const parts = normalized.split('/').filter(Boolean);
890
+ for (let i = 0; i < parts.length; i++) {
891
+ const suffix = parts.slice(i).join('/');
892
+ if (matchesAnyGlob(suffix, globs)) return true;
893
+ }
894
+ return false;
895
+ }
896
+
897
+ export function extractFindingIgnoreValue(finding) {
898
+ if (!finding || typeof finding !== 'object') return '';
899
+ const rule = normalizeIgnoreRule(finding.antipattern);
900
+ const directValueRules = new Set([
901
+ 'overused-font',
902
+ 'bounce-easing',
903
+ 'design-system-font',
904
+ 'design-system-color',
905
+ 'design-system-radius',
906
+ 'design-system-font-size',
907
+ ]);
908
+ if (!directValueRules.has(rule)) return '';
909
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
910
+ }
911
+
912
+ function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
913
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
914
+ if (direct) return direct;
915
+
916
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
917
+ for (const text of candidates) {
918
+ if (rule === 'bounce-easing') {
919
+ const motion = extractMotionIgnoreValue(text);
920
+ if (motion) return motion;
921
+ continue;
922
+ }
923
+
924
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
925
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
926
+
927
+ const googleLabel = text.match(/Google Fonts:\s*([^()\n;]+)/i);
928
+ if (googleLabel) return cleanIgnoreValueDisplay(googleLabel[1]);
929
+
930
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
931
+ if (family) return cleanIgnoreValueDisplay(family[1]);
932
+
933
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
934
+ if (google) {
935
+ try {
936
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
937
+ } catch {
938
+ return cleanIgnoreValueDisplay(google[1]);
939
+ }
940
+ }
941
+ }
942
+
943
+ return '';
944
+ }
945
+
946
+ function extractMotionIgnoreValue(text) {
947
+ const tailwind = text.match(/\banimate-bounce\b/i);
948
+ if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
949
+
950
+ const bezier = text.match(/cubic-bezier\([^)]+\)/i);
951
+ if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
952
+
953
+ const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
954
+ if (animation) {
955
+ const token = animation[1]
956
+ .split(/[,\s]+/)
957
+ .find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
958
+ if (token) return cleanIgnoreValueDisplay(token);
959
+ }
960
+
961
+ return '';
962
+ }
963
+
964
+ function cleanIgnoreValueDisplay(value) {
965
+ return String(value || '')
966
+ .trim()
967
+ .replace(/^["']|["']$/g, '')
968
+ .replace(/\+/g, ' ')
969
+ .replace(/\s+/g, ' ');
970
+ }
971
+
972
+ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
973
+ if (!Array.isArray(findings) || findings.length === 0) return [];
974
+ const fileEntry = ensureFile(cache, sessionId, filePath);
975
+ const known = new Set(fileEntry.findings || []);
976
+ const fresh = [];
977
+ for (const f of findings) {
978
+ const key = findingCacheKey(f);
979
+ if (known.has(key)) continue;
980
+ known.add(key);
981
+ fresh.push(f);
982
+ }
983
+ return fresh;
984
+ }
985
+
986
+ // Sync the remembered set to the findings present in the scan just performed.
987
+ //
988
+ // This replaces rather than accumulates, and that is the whole point. An
989
+ // append-only set made the hook lie twice over: the pending ack counted
990
+ // history instead of the live scan, so it kept naming findings the agent had
991
+ // already fixed, and a finding that was fixed and later reintroduced was
992
+ // deduped against a stale memory and never re-reported. Forgetting what is no
993
+ // longer there is what lets the count shrink and a regression fire again.
994
+ //
995
+ // Callers must pass the complete current finding set, not just the fresh ones.
996
+ export function rememberFindings(cache, sessionId, filePath, findings) {
997
+ const fileEntry = ensureFile(cache, sessionId, filePath);
998
+ const keys = new Set((findings || []).map(f => findingCacheKey(f)));
999
+ fileEntry.findings = Array.from(keys);
1000
+ ensureSession(cache, sessionId).updatedAt = Date.now();
1001
+ }
1002
+
1003
+ function findingCacheKey(finding) {
1004
+ const line = finding?.line || 0;
1005
+ const value = extractFindingIgnoreValue(finding);
1006
+ if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
1007
+ if (line > 0) return `${finding.antipattern}:${line}`;
1008
+ if (value) return `${finding.antipattern}:0:${value}`;
1009
+ const snippet = String(finding?.snippet || '').trim().slice(0, 80);
1010
+ return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
1011
+ }
1012
+
1013
+ export function renderTemplate(findings, filePath, config, opts = {}) {
1014
+ if (!Array.isArray(findings) || findings.length === 0) return '';
1015
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
1016
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
1017
+ // reserveChars holds back room for a note the caller appends after render
1018
+ // (the DESIGN.md staleness note), so the final payload stays inside the
1019
+ // configured budget. It comes off after the 500-char floor, so at floor
1020
+ // configs the note keeps guaranteed delivery room; the clamp budget can
1021
+ // therefore sit below 500, which clampLastLine's footer-preserving
1022
+ // fallback handles (Bugbot on PR #508).
1023
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars) - (opts.reserveChars || 0);
1024
+
1025
+ const cwd = opts.cwd || process.cwd();
1026
+ const display = relativize(filePath, cwd);
1027
+ const total = findings.length;
1028
+ const shown = findings.slice(0, cap);
1029
+ const remaining = total - shown.length;
1030
+
1031
+ const header = `${ENVELOPE_PREFIX} Design hook findings requiring review in ${display} (${total} issue(s)):`;
1032
+ const seenRules = new Set();
1033
+ const lines = shown.map((f) => formatDedupedFindingLine(f, seenRules));
1034
+ const more = remaining > 0
1035
+ ? `... and ${remaining} more (see ${IMPECCABLE_COMMAND} audit).`
1036
+ : null;
1037
+ const footer = directiveFooter({ mode: opts.footer });
1038
+
1039
+ const blocks = [header, ...lines];
1040
+ if (more) blocks.push(more);
1041
+ blocks.push('');
1042
+ blocks.push(footer);
1043
+ let text = blocks.join('\n');
1044
+
1045
+ if (text.length > maxChars) {
1046
+ text = clampToBudget(header, lines, more, footer, maxChars);
1047
+ }
1048
+ return text;
1049
+ }
1050
+
1051
+ function renderGroupedTemplate(groups, config, opts = {}) {
1052
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
1053
+ if (realGroups.length === 0) return '';
1054
+ if (realGroups.length === 1) {
1055
+ const [group] = realGroups;
1056
+ return renderTemplate(group.findings, group.filePath, config, opts);
1057
+ }
1058
+
1059
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
1060
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
1061
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars) - (opts.reserveChars || 0);
1062
+ const cwd = opts.cwd || process.cwd();
1063
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
1064
+ const header = `${ENVELOPE_PREFIX} Design hook findings requiring review across ${realGroups.length} files (${total} issue(s)):`;
1065
+ const lines = [];
1066
+ let shownCount = 0;
1067
+ // One seen-set across all groups: a rule already described under one file
1068
+ // is not re-described under the next.
1069
+ const seenRules = new Set();
1070
+
1071
+ for (const group of realGroups) {
1072
+ const display = relativize(group.filePath, cwd);
1073
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
1074
+ const remainingCap = Math.max(0, cap - shownCount);
1075
+ const shown = group.findings.slice(0, remainingCap);
1076
+ for (const finding of shown) {
1077
+ lines.push(formatDedupedFindingLine(finding, seenRules));
1078
+ }
1079
+ shownCount += shown.length;
1080
+ const hidden = group.findings.length - shown.length;
1081
+ if (hidden > 0) {
1082
+ lines.push(`- ... ${hidden} more in ${display} (see ${IMPECCABLE_COMMAND} audit).`);
1083
+ }
1084
+ }
1085
+
1086
+ const footer = directiveFooter({ mode: opts.footer });
1087
+ let text = [header, ...lines, '', footer].join('\n');
1088
+ if (text.length > maxChars) {
1089
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
1090
+ }
1091
+ return text;
1092
+ }
1093
+
1094
+ // The clamp contract, shared by both budget functions: the footer is policy,
1095
+ // not detail, so it survives every clamp. Try the requested footer first;
1096
+ // when it cannot fit even after dropping finding lines, retry with the short
1097
+ // policy rather than sacrifice findings that fit beside it. A result that
1098
+ // dropped every finding line (a grouped render can fit a bare file header)
1099
+ // does not count as a fit: findings are why the emission exists.
1100
+ const isFindingLine = (line) => line.startsWith('- ');
1101
+
1102
+ function footerFallbacks(footer) {
1103
+ const short = directiveFooter({ mode: 'short' });
1104
+ return footer === short ? [footer] : [footer, short];
1105
+ }
1106
+
1107
+ function clampGroupedToBudget(header, lines, footer, maxChars) {
1108
+ const assemble = (linesArr, omitted, footerText) => [
1109
+ header,
1110
+ ...linesArr,
1111
+ ...(omitted ? [`... and more (see ${IMPECCABLE_COMMAND} audit).`] : []),
1112
+ '',
1113
+ footerText,
1114
+ ].join('\n');
1115
+
1116
+ for (const footerText of footerFallbacks(footer)) {
1117
+ let working = lines.slice();
1118
+ let omitted = false;
1119
+ let assembled = assemble(working, omitted, footerText);
1120
+ while (assembled.length > maxChars && working.length > 1) {
1121
+ working.pop();
1122
+ omitted = true;
1123
+ assembled = assemble(working, omitted, footerText);
1124
+ }
1125
+ if (assembled.length <= maxChars && working.some(isFindingLine)) return assembled;
1126
+ }
1127
+ return clampLastLine((linesArr, footerText) => assemble(linesArr, true, footerText),
1128
+ lines.find(isFindingLine) || lines[0], maxChars);
1129
+ }
1130
+
1131
+ function clampToBudget(header, lines, more, footer, maxChars) {
1132
+ const assemble = (linesArr, moreText, footerText) => {
1133
+ const blocks = [header, ...linesArr];
1134
+ if (moreText) blocks.push(moreText);
1135
+ blocks.push('');
1136
+ blocks.push(footerText);
1137
+ return blocks.join('\n');
1138
+ };
1139
+
1140
+ let lastMore = more;
1141
+ for (const footerText of footerFallbacks(footer)) {
1142
+ let working = lines.slice();
1143
+ let moreText = more;
1144
+ let assembled = assemble(working, moreText, footerText);
1145
+ while (assembled.length > maxChars && working.length > 1) {
1146
+ working.pop();
1147
+ moreText = `... and more (see ${IMPECCABLE_COMMAND} audit).`;
1148
+ assembled = assemble(working, moreText, footerText);
1149
+ }
1150
+ lastMore = moreText;
1151
+ if (assembled.length <= maxChars) return assembled;
1152
+ }
1153
+ return clampLastLine((linesArr, footerText) => assemble(linesArr, lastMore, footerText),
1154
+ lines.find(isFindingLine) || lines[0], maxChars);
1155
+ }
1156
+
1157
+ // Last resort with one finding line left: the short policy gets the budget
1158
+ // first, the line is clipped to what remains. The pre-fix tail-slice cut
1159
+ // whatever happened to be last, which was always the footer.
1160
+ function clampLastLine(build, line, maxChars) {
1161
+ const footerText = directiveFooter({ mode: 'short' });
1162
+ const bare = build([], footerText);
1163
+ // +1 for the newline the line itself brings when it joins the blocks.
1164
+ const room = maxChars - bare.length - 1;
1165
+ if (room >= 24) {
1166
+ const clipped = line.length > room ? `${line.slice(0, room - 1)}…` : line;
1167
+ return build([clipped], footerText);
1168
+ }
1169
+ // No room for even a clipped finding line: the note reservation can pull
1170
+ // the budget below the 500-char floor, and a deep file path can push the
1171
+ // header past what remains beside the short policy (Bugbot on PR #508).
1172
+ // Drop the line, and if the bare header + policy still overflow, clip the
1173
+ // head. Never tail-slice: the footer sits at the end, so a tail slice is
1174
+ // exactly the footer cut this renderer exists to prevent.
1175
+ if (bare.length <= maxChars) return bare;
1176
+ const head = bare.slice(0, Math.max(0, maxChars - footerText.length - 4));
1177
+ return `${head}…\n\n${footerText}`;
1178
+ }
1179
+
1180
+ // `compact` drops the registry description: within one emission the first
1181
+ // occurrence of a rule carries the full description and repeats keep only the
1182
+ // rule id, name, and their own ignore hint (values differ per line, so the
1183
+ // hint must survive the dedupe).
1184
+ function formatFindingLine(f, opts = {}) {
1185
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
1186
+ const desc = opts.compact ? '' : (f.description || '').trim();
1187
+ const name = (f.name || '').trim();
1188
+ // Description from the registry already ends in punctuation; join with a
1189
+ // single space. `name` may have a trailing period already, keep it clean.
1190
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
1191
+ const ignoreHint = formatFindingIgnoreHint(f);
1192
+ const ignoreSegment = ignoreHint ? ` If intentional: \`${ignoreHint}\`.` : '';
1193
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
1194
+ }
1195
+
1196
+ // Dedupe applied in shown-line order, so the first rendered occurrence of a
1197
+ // rule always carries the description. The budget clamps pop lines from the
1198
+ // end, which can never orphan a compact repeat before its described first
1199
+ // occurrence.
1200
+ function formatDedupedFindingLine(finding, seenRules) {
1201
+ const rule = normalizeIgnoreRule(finding?.antipattern);
1202
+ const compact = rule ? seenRules.has(rule) : false;
1203
+ if (rule) seenRules.add(rule);
1204
+ return formatFindingLine(finding, { compact });
1205
+ }
1206
+
1207
+ // The rule/value pair the footer's `hook-admin.mjs ignore-value` command
1208
+ // takes. Deliberately just the args: the executable prefix, the --reason
1209
+ // contract, and the disclosure rule live in the directive footer, stated once
1210
+ // instead of per line.
1211
+ function formatFindingIgnoreHint(finding) {
1212
+ if (!finding || typeof finding !== 'object') return '';
1213
+ const rule = normalizeIgnoreRule(finding.antipattern);
1214
+ if (!rule) return '';
1215
+ const normalizedValue = extractFindingIgnoreValue(finding);
1216
+ if (!normalizedValue) return '';
1217
+ const valueArg = quoteCommandArg(extractFindingIgnoreValueRaw(finding));
1218
+ return `ignore-value ${rule} ${valueArg}`;
1219
+ }
1220
+
1221
+ function quoteCommandArg(value) {
1222
+ const text = String(value || '').trim();
1223
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
1224
+ // The suggestion is meant to be run on this same machine, so quote for its
1225
+ // shell. POSIX /bin/sh still expands $(...), backticks, and ${} inside
1226
+ // double quotes, and these values come from scanned file content (a
1227
+ // font-family name) or a file path, so untrusted input must be
1228
+ // single-quoted (issue #476). Windows cmd.exe performs no such command
1229
+ // substitution, but it treats a single quote as a literal character rather
1230
+ // than a grouping delimiter, so a value or path containing spaces has to
1231
+ // stay double-quoted there (Greptile #533). Keep the pre-existing
1232
+ // double-quote escaping on Windows so that path's behavior is unchanged.
1233
+ if (process.platform === 'win32') {
1234
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
1235
+ }
1236
+ return `'${text.replace(/'/g, `'\\''`)}'`;
1237
+ }
1238
+
1239
+ function relativize(filePath, cwd) {
1240
+ try {
1241
+ const rel = path.relative(cwd, filePath);
1242
+ if (!rel || rel.startsWith('..')) return filePath;
1243
+ return rel.split(path.sep).join('/');
1244
+ } catch {
1245
+ return filePath;
1246
+ }
1247
+ }
1248
+
1249
+ // Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
1250
+ // `tool_input.file_path`. Claude Code may send both; parse the patch body
1251
+ // so we can scan the file(s) the tool actually touched.
1252
+ // https://developers.openai.com/codex/hooks#posttooluse
1253
+ const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
1254
+
1255
+ export function parseApplyPatchPaths(command, projectCwd) {
1256
+ if (!command || typeof command !== 'string') return [];
1257
+ const out = [];
1258
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
1259
+ let p = (m[1] || '').trim();
1260
+ if (!p) continue;
1261
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
1262
+ out.push(p);
1263
+ }
1264
+ return out;
1265
+ }
1266
+
1267
+ export function resolveTargetFiles(event, projectCwd) {
1268
+ const ti = event?.tool_input;
1269
+ const out = [];
1270
+ const add = (filePath) => {
1271
+ if (typeof filePath !== 'string' || !filePath) return;
1272
+ if (!out.includes(filePath)) out.push(filePath);
1273
+ };
1274
+
1275
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
1276
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
1277
+ }
1278
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
1279
+ add(ti.file_path);
1280
+ }
1281
+ // Cursor Write / StrReplace use `path`, not `file_path`.
1282
+ if (ti && typeof ti.path === 'string' && ti.path) {
1283
+ add(ti.path);
1284
+ }
1285
+ if (typeof event?.file_path === 'string' && event.file_path) {
1286
+ add(event.file_path);
1287
+ }
1288
+ return out;
1289
+ }
1290
+
1291
+ export function resolveHarness(env = {}, event = null) {
1292
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
1293
+ if (explicit === 'cursor') return 'cursor';
1294
+ if (explicit === 'github') return 'github';
1295
+ if (explicit === 'grok') return 'grok';
1296
+ if (explicit === 'claude') return 'claude';
1297
+ if (explicit === 'codex') return 'codex';
1298
+ // Grok Build sends camelCase `toolName`/`toolInput`/`hookEventName` and no
1299
+ // snake_case pair. GitHub Copilot sends camelCase `toolName`/`toolArgs`.
1300
+ // Check Grok first: the old GitHub heuristic (`toolName` and no
1301
+ // `tool_input`) also matches Grok, which is how live PostToolUse was
1302
+ // classified as Copilot and then skipped with no-file-path (#646).
1303
+ if (looksLikeGrokEnvelope(event)) return 'grok';
1304
+ if (event && typeof event === 'object'
1305
+ && (typeof event.toolName === 'string' || event.toolArgs !== undefined)
1306
+ && event.tool_name === undefined && event.tool_input === undefined) {
1307
+ return 'github';
1308
+ }
1309
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
1310
+ // Codex turn-scoped events carry `turn_id`. Claude Code does not. Detecting
1311
+ // it here means an already-installed Codex hook emits the Codex Stop
1312
+ // contract without rewriting the hook command to set IMPECCABLE_HOOK_HARNESS.
1313
+ // https://developers.openai.com/codex/hooks#stop
1314
+ if (typeof event?.turn_id === 'string' && event.turn_id) return 'codex';
1315
+ return 'claude';
1316
+ }
1317
+
1318
+ function looksLikeGrokEnvelope(event) {
1319
+ if (!event || typeof event !== 'object') return false;
1320
+ if (event.hook_event_name !== undefined
1321
+ || event.tool_name !== undefined
1322
+ || event.tool_input !== undefined) {
1323
+ return false;
1324
+ }
1325
+ if (event.toolArgs !== undefined) return false;
1326
+ if (typeof event.hookEventName === 'string') return true;
1327
+ return typeof event.toolName === 'string' && event.toolInput !== undefined;
1328
+ }
1329
+
1330
+ // Stop arrives as Claude's `hook_event_name: "Stop"` or Grok Build's
1331
+ // `hookEventName: "stop"`. hook.mjs routes on the raw stdin, before any
1332
+ // normalize, so both casings must match here.
1333
+ export function isStopEvent(event) {
1334
+ if (!event || typeof event !== 'object') return false;
1335
+ const name = event.hook_event_name || event.hookEventName;
1336
+ return typeof name === 'string' && name.toLowerCase() === 'stop';
1337
+ }
1338
+
1339
+ // GitHub Copilot's postToolUse payload is
1340
+ // { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
1341
+ // mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
1342
+ // `toolArgs` shape depends on the tool: the `edit`/`create`/`view` tools send a
1343
+ // JSON *string* (double-encoded) carrying the file under `path`, e.g.
1344
+ // "{\"path\":\"/abs/app.tsx\",\"old_str\":\"...\",\"new_str\":\"...\"}",
1345
+ // while `apply_patch` sends a raw OpenAI-format patch string (handled below in
1346
+ // normalizeGitHubEvent). The detector reads the file from disk after the tool
1347
+ // ran, so only the path (not the proposed content) is needed here.
1348
+ export function parseGitHubToolArgs(toolArgs) {
1349
+ if (toolArgs && typeof toolArgs === 'object' && !Array.isArray(toolArgs)) return toolArgs;
1350
+ if (typeof toolArgs === 'string' && toolArgs.trim()) {
1351
+ try {
1352
+ const parsed = JSON.parse(toolArgs);
1353
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
1354
+ } catch {
1355
+ return {};
1356
+ }
1357
+ }
1358
+ return {};
1359
+ }
1360
+
1361
+ // Copilot's `apply_patch` tool (used by interactive sessions and the cloud
1362
+ // agent) sends a raw OpenAI-format patch string in toolArgs, not JSON:
1363
+ // *** Begin Patch
1364
+ // *** Add File: /abs/app.css
1365
+ // +body { ... }
1366
+ // *** End Patch
1367
+ // The `view`/`edit`/`create` tools (seen in `copilot -p` runs) instead send a
1368
+ // JSON string with the path under `path`. Both must map onto the internal shape.
1369
+ const APPLY_PATCH_MARKER = /\*\*\* (?:Begin Patch|Add File:|Update File:|Delete File:)/;
1370
+
1371
+ function looksLikeApplyPatch(rawArgs) {
1372
+ if (typeof rawArgs !== 'string' || !APPLY_PATCH_MARKER.test(rawArgs)) return false;
1373
+ // Guard against an edit/create payload whose edited *content* happens to
1374
+ // contain patch markers: that payload is a JSON object string, whereas a real
1375
+ // apply_patch payload is a raw patch string that does not parse as JSON. Only
1376
+ // treat non-JSON-object strings as apply_patch so edit events still get their
1377
+ // `path` extracted.
1378
+ try {
1379
+ const parsed = JSON.parse(rawArgs);
1380
+ if (parsed && typeof parsed === 'object') return false;
1381
+ } catch { /* not JSON → genuine raw patch */ }
1382
+ return true;
1383
+ }
1384
+
1385
+ function applyPatchText(rawArgs) {
1386
+ if (typeof rawArgs === 'string') {
1387
+ if (APPLY_PATCH_MARKER.test(rawArgs)) return rawArgs;
1388
+ // Defensive: a future Copilot build might JSON-wrap the patch.
1389
+ const parsed = parseGitHubToolArgs(rawArgs);
1390
+ return parsed.patch || parsed.input || parsed.command || '';
1391
+ }
1392
+ if (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)) {
1393
+ return rawArgs.patch || rawArgs.input || rawArgs.command || '';
1394
+ }
1395
+ return '';
1396
+ }
1397
+
1398
+ function normalizeGitHubEvent(event, projectCwd) {
1399
+ const cwd = event.cwd || envProjectDir(projectCwd) || projectCwd;
1400
+ const sessionId = event.sessionId || event.session_id || 'unknown';
1401
+ const toolName = event.toolName || event.tool_name || null;
1402
+ const toolInput = event.tool_input && typeof event.tool_input === 'object' ? { ...event.tool_input } : {};
1403
+ const rawArgs = event.toolArgs;
1404
+
1405
+ let normalizedToolName = toolName;
1406
+ if (toolName === 'apply_patch' || looksLikeApplyPatch(rawArgs)) {
1407
+ // resolveTargetFiles() reads the touched paths from tool_input.command when
1408
+ // tool_name is 'apply_patch', so normalize the name even if a future build
1409
+ // sends the patch under a different tool label.
1410
+ const patch = applyPatchText(rawArgs);
1411
+ if (patch) {
1412
+ toolInput.command = patch;
1413
+ normalizedToolName = 'apply_patch';
1414
+ }
1415
+ } else {
1416
+ const args = parseGitHubToolArgs(rawArgs);
1417
+ const filePath = args.path || args.file_path || args.filePath || args.target_file;
1418
+ if (typeof filePath === 'string' && filePath) toolInput.file_path = filePath;
1419
+ }
1420
+
1421
+ return {
1422
+ ...event,
1423
+ cwd,
1424
+ session_id: sessionId,
1425
+ tool_name: normalizedToolName,
1426
+ tool_input: toolInput,
1427
+ };
1428
+ }
1429
+
1430
+ // Grok Build 1.0.5 (captured 2026-08-24) sends camelCase `toolName` /
1431
+ // `toolInput` / `sessionId` / `stopHookActive`, plus `cwd` alongside a
1432
+ // trailing-slashed `workspaceRoot` (every consumer path.resolve()s, so no
1433
+ // stripping here). Only the fields the hook reads are copied; the event
1434
+ // name stays camelCase because routing already happened on the raw stdin
1435
+ // (isStopEvent) and nothing downstream reads `hook_event_name`.
1436
+ function normalizeGrokEvent(event, projectCwd) {
1437
+ const cwd = event.cwd || event.workspaceRoot || envProjectDir(projectCwd) || projectCwd;
1438
+ const sessionId = event.sessionId || event.session_id || 'unknown';
1439
+ const rawInput = event.toolInput ?? event.tool_input;
1440
+ const toolInput = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
1441
+ ? { ...rawInput }
1442
+ : {};
1443
+ const out = {
1444
+ ...event,
1445
+ cwd,
1446
+ session_id: sessionId,
1447
+ tool_name: event.toolName || event.tool_name || null,
1448
+ tool_input: toolInput,
1449
+ };
1450
+ if (event.stopHookActive !== undefined && event.stop_hook_active === undefined) {
1451
+ out.stop_hook_active = event.stopHookActive;
1452
+ }
1453
+ return out;
1454
+ }
1455
+
1456
+ export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
1457
+ if (!event || typeof event !== 'object') return event;
1458
+ if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
1459
+ if (harness === 'grok') return normalizeGrokEvent(event, projectCwd);
1460
+ if (harness !== 'cursor') return event;
1461
+
1462
+ const cwd = event.cwd
1463
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
1464
+ || envProjectDir(projectCwd)
1465
+ || projectCwd;
1466
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
1467
+
1468
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
1469
+ const filePath = ti.file_path || ti.path || event.file_path;
1470
+ if (filePath) {
1471
+ return {
1472
+ ...event,
1473
+ cwd,
1474
+ session_id: sessionId,
1475
+ tool_input: { ...ti, file_path: filePath },
1476
+ };
1477
+ }
1478
+
1479
+ return { ...event, cwd, session_id: sessionId };
1480
+ }
1481
+
1482
+ function envProjectDir(fallback) {
1483
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
1484
+ return process.env.CURSOR_PROJECT_DIR;
1485
+ }
1486
+ return fallback;
1487
+ }
1488
+
1489
+ // UI components often keep slop in a sibling/co-located stylesheet while the
1490
+ // JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
1491
+ // patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
1492
+ const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
1493
+ const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
1494
+ const CO_SCAN_STYLE_NAMES = [
1495
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
1496
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
1497
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
1498
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
1499
+ ];
1500
+ const MAX_SCAN_TARGETS = 6;
1501
+
1502
+ const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
1503
+
1504
+ function hasPathTraversal(filePath) {
1505
+ return typeof filePath === 'string' && filePath.includes('..');
1506
+ }
1507
+
1508
+ function isInsideProject(filePath, projectCwd) {
1509
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
1510
+ try {
1511
+ const rel = path.relative(projectCwd, filePath);
1512
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
1513
+ } catch {
1514
+ return false;
1515
+ }
1516
+ }
1517
+
1518
+ // Resolve a path to its canonical (symlink-free) form. When the path does
1519
+ // not exist yet — the before-edit hook gates proposed Writes — canonicalize
1520
+ // the nearest existing ancestor and re-append the remainder, so a new file
1521
+ // under a symlinked root still compares equal to its canonical project.
1522
+ // Memoized: the hook runs as a fresh process per tool event, so the cache
1523
+ // amounts to once-per-event work — the scan loops re-check the same project
1524
+ // root for every target file. The cap only matters to long-lived importers
1525
+ // like the test runner.
1526
+ const canonicalPathCache = new Map();
1527
+ const CANONICAL_PATH_CACHE_MAX = 1024;
1528
+
1529
+ function canonicalPath(p) {
1530
+ const resolved = path.resolve(p);
1531
+ if (canonicalPathCache.has(resolved)) return canonicalPathCache.get(resolved);
1532
+ let canonical = resolved;
1533
+ let dir = resolved;
1534
+ const tail = [];
1535
+ while (true) {
1536
+ try {
1537
+ canonical = tail.length ? path.join(fs.realpathSync(dir), ...tail) : fs.realpathSync(dir);
1538
+ break;
1539
+ } catch { /* keep climbing */ }
1540
+ const parent = path.dirname(dir);
1541
+ if (parent === dir) break;
1542
+ tail.unshift(path.basename(dir));
1543
+ dir = parent;
1544
+ }
1545
+ if (canonicalPathCache.size >= CANONICAL_PATH_CACHE_MAX) canonicalPathCache.clear();
1546
+ canonicalPathCache.set(resolved, canonical);
1547
+ return canonical;
1548
+ }
1549
+
1550
+ // Containment gate shared by the before-edit hook and both scan passes. A
1551
+ // session routinely touches files that belong to no project or to a
1552
+ // different one — harness scratchpad dirs under the system temp root,
1553
+ // sibling checkouts, one-off throwaway HTML — and findings against those are
1554
+ // judged with THIS project's config and DESIGN.md palette, which is never
1555
+ // right. Skip them (audit reason: outside-project). Paths are canonicalized
1556
+ // first so a symlinked root (macOS /tmp -> /private/tmp) doesn't split the
1557
+ // comparison.
1558
+ export function isScanTargetInsideProject(filePath, projectCwd) {
1559
+ if (!filePath || !projectCwd) return false;
1560
+ return isInsideProject(canonicalPath(filePath), canonicalPath(projectCwd));
1561
+ }
1562
+
1563
+ export function parseStaticStyleImports(content, fromFile, projectCwd) {
1564
+ if (!content || typeof content !== 'string') return [];
1565
+ const dir = path.dirname(fromFile);
1566
+ const out = [];
1567
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
1568
+ let p = (m[1] || '').trim();
1569
+ if (!p) continue;
1570
+ if (p.startsWith('.')) p = path.resolve(dir, p);
1571
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
1572
+ if (!isInsideProject(p, projectCwd)) continue;
1573
+ out.push(p);
1574
+ }
1575
+ return out;
1576
+ }
1577
+
1578
+ export function coLocatedStylesheets(filePath) {
1579
+ const dir = path.dirname(filePath);
1580
+ const base = path.basename(filePath, path.extname(filePath));
1581
+ const candidates = new Set([
1582
+ path.join(dir, `${base}.css`),
1583
+ path.join(dir, `${base}.module.css`),
1584
+ path.join(dir, `${base}.scss`),
1585
+ path.join(dir, `${base}.module.scss`),
1586
+ path.join(dir, `${base}.sass`),
1587
+ path.join(dir, `${base}.module.sass`),
1588
+ path.join(dir, `${base}.less`),
1589
+ path.join(dir, `${base}.module.less`),
1590
+ ]);
1591
+ for (const name of CO_SCAN_STYLE_NAMES) {
1592
+ candidates.add(path.join(dir, name));
1593
+ }
1594
+ return [...candidates].filter((p) => fs.existsSync(p));
1595
+ }
1596
+
1597
+ export function normalizeScanTargets(primaryTargets, projectCwd) {
1598
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
1599
+ const ordered = [];
1600
+ const seen = new Set();
1601
+ const baseCwd = projectCwd || process.cwd();
1602
+ const normalizeTarget = (p) => {
1603
+ // Preserve literal `..` segments so downstream sensitive-path checks
1604
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
1605
+ if (hasPathTraversal(p)) return p;
1606
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
1607
+ };
1608
+ const add = (p) => {
1609
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
1610
+ const abs = normalizeTarget(p);
1611
+ if (seen.has(abs)) return;
1612
+ seen.add(abs);
1613
+ ordered.push(abs);
1614
+ return abs;
1615
+ };
1616
+
1617
+ for (const p of primaryTargets) add(p);
1618
+ return ordered;
1619
+ }
1620
+
1621
+ export function expandScanTargets(primaryTargets, projectCwd) {
1622
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
1623
+ if (ordered.length === 0) return [];
1624
+ const seen = new Set(ordered);
1625
+ const baseCwd = projectCwd || process.cwd();
1626
+ const add = (p) => {
1627
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
1628
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
1629
+ if (seen.has(abs)) return;
1630
+ seen.add(abs);
1631
+ ordered.push(abs);
1632
+ return abs;
1633
+ };
1634
+
1635
+ const normalizedPrimaries = [];
1636
+ for (const p of ordered) normalizedPrimaries.push(p);
1637
+
1638
+ for (const p of normalizedPrimaries) {
1639
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
1640
+ if (!isInsideProject(p, baseCwd)) continue;
1641
+ const ext = path.extname(p).toLowerCase();
1642
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
1643
+
1644
+ let content = '';
1645
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
1646
+
1647
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
1648
+ add(imp);
1649
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
1650
+ }
1651
+ for (const col of coLocatedStylesheets(p)) {
1652
+ add(col);
1653
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
1654
+ }
1655
+ }
1656
+
1657
+ return ordered;
1658
+ }
1659
+
1660
+ export function writeAuditLog(env, entry, cwd = process.cwd()) {
1661
+ // The event's project root (entry.cwd) when present, else the passed cwd. Both
1662
+ // config reads and relative log paths resolve against this, since the hook
1663
+ // process cwd can differ from the project being edited.
1664
+ const baseCwd = entry && typeof entry.cwd === 'string' && entry.cwd ? entry.cwd : cwd;
1665
+ // Env wins; otherwise fall back to the unified config's hook.auditLog path.
1666
+ let target = env?.IMPECCABLE_HOOK_LOG;
1667
+ if (!target || typeof target !== 'string') {
1668
+ try { target = readConfig(baseCwd).auditLog; } catch { target = null; }
1669
+ }
1670
+ if (!target || typeof target !== 'string') return false;
1671
+ try {
1672
+ let expanded;
1673
+ if (target.startsWith('~/')) {
1674
+ expanded = path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2));
1675
+ } else if (path.isAbsolute(target)) {
1676
+ expanded = target;
1677
+ } else {
1678
+ expanded = path.resolve(baseCwd, target);
1679
+ }
1680
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
1681
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
1682
+ fs.appendFileSync(expanded, line);
1683
+ return true;
1684
+ } catch {
1685
+ return false;
1686
+ }
1687
+ }
1688
+
1689
+ const DETECTOR_CANDIDATES = [
1690
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
1691
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
1692
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
1693
+ ];
1694
+
1695
+ let detectorCache = null;
1696
+ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
1697
+ if (detectorCache) return detectorCache;
1698
+ const found = candidates.find((c) => fs.existsSync(c));
1699
+ if (!found) return null;
1700
+ const mod = await import(pathToFileURL(found));
1701
+ detectorCache = {
1702
+ detectText: mod.detectText,
1703
+ detectHtml: mod.detectHtml,
1704
+ loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
1705
+ };
1706
+ return detectorCache;
1707
+ }
1708
+
1709
+ // For tests: allow injecting a detector implementation.
1710
+ export function setDetectorForTesting(impl) {
1711
+ detectorCache = impl;
1712
+ }
1713
+
1714
+ // ────────────────────────────────────────────────────────────────────────
1715
+ // Nudge/steer messages for the no-silent-fires policy.
1716
+ //
1717
+ // The hook is designed to be a conversational presence: every fire that
1718
+ // actually scans a file emits a developer-role message into the model's
1719
+ // next turn. Three states map to three templates:
1720
+ //
1721
+ // 1. **Fresh findings** → `renderTemplate` (existing, imperative).
1722
+ // 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
1723
+ // model was already told about in this
1724
+ // session but hasn't fixed yet).
1725
+ // 3. **Truly clean** → `renderCleanAck` (short positive nudge that
1726
+ // keeps the design discipline in context).
1727
+ //
1728
+ // All three are short (≤ ~40 tokens each) so the cumulative cost stays
1729
+ // bounded across a long active editing session. Users who explicitly want
1730
+ // silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
1731
+ // env before emitting #2 or #3.
1732
+ //
1733
+ // Why not stay silent on dedup-clean? Earlier versions did. The model
1734
+ // quickly forgets the prior reminder once tool output scrolls past it, so
1735
+ // re-nudging on the same file with a short "still pending" line keeps the
1736
+ // pressure on. The wording deliberately points back to "earlier this
1737
+ // session" so the model knows it's a re-mind, not a new finding.
1738
+ // ────────────────────────────────────────────────────────────────────────
1739
+
1740
+ const STEER_LINE = 'That does not mean the design is good: keep following the project design system and the impeccable skill guidance.';
1741
+
1742
+ export function renderCleanAck(filePath, opts = {}) {
1743
+ const cwd = opts.cwd || process.cwd();
1744
+ const display = relativize(filePath, cwd);
1745
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No deterministic design-quality issues found. ${STEER_LINE}`;
1746
+ }
1747
+
1748
+ export function renderPendingAck(filePath, knownFindings, opts = {}) {
1749
+ const cwd = opts.cwd || process.cwd();
1750
+ const display = relativize(filePath, cwd);
1751
+ const count = knownFindings.length;
1752
+ // `knownFindings` here are the cache strings like "side-tab:3".
1753
+ const sample = knownFindings.slice(0, 3).join(', ');
1754
+ const more = count > 3 ? `, +${count - 3} more` : '';
1755
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} finding(s) flagged earlier this session (${sample}${more}). Handle them before finalizing — the previous reminder still applies.`;
1756
+ }
1757
+
1758
+ export function shouldEmitAckForFile(filePath, config = null) {
1759
+ if (ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase())) return true;
1760
+ // Configured html-engine extensions are declared UI markup, so they get the
1761
+ // clean/pending acks; text-engine ones stay quiet like plain .ts/.js.
1762
+ const configured = matchConfiguredExtension(filePath, config?.extensions);
1763
+ return Boolean(configured && configured.engine === 'html');
1764
+ }
1765
+
1766
+ export function designSystemOptions(config, detector, projectCwd) {
1767
+ if (config?.designSystem?.enabled === false) return {};
1768
+ if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
1769
+ try {
1770
+ const designSystem = detector.loadDesignSystemForCwd(projectCwd);
1771
+ return designSystem ? { designSystem } : {};
1772
+ } catch {
1773
+ return {};
1774
+ }
1775
+ }
1776
+
1777
+ const DESIGN_STALE_NOTE = `${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run ${IMPECCABLE_COMMAND} document to refresh the design-system sidecar.`;
1778
+
1779
+ export function appendDesignSystemNote(text, scanOptions) {
1780
+ if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
1781
+ return `${text}\n\n${DESIGN_STALE_NOTE}`;
1782
+ }
1783
+
1784
+ // Session-scoped once-only gate for repeat-prone message parts. Returns true
1785
+ // the first time a flag is consumed in a session and false after, mirroring
1786
+ // the `cleanAcked` mechanic: the mtime skew (and the policy footer) do not
1787
+ // change between edits, so re-stating them on every emission spends context
1788
+ // to say nothing new. Callers must persist the cache for the flag to stick.
1789
+ function consumeSessionNoticeFlag(cache, sessionId, flag) {
1790
+ const session = ensureSession(cache, sessionId);
1791
+ if (session[flag]) return false;
1792
+ session[flag] = true;
1793
+ session.updatedAt = Date.now();
1794
+ return true;
1795
+ }
1796
+
1797
+ // Once-per-session variant of appendDesignSystemNote for the emission paths
1798
+ // that have cache access. The staleness note names standing project state,
1799
+ // not new information, so one mention per session is enough. The note is
1800
+ // appended after the renderer has clamped to the configured budget: render
1801
+ // paths reserve room for it via designNoteReserve, and the size check here
1802
+ // is the safety net for the ack paths, deferring (without consuming the
1803
+ // flag) to a later emission rather than busting maxChars.
1804
+ export function appendDesignSystemNoteOnce(text, scanOptions, cache, sessionId, config) {
1805
+ if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
1806
+ const maxChars = Math.max(500, config?.limits?.maxChars || DEFAULT_CONFIG.limits.maxChars);
1807
+ if (text.length + DESIGN_STALE_NOTE.length + 2 > maxChars) return text;
1808
+ if (!consumeSessionNoticeFlag(cache, sessionId, 'designNoteShown')) return text;
1809
+ return appendDesignSystemNote(text, scanOptions);
1810
+ }
1811
+
1812
+ // Render-time reservation for the note above: how many characters the
1813
+ // renderer must hold back so a pending staleness note still fits inside the
1814
+ // configured budget. Zero once the session has seen the note. Without the
1815
+ // reservation, a session whose every emission fills the budget would defer
1816
+ // the note forever.
1817
+ export function designNoteReserve(scanOptions, cache, sessionId) {
1818
+ if (!scanOptions?.designSystem?.mdNewerThanJson) return 0;
1819
+ if (ensureSession(cache, sessionId).designNoteShown) return 0;
1820
+ return DESIGN_STALE_NOTE.length + 2;
1821
+ }
1822
+
1823
+ // Full directive footer once per session, the short reminder after. Fresh
1824
+ // emissions and Cursor denials share the session flag (`footerShown`), so a
1825
+ // session pays the full policy exactly once however it first fires. The mode
1826
+ // is a peek: the clamp can downgrade a requested full footer under a tight
1827
+ // budget, so the flag commits only when the complete full policy actually
1828
+ // reached the output. Matching the whole footer text (not a sentinel) keeps
1829
+ // the flag honest against any truncation that spares the opening words.
1830
+ export function footerModeForSession(cache, sessionId) {
1831
+ return ensureSession(cache, sessionId).footerShown ? 'short' : 'full';
1832
+ }
1833
+
1834
+ export function commitFooterShown(cache, sessionId, text) {
1835
+ if (!text || !text.includes(directiveFooter())) return;
1836
+ const session = ensureSession(cache, sessionId);
1837
+ if (session.footerShown) return;
1838
+ session.footerShown = true;
1839
+ session.updatedAt = Date.now();
1840
+ }
1841
+
1842
+ const HOOK_ADMIN_COMMAND = `node ${quoteCommandArg(path.join(__dirname, 'hook-admin.mjs'))}`;
1843
+
1844
+ // The directive footer is the part of the hook output that steers model
1845
+ // behavior. Intentional moves, in order:
1846
+ // 1. **Imperative, not advisory.** "Triage each finding..." beats
1847
+ // "Consider revising...", which the model treats as a soft suggestion.
1848
+ // 2. **Positive triage branches.** Fix / suppress-and-disclose / ask. The
1849
+ // suppress branch names the calibration examples (demo, fixture,
1850
+ // documented bad design, user-confirmed choice) because the agent now
1851
+ // acts on its own confidence and needs the bar stated.
1852
+ // 3. **Executable ignore path.** The old footer named only the slash
1853
+ // command, which an agent reacting to hook output cannot run; the
1854
+ // hook-admin.mjs invocation is runnable as-is and keeps agents out of
1855
+ // hand-editing config.json.
1856
+ // 4. **Honest provenance.** The --reason is the audit trail; "user
1857
+ // confirmed" appears only when the user actually did.
1858
+ // 5. **Acknowledgement instruction.** Hook output is injected as
1859
+ // developer-role context, so the reply is where the user sees the
1860
+ // resolution, including any ignore the agent persisted.
1861
+ // 6. **Once per session.** The full policy emits on the session's first
1862
+ // fire; later emissions carry the one-line short form (mode 'short').
1863
+ function directiveFooter(opts = {}) {
1864
+ if (opts.mode === 'short') {
1865
+ // No command path here: the session's first emission already gave the
1866
+ // runnable hook-admin.mjs invocation, and restating ~70 chars of absolute
1867
+ // path on every repeat is the duplication this mode exists to cut.
1868
+ return 'Triage per the session policy: fix real problems; persist confident false-positive or sanctioned-exception ignores via `hook-admin.mjs ignore-value` and disclose them in your reply; unsure, ask in one line.';
1869
+ }
1870
+ return [
1871
+ 'Triage each finding, then state in your reply what you fixed, what you suppressed, and what you left standing:',
1872
+ '- Real design problem: fix it. Keep intentional design as designed.',
1873
+ `- Confident false positive or sanctioned exception (an intentional demo or fixture, documentation of bad design, literal or domain-appropriate motion, a choice the user confirmed): persist the narrowest ignore yourself and disclose it. Run \`${HOOK_ADMIN_COMMAND} ignore-value <rule> "<value>" --reason "<who decided: evidence>"\` with the pair shown on the finding line, or value "*" plus \`--file <path>\` when the line shows none. Write "user confirmed" in a reason only when the user did.`,
1874
+ '- Unsure: leave it as is and ask the user in one line.',
1875
+ `Self-serve ends at ignore-value: \`ignore-file\` and \`ignore-rule\` need the user's explicit approval, and never add an ignore to push a blocked write through. Full suppression ladder: ${IMPECCABLE_COMMAND} hooks.`,
1876
+ ].join('\n');
1877
+ }
1878
+
1879
+ /**
1880
+ * Run the hook with explicit dependencies. Returns a result object:
1881
+ * { exitCode, stdout, audit, reason? }
1882
+ *
1883
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
1884
+ */
1885
+ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
1886
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
1887
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
1888
+
1889
+ try {
1890
+ // Re-entrancy guard.
1891
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
1892
+ return result({ reentrant: true, durationMs: 0 });
1893
+ }
1894
+
1895
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
1896
+ return result({ skipped: 'env-disabled', durationMs: 0 });
1897
+ }
1898
+
1899
+ const started = Date.now();
1900
+
1901
+ let event;
1902
+ try {
1903
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
1904
+ } catch {
1905
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
1906
+ }
1907
+ if (!event || typeof event !== 'object') {
1908
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
1909
+ }
1910
+
1911
+ const harness = resolveHarness(env, event);
1912
+ event = normalizeHookEvent(event, cwd, harness);
1913
+ audit.harness = harness;
1914
+
1915
+ const sessionCwd = event.cwd || cwd;
1916
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, sessionCwd), sessionCwd);
1917
+ const projectCwd = resolveCacheCwd(primaryFiles[0], sessionCwd);
1918
+ audit.cwd = projectCwd;
1919
+ const primaryFileSet = new Set(primaryFiles);
1920
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
1921
+ audit.session = event.session_id || null;
1922
+ if (event.tool_name) audit.tool = event.tool_name;
1923
+
1924
+ if (targetFiles.length === 0) {
1925
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
1926
+ }
1927
+
1928
+ const config = readConfig(projectCwd);
1929
+ if (config.enabled === false) {
1930
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
1931
+ }
1932
+
1933
+ const platform = resolveProjectPlatform(projectCwd);
1934
+ if (isNativePlatform(platform)) {
1935
+ return result({ skipped: 'native-platform', platform, durationMs: Date.now() - started });
1936
+ }
1937
+
1938
+ const cache = readCache(projectCwd);
1939
+ const sessionId = event.session_id || 'unknown';
1940
+ const det = detector || await loadDetector();
1941
+ if (!det || typeof det.detectText !== 'function') {
1942
+ // Cache is not mutated yet at this point; nothing to persist.
1943
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
1944
+ }
1945
+ const scanOptions = designSystemOptions(config, det, projectCwd);
1946
+ const tiered = perEditTieringActive(config, harness);
1947
+
1948
+ let pendingWinner = null;
1949
+ let cleanWinner = null;
1950
+ const freshGroups = [];
1951
+ let suppressionWinner = null;
1952
+ let cleanAckDeduped = false;
1953
+ let skippedBytes = 0;
1954
+ const quietMode = truthy(env.IMPECCABLE_HOOK_QUIET) || config.quiet === true;
1955
+ let detectorThrewAny = false;
1956
+ let lastSkip = 'no-scannable-file';
1957
+ let suppressedHit = false;
1958
+ let cacheDirty = false;
1959
+ let deferredTotal = 0;
1960
+
1961
+ for (const filePath of targetFiles) {
1962
+ audit.file = filePath;
1963
+
1964
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
1965
+ lastSkip = 'sensitive';
1966
+ continue;
1967
+ }
1968
+ if (GENERATED_PATH.test(filePath)) {
1969
+ lastSkip = 'generated';
1970
+ continue;
1971
+ }
1972
+
1973
+ const ext = path.extname(filePath).toLowerCase();
1974
+ const configuredExt = matchConfiguredExtension(filePath, config.extensions);
1975
+ audit.ext = configuredExt ? configuredExt.ext : ext;
1976
+ if (!ALLOWED_EXTS.has(ext) && !configuredExt) {
1977
+ lastSkip = 'extension';
1978
+ continue;
1979
+ }
1980
+
1981
+ const relForMatch = relativize(filePath, projectCwd);
1982
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
1983
+ lastSkip = 'config-ignore-file';
1984
+ continue;
1985
+ }
1986
+ if (!fs.existsSync(filePath)) {
1987
+ lastSkip = 'file-missing';
1988
+ continue;
1989
+ }
1990
+ if (!isScanTargetInsideProject(filePath, projectCwd)) {
1991
+ lastSkip = 'outside-project';
1992
+ continue;
1993
+ }
1994
+
1995
+ const maxFileBytes = config.limits?.maxFileBytes ?? DEFAULT_CONFIG.limits.maxFileBytes;
1996
+ if (maxFileBytes > 0) {
1997
+ let size = 0;
1998
+ try { size = fs.statSync(filePath).size; } catch { size = 0; }
1999
+ if (size > maxFileBytes) {
2000
+ skippedBytes = size;
2001
+ lastSkip = 'too-large';
2002
+ continue;
2003
+ }
2004
+ }
2005
+
2006
+ if (primaryFileSet.has(filePath)) {
2007
+ const editCount = bumpEditCount(cache, sessionId, filePath);
2008
+ cacheDirty = true;
2009
+ audit.editCount = editCount;
2010
+
2011
+ if (editCount > EDIT_COUNT_THRESHOLD) {
2012
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
2013
+ if (wasJustCrossed && !suppressionWinner) {
2014
+ suppressionWinner = { filePath };
2015
+ }
2016
+ lastSkip = 'suppressed';
2017
+ suppressedHit = true;
2018
+ continue;
2019
+ }
2020
+ }
2021
+
2022
+ const content = fs.readFileSync(filePath, 'utf-8');
2023
+ let findings;
2024
+ let detectorThrew = false;
2025
+ const useHtmlEngine = configuredExt
2026
+ ? configuredExt.engine === 'html'
2027
+ : (ext === '.html' || ext === '.htm');
2028
+ if (useHtmlEngine && typeof det.detectHtml === 'function') {
2029
+ try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
2030
+ } else {
2031
+ try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
2032
+ }
2033
+
2034
+ const filtered = filterFindings(findings || [], content, ext, config);
2035
+ // Per-edit only surfaces the immediate tier; the rest waits for the
2036
+ // Stop deep pass. The file is still marked touched so the deep pass
2037
+ // knows to re-scan it.
2038
+ const { immediate, deferred } = tiered
2039
+ ? splitFindingsByTier(filtered)
2040
+ : { immediate: filtered, deferred: [] };
2041
+ if (deferred.length > 0) {
2042
+ touchFile(cache, sessionId, filePath);
2043
+ cacheDirty = true;
2044
+ deferredTotal += deferred.length;
2045
+ }
2046
+ const fresh = dedupeAgainstCache(immediate, cache, sessionId, filePath);
2047
+ audit.findings = (findings || []).length;
2048
+ audit.freshFindings = fresh.length;
2049
+ if (deferredTotal > 0) audit.deferred = deferredTotal;
2050
+
2051
+ // A detector failure tells us nothing about the file, so leave whatever
2052
+ // was remembered alone rather than recording an empty scan as truth.
2053
+ if (detectorThrew) {
2054
+ detectorThrewAny = true;
2055
+ continue;
2056
+ }
2057
+
2058
+ // Sync the cache to this scan before deciding what to emit, so fixed
2059
+ // findings stop being remembered and a reintroduced one reads as fresh.
2060
+ // Only the immediate tier is remembered: a deferred finding the per-edit
2061
+ // pass never reported must still read as fresh to the Stop deep pass.
2062
+ //
2063
+ // Grok ignores PostToolUse stdout, so Stop is the user-visible pass.
2064
+ // Remembering here would dedupe those findings out of Stop. Touch the
2065
+ // file so Stop has it, and leave the finding list empty.
2066
+ if (harness === 'grok') {
2067
+ touchFile(cache, sessionId, filePath);
2068
+ } else {
2069
+ rememberFindings(cache, sessionId, filePath, immediate);
2070
+ }
2071
+ cacheDirty = true;
2072
+
2073
+ if (fresh.length > 0) {
2074
+ freshGroups.push({ filePath, findings: fresh });
2075
+ continue;
2076
+ }
2077
+
2078
+ if (immediate.length > 0 && !pendingWinner) {
2079
+ // Count the live scan, not the session's history.
2080
+ pendingWinner = { filePath, known: immediate.map(f => findingCacheKey(f)) };
2081
+ } else if (immediate.length === 0 && !cleanWinner) {
2082
+ // The clean ack carries no finding, only the standing steer that a
2083
+ // silent hook is not a verdict on the design. Repeating it on every
2084
+ // clean edit spends context to say nothing, so it fires once per file
2085
+ // per session. The pending ack, which names real unresolved work, is
2086
+ // deliberately left to repeat.
2087
+ //
2088
+ // Quiet mode emits nothing, so it must not consume the ack and leave a
2089
+ // later non-quiet run in this session silent.
2090
+ if (quietMode || !shouldEmitAckForFile(filePath, config)) {
2091
+ cleanWinner = { filePath };
2092
+ } else if (ensureFile(cache, sessionId, filePath).cleanAcked) {
2093
+ // Spent for this file. Remember it for the audit trail, but keep
2094
+ // scanning: another target in this same event may still be owed an
2095
+ // ack, and dropping out here would lose it.
2096
+ cleanAckDeduped = true;
2097
+ } else {
2098
+ ensureFile(cache, sessionId, filePath).cleanAcked = true;
2099
+ cleanWinner = { filePath };
2100
+ cleanAckDeduped = false;
2101
+ }
2102
+ }
2103
+ }
2104
+
2105
+ // The session notice flags mutate the cache, so they must settle before
2106
+ // the persist that makes them stick across events.
2107
+ if (freshGroups.length > 0) {
2108
+ const firstGroup = freshGroups[0];
2109
+ const footerMode = footerModeForSession(cache, sessionId);
2110
+ const text = appendDesignSystemNoteOnce(
2111
+ renderGroupedTemplate(freshGroups, config, {
2112
+ cwd: projectCwd,
2113
+ footer: footerMode,
2114
+ reserveChars: designNoteReserve(scanOptions, cache, sessionId),
2115
+ }),
2116
+ scanOptions, cache, sessionId, config,
2117
+ );
2118
+ commitFooterShown(cache, sessionId, text);
2119
+ // Fresh findings always earn the cache write, including creating
2120
+ // `.impeccable/`: dedup, suppression, and the notice flags need it.
2121
+ persistCache(projectCwd, cache);
2122
+ const allFindings = freshGroups.flatMap((group) => group.findings);
2123
+ return {
2124
+ exitCode: 0,
2125
+ stdout: payload(text, 'PostToolUse', harness),
2126
+ emission: {
2127
+ kind: 'fresh',
2128
+ file: firstGroup.filePath,
2129
+ findings: firstGroup.findings,
2130
+ groups: freshGroups,
2131
+ },
2132
+ audit: {
2133
+ ...audit,
2134
+ file: firstGroup.filePath,
2135
+ emitted: true,
2136
+ freshFiles: freshGroups.length,
2137
+ freshFindings: allFindings.length,
2138
+ chars: text.length,
2139
+ durationMs: Date.now() - started,
2140
+ },
2141
+ };
2142
+ }
2143
+
2144
+ // Resolve the ack emission before the persist below: appendDesignSystem-
2145
+ // NoteOnce consumes a session flag, and the flag only sticks when the
2146
+ // write happens after it. Quiet mode emits nothing, so it consumes
2147
+ // nothing. The clean arm mirrors the branch order further down: pending
2148
+ // outranks suppression, suppression outranks clean.
2149
+ let ack = null;
2150
+ if (!quietMode && pendingWinner && shouldEmitAckForFile(pendingWinner.filePath, config)) {
2151
+ ack = {
2152
+ kind: 'pending',
2153
+ text: appendDesignSystemNoteOnce(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions, cache, sessionId, config),
2154
+ };
2155
+ } else if (!quietMode && !suppressionWinner && cleanWinner && !cleanAckDeduped && shouldEmitAckForFile(cleanWinner.filePath, config)) {
2156
+ ack = {
2157
+ kind: 'clean',
2158
+ text: appendDesignSystemNoteOnce(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions, cache, sessionId, config),
2159
+ };
2160
+ }
2161
+
2162
+ // Persist only when the write is earned: deferred findings need the
2163
+ // touched-file list for the Stop deep pass, and an already-present
2164
+ // `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
2165
+ // clean UI edit in a project with no Impeccable footprint, must be a
2166
+ // no-op on disk (issues #344, #305). An existing cache file also counts
2167
+ // as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
2168
+ // outside the project, so the project dir alone can't carry the marker —
2169
+ // without this, clean-edit editCount bumps would stop persisting the
2170
+ // moment state relocates. Under stock paths the cache sits inside
2171
+ // `.impeccable/`, so the extra check changes nothing there.
2172
+ if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
2173
+ persistCache(projectCwd, cache);
2174
+ }
2175
+
2176
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
2177
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
2178
+ }
2179
+
2180
+ if (quietMode) {
2181
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
2182
+ }
2183
+
2184
+ if (ack?.kind === 'pending') {
2185
+ const text = ack.text;
2186
+ return {
2187
+ exitCode: 0,
2188
+ stdout: payload(text, 'PostToolUse', harness),
2189
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
2190
+ audit: {
2191
+ ...audit,
2192
+ file: pendingWinner.filePath,
2193
+ emitted: true,
2194
+ kind: 'pending',
2195
+ pending: pendingWinner.known.length,
2196
+ chars: text.length,
2197
+ durationMs: Date.now() - started,
2198
+ },
2199
+ };
2200
+ }
2201
+
2202
+ if (suppressionWinner) {
2203
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
2204
+ return {
2205
+ exitCode: 0,
2206
+ stdout: payload(text, 'PostToolUse', harness),
2207
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
2208
+ audit: {
2209
+ ...audit,
2210
+ file: suppressionWinner.filePath,
2211
+ suppressed: true,
2212
+ emitted: true,
2213
+ durationMs: Date.now() - started,
2214
+ },
2215
+ };
2216
+ }
2217
+
2218
+ if (ack?.kind === 'clean') {
2219
+ const text = ack.text;
2220
+ return {
2221
+ exitCode: 0,
2222
+ stdout: payload(text, 'PostToolUse', harness),
2223
+ emission: { kind: 'clean', file: cleanWinner.filePath },
2224
+ audit: {
2225
+ ...audit,
2226
+ file: cleanWinner.filePath,
2227
+ emitted: true,
2228
+ kind: 'clean',
2229
+ chars: text.length,
2230
+ durationMs: Date.now() - started,
2231
+ },
2232
+ };
2233
+ }
2234
+
2235
+ if (pendingWinner) {
2236
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
2237
+ }
2238
+
2239
+ // Distinct from non-ui-ack so the audit log shows noise being suppressed on
2240
+ // purpose rather than a file the hook could not classify.
2241
+ if (cleanWinner) {
2242
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
2243
+ }
2244
+
2245
+ if (cleanAckDeduped) {
2246
+ return result({ emitted: false, skipped: 'clean-ack-deduped', durationMs: Date.now() - started });
2247
+ }
2248
+
2249
+ if (suppressedHit) {
2250
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
2251
+ }
2252
+
2253
+ return result({
2254
+ skipped: lastSkip,
2255
+ ...(lastSkip === 'too-large' ? { bytes: skippedBytes } : {}),
2256
+ durationMs: Date.now() - started,
2257
+ });
2258
+ } catch (err) {
2259
+ return {
2260
+ exitCode: 0,
2261
+ stdout: '',
2262
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
2263
+ };
2264
+ }
2265
+ }
2266
+
2267
+ // Cap on files the Stop deep pass will scan. The touched-file list is
2268
+ // session-scoped and already capped per edit, but a very long session could
2269
+ // accumulate more than the 30s hook timeout comfortably covers.
2270
+ export const STOP_MAX_FILES = 20;
2271
+
2272
+ /**
2273
+ * Run the Stop-event deep pass: the FULL detector rule set over every UI
2274
+ * file touched this session, surfaced once, deduped against everything the
2275
+ * per-edit hook already reported. Same result contract as runHook():
2276
+ * { exitCode, stdout, audit, emission? }
2277
+ *
2278
+ * Never throws; exits silent (and fast) when the session touched no UI
2279
+ * files. Output goes out on the harness's Stop continuation channel: Claude
2280
+ * Code and Grok Build read hookSpecificOutput.additionalContext, Codex takes
2281
+ * a decision: "block" whose reason becomes the continuation prompt. Either
2282
+ * way the findings reach the model and the conversation continues so it
2283
+ * can act.
2284
+ */
2285
+ export async function runStopHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
2286
+ const audit = { ts: new Date(now()).toISOString(), event: 'Stop' };
2287
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
2288
+
2289
+ try {
2290
+ // Re-entrancy guard, same as the per-edit pass.
2291
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
2292
+ return result({ reentrant: true, durationMs: 0 });
2293
+ }
2294
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
2295
+ return result({ skipped: 'env-disabled', durationMs: 0 });
2296
+ }
2297
+
2298
+ const started = Date.now();
2299
+
2300
+ let event;
2301
+ try {
2302
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
2303
+ } catch {
2304
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
2305
+ }
2306
+ if (!event || typeof event !== 'object') {
2307
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
2308
+ }
2309
+
2310
+ const harness = resolveHarness(env, event);
2311
+ audit.harness = harness;
2312
+ event = normalizeHookEvent(event, cwd, harness);
2313
+
2314
+ // Stop-hook re-entry guard: `stop_hook_active` is true when this hook is
2315
+ // being re-invoked only because a prior invocation kept the turn alive
2316
+ // (Claude Code via hookSpecificOutput.additionalContext, Codex via a
2317
+ // decision: "block" continuation). Re-scanning and re-blocking now could
2318
+ // loop (issue #400). The prior fire already surfaced the findings;
2319
+ // whether to act on them is the agent's call. Exit fast with no output
2320
+ // before any scan. Claude Code and Codex both send this field: Codex
2321
+ // mirrors the Claude contract (StopCommandInput in
2322
+ // codex-rs/hooks/src/schema.rs) and latches it true for the rest of the
2323
+ // turn once a block is honored (codex-rs/core/src/session/turn.rs). Grok
2324
+ // sends `stopHookActive`, copied onto the snake_case field above. Cursor
2325
+ // and GitHub Copilot omit the field, so the strict `=== true` is a no-op
2326
+ // for them. The guard makes the loop impossible regardless of the finding
2327
+ // cache key's line-number sensitivity (out of scope here; see
2328
+ // findingCacheKey).
2329
+ if (event.stop_hook_active === true) {
2330
+ return result({ skipped: 'stop-hook-active', durationMs: Date.now() - started });
2331
+ }
2332
+
2333
+ // Grok fires Stop twice: `end_turn` (the gate that can inject
2334
+ // additionalContext) then an observe-only `shutdown`. A second deep
2335
+ // pass would re-emit the same findings. Claude omits `reason`; only
2336
+ // skip when Grok named a reason that is not end_turn.
2337
+ if (harness === 'grok' && typeof event.reason === 'string' && event.reason !== 'end_turn') {
2338
+ return result({ skipped: 'stop-reason', reason: event.reason, durationMs: Date.now() - started });
2339
+ }
2340
+
2341
+ // A Stop event carries no file, so the session cwd is the project.
2342
+ // Umbrella-dir launches keyed their per-edit cache to the edited file's
2343
+ // project root (resolveCacheCwd); those sessions no-op here rather than
2344
+ // guessing which child project the session was about.
2345
+ const projectCwd = path.resolve(event.cwd || cwd);
2346
+ audit.cwd = projectCwd;
2347
+ const sessionId = event.session_id || 'unknown';
2348
+ audit.session = sessionId;
2349
+
2350
+ const config = readConfig(projectCwd);
2351
+ if (config.enabled === false) {
2352
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
2353
+ }
2354
+
2355
+ const cache = readCache(projectCwd);
2356
+ const touched = Object.keys(cache.sessions?.[sessionId]?.files || {});
2357
+ if (touched.length === 0) {
2358
+ return result({ skipped: 'no-touched-files', durationMs: Date.now() - started });
2359
+ }
2360
+
2361
+ const platform = resolveProjectPlatform(projectCwd);
2362
+ if (isNativePlatform(platform)) {
2363
+ return result({ skipped: 'native-platform', platform, durationMs: Date.now() - started });
2364
+ }
2365
+
2366
+ const det = detector || await loadDetector();
2367
+ if (!det || typeof det.detectText !== 'function') {
2368
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
2369
+ }
2370
+ const scanOptions = designSystemOptions(config, det, projectCwd);
2371
+
2372
+ const freshGroups = [];
2373
+ let scanned = 0;
2374
+ let cacheDirty = false;
2375
+ for (const filePath of touched) {
2376
+ if (scanned >= STOP_MAX_FILES) break;
2377
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) continue;
2378
+ if (GENERATED_PATH.test(filePath)) continue;
2379
+ const ext = path.extname(filePath).toLowerCase();
2380
+ const configuredExt = matchConfiguredExtension(filePath, config.extensions);
2381
+ if (!ALLOWED_EXTS.has(ext) && !configuredExt) continue;
2382
+ const relForMatch = relativize(filePath, projectCwd);
2383
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) continue;
2384
+ if (!fs.existsSync(filePath)) continue;
2385
+ // Caches written before this gate existed can still hold out-of-project
2386
+ // paths, so the Stop pass re-checks containment rather than trusting
2387
+ // the per-edit pass to have filtered them.
2388
+ if (!isScanTargetInsideProject(filePath, projectCwd)) continue;
2389
+
2390
+ scanned += 1;
2391
+ let content = '';
2392
+ try { content = fs.readFileSync(filePath, 'utf-8'); } catch { continue; }
2393
+
2394
+ let findings;
2395
+ let detectorThrew = false;
2396
+ const useHtmlEngine = configuredExt
2397
+ ? configuredExt.engine === 'html'
2398
+ : (ext === '.html' || ext === '.htm');
2399
+
2400
+ if (useHtmlEngine && typeof det.detectHtml === 'function') {
2401
+ try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
2402
+ } else {
2403
+ try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
2404
+ }
2405
+
2406
+ // A detector failure tells us nothing about the file. Leave whatever
2407
+ // was remembered alone rather than recording an empty scan as truth.
2408
+ if (detectorThrew) continue;
2409
+
2410
+ // Full rule set: no tier split here. Config/inline ignores still apply,
2411
+ // and the session dedupe drops everything the per-edit pass (or an
2412
+ // earlier Stop pass) already surfaced.
2413
+ const filtered = filterFindings(findings || [], content, ext, config);
2414
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
2415
+ // Sync to the live scan, including empty. Remembering only `fresh`
2416
+ // (or skipping the write on a clean Stop) left stale keys in place, so
2417
+ // a finding that was fixed and later reintroduced never fired again.
2418
+ rememberFindings(cache, sessionId, filePath, filtered);
2419
+ cacheDirty = true;
2420
+ if (fresh.length > 0) {
2421
+ freshGroups.push({ filePath, findings: fresh });
2422
+ }
2423
+ }
2424
+ audit.scannedFiles = scanned;
2425
+
2426
+ if (freshGroups.length === 0) {
2427
+ if (cacheDirty) persistCache(projectCwd, cache);
2428
+ return result({ emitted: false, skipped: 'stop-clean', durationMs: Date.now() - started });
2429
+ }
2430
+
2431
+ // A per-edit fire earlier in this session already consumed the footer
2432
+ // flag, so the Stop wall of text carries the one-line short footer.
2433
+ const footerMode = footerModeForSession(cache, sessionId);
2434
+ const text = appendDesignSystemNoteOnce(
2435
+ renderGroupedTemplate(freshGroups, config, {
2436
+ cwd: projectCwd,
2437
+ footer: footerMode,
2438
+ reserveChars: designNoteReserve(scanOptions, cache, sessionId),
2439
+ }),
2440
+ scanOptions, cache, sessionId, config,
2441
+ );
2442
+ commitFooterShown(cache, sessionId, text);
2443
+
2444
+ // Persist the live finding set so the next Stop fire is silent unless
2445
+ // new issues appear; the notice flags ride along.
2446
+ persistCache(projectCwd, cache);
2447
+ return {
2448
+ exitCode: 0,
2449
+ stdout: payload(text, 'Stop', harness),
2450
+ emission: {
2451
+ kind: 'stop-deep-pass',
2452
+ groups: freshGroups,
2453
+ },
2454
+ audit: {
2455
+ ...audit,
2456
+ emitted: true,
2457
+ freshFiles: freshGroups.length,
2458
+ freshFindings: freshGroups.reduce((sum, group) => sum + group.findings.length, 0),
2459
+ chars: text.length,
2460
+ durationMs: Date.now() - started,
2461
+ },
2462
+ };
2463
+ } catch (err) {
2464
+ return {
2465
+ exitCode: 0,
2466
+ stdout: '',
2467
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
2468
+ };
2469
+ }
2470
+ }
2471
+
2472
+ export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
2473
+ if (harness === 'cursor') {
2474
+ return JSON.stringify({ additional_context: text });
2475
+ }
2476
+ // GitHub Copilot's postToolUse hook injects context via a top-level
2477
+ // `additionalContext` string (alongside an optional `modifiedResult`).
2478
+ if (harness === 'github') {
2479
+ return JSON.stringify({ additionalContext: text });
2480
+ }
2481
+ // Codex shares Claude Code's PostToolUse additional-context shape, but its
2482
+ // Stop schema rejects unknown fields. Findings that should continue the
2483
+ // turn must be a top-level blocking decision.
2484
+ // https://developers.openai.com/codex/hooks#stop (schema of record:
2485
+ // codex-rs/hooks/src/schema.rs, StopCommandOutputWire)
2486
+ if (harness === 'codex' && eventName === 'Stop') {
2487
+ if (!String(text ?? '').trim()) return '';
2488
+ return JSON.stringify({ decision: 'block', reason: text });
2489
+ }
2490
+ return JSON.stringify({
2491
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
2492
+ });
2493
+ }