@bastani/atomic 0.9.20-alpha.1 → 0.9.20-alpha.11

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