@webpieces/agent-workflow-rules 0.0.0-stage → 0.0.1

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 (299) hide show
  1. package/README.md +23 -2
  2. package/package.json +45 -4
  3. package/src/adapters/agent-response.d.ts +5 -0
  4. package/src/adapters/agent-response.js +86 -0
  5. package/src/adapters/agent-response.js.map +1 -0
  6. package/src/adapters/codex-subagent-guard.d.ts +45 -0
  7. package/src/adapters/codex-subagent-guard.js +88 -0
  8. package/src/adapters/codex-subagent-guard.js.map +1 -0
  9. package/src/adapters/guards-hook.d.ts +3 -0
  10. package/src/adapters/guards-hook.js +30 -0
  11. package/src/adapters/guards-hook.js.map +1 -0
  12. package/src/adapters/hook-app-fixtures.d.ts +68 -0
  13. package/src/adapters/hook-app-fixtures.js +170 -0
  14. package/src/adapters/hook-app-fixtures.js.map +1 -0
  15. package/src/adapters/hook-core.d.ts +22 -0
  16. package/src/adapters/hook-core.js +359 -0
  17. package/src/adapters/hook-core.js.map +1 -0
  18. package/src/adapters/hook-pipeline-evaluator.d.ts +5 -0
  19. package/src/adapters/hook-pipeline-evaluator.js +18 -0
  20. package/src/adapters/hook-pipeline-evaluator.js.map +1 -0
  21. package/src/adapters/review-identity-stamper.d.ts +20 -0
  22. package/src/adapters/review-identity-stamper.js +34 -0
  23. package/src/adapters/review-identity-stamper.js.map +1 -0
  24. package/src/bin/codex-trust.d.ts +105 -0
  25. package/src/bin/codex-trust.js +205 -0
  26. package/src/bin/codex-trust.js.map +1 -0
  27. package/src/bin/dev-hook-install.d.ts +1 -0
  28. package/src/bin/dev-hook-install.js +80 -0
  29. package/src/bin/dev-hook-install.js.map +1 -0
  30. package/src/bin/dev-hook-uninstall.d.ts +1 -0
  31. package/src/bin/dev-hook-uninstall.js +45 -0
  32. package/src/bin/dev-hook-uninstall.js.map +1 -0
  33. package/src/bin/hook-registration.d.ts +429 -0
  34. package/src/bin/hook-registration.js +661 -0
  35. package/src/bin/hook-registration.js.map +1 -0
  36. package/src/bin/install-entry.d.ts +19 -0
  37. package/src/bin/install-entry.js +128 -0
  38. package/src/bin/install-entry.js.map +1 -0
  39. package/src/bin/l0-allowlist.d.ts +46 -0
  40. package/src/bin/l0-allowlist.js +527 -0
  41. package/src/bin/l0-allowlist.js.map +1 -0
  42. package/src/bin/l0-codex-read.d.ts +20 -0
  43. package/src/bin/l0-codex-read.js +108 -0
  44. package/src/bin/l0-codex-read.js.map +1 -0
  45. package/src/bin/l0-decide.d.ts +49 -0
  46. package/src/bin/l0-decide.js +90 -0
  47. package/src/bin/l0-decide.js.map +1 -0
  48. package/src/bin/l0-entry.d.ts +103 -0
  49. package/src/bin/l0-entry.js +98 -0
  50. package/src/bin/l0-entry.js.map +1 -0
  51. package/src/bin/l0-ignored-tools.d.ts +38 -0
  52. package/src/bin/l0-ignored-tools.js +44 -0
  53. package/src/bin/l0-ignored-tools.js.map +1 -0
  54. package/src/bin/managed-env.d.ts +46 -0
  55. package/src/bin/managed-env.js +50 -0
  56. package/src/bin/managed-env.js.map +1 -0
  57. package/src/bin/neighbour-hooks.d.ts +42 -0
  58. package/src/bin/neighbour-hooks.js +177 -0
  59. package/src/bin/neighbour-hooks.js.map +1 -0
  60. package/src/bin/reviewer-agent.d.ts +19 -0
  61. package/src/bin/reviewer-agent.js +135 -0
  62. package/src/bin/reviewer-agent.js.map +1 -0
  63. package/src/bin/settings-shape.d.ts +37 -0
  64. package/src/bin/settings-shape.js +17 -0
  65. package/src/bin/settings-shape.js.map +1 -0
  66. package/src/bin/setup-config.d.ts +20 -0
  67. package/src/bin/setup-config.js +371 -0
  68. package/src/bin/setup-config.js.map +1 -0
  69. package/src/bin/setup.d.ts +78 -0
  70. package/src/bin/setup.js +411 -0
  71. package/src/bin/setup.js.map +1 -0
  72. package/src/bin/shim-audit-log.d.ts +119 -0
  73. package/src/bin/shim-audit-log.js +286 -0
  74. package/src/bin/shim-audit-log.js.map +1 -0
  75. package/src/bin/shim-deny-reason.d.ts +1 -0
  76. package/src/bin/shim-deny-reason.js +244 -0
  77. package/src/bin/shim-deny-reason.js.map +1 -0
  78. package/src/bin/shim-drift-fix.d.ts +1 -0
  79. package/src/bin/shim-drift-fix.js +73 -0
  80. package/src/bin/shim-drift-fix.js.map +1 -0
  81. package/src/bin/shim-testkit.d.ts +107 -0
  82. package/src/bin/shim-testkit.js +197 -0
  83. package/src/bin/shim-testkit.js.map +1 -0
  84. package/src/bin/shim-version-drift.d.ts +1 -0
  85. package/src/bin/shim-version-drift.js +164 -0
  86. package/src/bin/shim-version-drift.js.map +1 -0
  87. package/src/bin/shim.d.ts +16 -0
  88. package/src/bin/shim.js +641 -0
  89. package/src/bin/shim.js.map +1 -0
  90. package/src/bin/upgrade-shim.d.ts +18 -0
  91. package/src/bin/upgrade-shim.js +283 -0
  92. package/src/bin/upgrade-shim.js.map +1 -0
  93. package/src/configs/main-sync-guard-configs.d.ts +38 -0
  94. package/src/configs/main-sync-guard-configs.js +54 -0
  95. package/src/configs/main-sync-guard-configs.js.map +1 -0
  96. package/src/configs/rule-configs.d.ts +47 -0
  97. package/src/configs/rule-configs.js +96 -0
  98. package/src/configs/rule-configs.js.map +1 -0
  99. package/src/core/ai-type-context.d.ts +36 -0
  100. package/src/core/ai-type-context.js +45 -0
  101. package/src/core/ai-type-context.js.map +1 -0
  102. package/src/core/decision-log.d.ts +190 -0
  103. package/src/core/decision-log.js +409 -0
  104. package/src/core/decision-log.js.map +1 -0
  105. package/src/core/excluded-path-escape.d.ts +101 -0
  106. package/src/core/excluded-path-escape.js +236 -0
  107. package/src/core/excluded-path-escape.js.map +1 -0
  108. package/src/core/force-to-root.d.ts +32 -0
  109. package/src/core/force-to-root.js +60 -0
  110. package/src/core/force-to-root.js.map +1 -0
  111. package/src/core/guard-index-doc.d.ts +63 -0
  112. package/src/core/guard-index-doc.js +172 -0
  113. package/src/core/guard-index-doc.js.map +1 -0
  114. package/src/core/instruct-ai-writer.d.ts +1 -0
  115. package/src/core/instruct-ai-writer.js +6 -0
  116. package/src/core/instruct-ai-writer.js.map +1 -0
  117. package/src/core/l0-matrix.d.ts +102 -0
  118. package/src/core/l0-matrix.js +357 -0
  119. package/src/core/l0-matrix.js.map +1 -0
  120. package/src/core/l0-tooling-doc.d.ts +45 -0
  121. package/src/core/l0-tooling-doc.js +258 -0
  122. package/src/core/l0-tooling-doc.js.map +1 -0
  123. package/src/core/l1-doc.d.ts +7 -0
  124. package/src/core/l1-doc.js +340 -0
  125. package/src/core/l1-doc.js.map +1 -0
  126. package/src/core/l1-matrix-doc.d.ts +31 -0
  127. package/src/core/l1-matrix-doc.js +111 -0
  128. package/src/core/l1-matrix-doc.js.map +1 -0
  129. package/src/core/l1-rows.d.ts +167 -0
  130. package/src/core/l1-rows.js +262 -0
  131. package/src/core/l1-rows.js.map +1 -0
  132. package/src/core/l2-doc.d.ts +7 -0
  133. package/src/core/l2-doc.js +385 -0
  134. package/src/core/l2-doc.js.map +1 -0
  135. package/src/core/l2-matrix-doc.d.ts +23 -0
  136. package/src/core/l2-matrix-doc.js +72 -0
  137. package/src/core/l2-matrix-doc.js.map +1 -0
  138. package/src/core/l2-row.d.ts +54 -0
  139. package/src/core/l2-row.js +75 -0
  140. package/src/core/l2-row.js.map +1 -0
  141. package/src/core/l2-rows.d.ts +56 -0
  142. package/src/core/l2-rows.js +272 -0
  143. package/src/core/l2-rows.js.map +1 -0
  144. package/src/core/load-rules.d.ts +9 -0
  145. package/src/core/load-rules.js +65 -0
  146. package/src/core/load-rules.js.map +1 -0
  147. package/src/core/log-stream.d.ts +117 -0
  148. package/src/core/log-stream.js +156 -0
  149. package/src/core/log-stream.js.map +1 -0
  150. package/src/core/log-streams.d.ts +48 -0
  151. package/src/core/log-streams.js +55 -0
  152. package/src/core/log-streams.js.map +1 -0
  153. package/src/core/log-target.d.ts +21 -0
  154. package/src/core/log-target.js +29 -0
  155. package/src/core/log-target.js.map +1 -0
  156. package/src/core/main-sync-log.d.ts +16 -0
  157. package/src/core/main-sync-log.js +108 -0
  158. package/src/core/main-sync-log.js.map +1 -0
  159. package/src/core/main-sync-refresh.d.ts +39 -0
  160. package/src/core/main-sync-refresh.js +96 -0
  161. package/src/core/main-sync-refresh.js.map +1 -0
  162. package/src/core/main-sync-timeout.d.ts +33 -0
  163. package/src/core/main-sync-timeout.js +95 -0
  164. package/src/core/main-sync-timeout.js.map +1 -0
  165. package/src/core/matrix-cures.d.ts +12 -0
  166. package/src/core/matrix-cures.js +56 -0
  167. package/src/core/matrix-cures.js.map +1 -0
  168. package/src/core/missing-directory.d.ts +38 -0
  169. package/src/core/missing-directory.js +66 -0
  170. package/src/core/missing-directory.js.map +1 -0
  171. package/src/core/read-only-inspection.d.ts +34 -0
  172. package/src/core/read-only-inspection.js +88 -0
  173. package/src/core/read-only-inspection.js.map +1 -0
  174. package/src/core/rejection-log.d.ts +9 -0
  175. package/src/core/rejection-log.js +262 -0
  176. package/src/core/rejection-log.js.map +1 -0
  177. package/src/core/rules/branch-creation-guard.d.ts +113 -0
  178. package/src/core/rules/branch-creation-guard.js +425 -0
  179. package/src/core/rules/branch-creation-guard.js.map +1 -0
  180. package/src/core/rules/branch-switch-scan.d.ts +43 -0
  181. package/src/core/rules/branch-switch-scan.js +132 -0
  182. package/src/core/rules/branch-switch-scan.js.map +1 -0
  183. package/src/core/rules/build-output-pipe-guard.d.ts +56 -0
  184. package/src/core/rules/build-output-pipe-guard.js +120 -0
  185. package/src/core/rules/build-output-pipe-guard.js.map +1 -0
  186. package/src/core/rules/build-output-pipe-scan.d.ts +47 -0
  187. package/src/core/rules/build-output-pipe-scan.js +84 -0
  188. package/src/core/rules/build-output-pipe-scan.js.map +1 -0
  189. package/src/core/rules/cap-remedies.d.ts +39 -0
  190. package/src/core/rules/cap-remedies.js +59 -0
  191. package/src/core/rules/cap-remedies.js.map +1 -0
  192. package/src/core/rules/commit-message-substitution-guard.d.ts +72 -0
  193. package/src/core/rules/commit-message-substitution-guard.js +134 -0
  194. package/src/core/rules/commit-message-substitution-guard.js.map +1 -0
  195. package/src/core/rules/commit-message-substitution-scan.d.ts +42 -0
  196. package/src/core/rules/commit-message-substitution-scan.js +145 -0
  197. package/src/core/rules/commit-message-substitution-scan.js.map +1 -0
  198. package/src/core/rules/content-read-scan.d.ts +76 -0
  199. package/src/core/rules/content-read-scan.js +176 -0
  200. package/src/core/rules/content-read-scan.js.map +1 -0
  201. package/src/core/rules/cure-prefix-scan.d.ts +64 -0
  202. package/src/core/rules/cure-prefix-scan.js +133 -0
  203. package/src/core/rules/cure-prefix-scan.js.map +1 -0
  204. package/src/core/rules/feature-branch-guard.d.ts +121 -0
  205. package/src/core/rules/feature-branch-guard.js +327 -0
  206. package/src/core/rules/feature-branch-guard.js.map +1 -0
  207. package/src/core/rules/index.d.ts +1 -0
  208. package/src/core/rules/index.js +5 -0
  209. package/src/core/rules/index.js.map +1 -0
  210. package/src/core/rules/judged-tree.d.ts +66 -0
  211. package/src/core/rules/judged-tree.js +97 -0
  212. package/src/core/rules/judged-tree.js.map +1 -0
  213. package/src/core/rules/main-freshness.d.ts +37 -0
  214. package/src/core/rules/main-freshness.js +61 -0
  215. package/src/core/rules/main-freshness.js.map +1 -0
  216. package/src/core/rules/merge-in-progress-guard.d.ts +17 -0
  217. package/src/core/rules/merge-in-progress-guard.js +124 -0
  218. package/src/core/rules/merge-in-progress-guard.js.map +1 -0
  219. package/src/core/rules/merged-branch-bash-guard.d.ts +62 -0
  220. package/src/core/rules/merged-branch-bash-guard.js +171 -0
  221. package/src/core/rules/merged-branch-bash-guard.js.map +1 -0
  222. package/src/core/rules/merged-branch-message.d.ts +59 -0
  223. package/src/core/rules/merged-branch-message.js +137 -0
  224. package/src/core/rules/merged-branch-message.js.map +1 -0
  225. package/src/core/rules/pr-creation-or-push-guard.d.ts +26 -0
  226. package/src/core/rules/pr-creation-or-push-guard.js +150 -0
  227. package/src/core/rules/pr-creation-or-push-guard.js.map +1 -0
  228. package/src/core/rules/pr-merge-guard.d.ts +36 -0
  229. package/src/core/rules/pr-merge-guard.js +87 -0
  230. package/src/core/rules/pr-merge-guard.js.map +1 -0
  231. package/src/core/rules/read-stale-guard.d.ts +136 -0
  232. package/src/core/rules/read-stale-guard.js +328 -0
  233. package/src/core/rules/read-stale-guard.js.map +1 -0
  234. package/src/core/rules/recovery-allowlist.d.ts +49 -0
  235. package/src/core/rules/recovery-allowlist.js +187 -0
  236. package/src/core/rules/recovery-allowlist.js.map +1 -0
  237. package/src/core/rules/redirect-how-to-merge-main.d.ts +16 -0
  238. package/src/core/rules/redirect-how-to-merge-main.js +159 -0
  239. package/src/core/rules/redirect-how-to-merge-main.js.map +1 -0
  240. package/src/core/rules/stale-main-bash-guard.d.ts +198 -0
  241. package/src/core/rules/stale-main-bash-guard.js +363 -0
  242. package/src/core/rules/stale-main-bash-guard.js.map +1 -0
  243. package/src/core/rules/stale-main-message.d.ts +62 -0
  244. package/src/core/rules/stale-main-message.js +102 -0
  245. package/src/core/rules/stale-main-message.js.map +1 -0
  246. package/src/core/rules/tree-recovery.d.ts +92 -0
  247. package/src/core/rules/tree-recovery.js +165 -0
  248. package/src/core/rules/tree-recovery.js.map +1 -0
  249. package/src/core/rules/wait-spin-guard.d.ts +128 -0
  250. package/src/core/rules/wait-spin-guard.js +211 -0
  251. package/src/core/rules/wait-spin-guard.js.map +1 -0
  252. package/src/core/rules/wait-spin-scan.d.ts +118 -0
  253. package/src/core/rules/wait-spin-scan.js +203 -0
  254. package/src/core/rules/wait-spin-scan.js.map +1 -0
  255. package/src/core/rules/whole-repo-build-guard.d.ts +125 -0
  256. package/src/core/rules/whole-repo-build-guard.js +257 -0
  257. package/src/core/rules/whole-repo-build-guard.js.map +1 -0
  258. package/src/core/rules/whole-repo-build-scan.d.ts +28 -0
  259. package/src/core/rules/whole-repo-build-scan.js +198 -0
  260. package/src/core/rules/whole-repo-build-scan.js.map +1 -0
  261. package/src/core/runner.d.ts +19 -0
  262. package/src/core/runner.js +482 -0
  263. package/src/core/runner.js.map +1 -0
  264. package/src/core/session-call-history.d.ts +44 -0
  265. package/src/core/session-call-history.js +79 -0
  266. package/src/core/session-call-history.js.map +1 -0
  267. package/src/core/sync-main.d.ts +46 -0
  268. package/src/core/sync-main.js +176 -0
  269. package/src/core/sync-main.js.map +1 -0
  270. package/src/core/version-sync.d.ts +219 -0
  271. package/src/core/version-sync.js +558 -0
  272. package/src/core/version-sync.js.map +1 -0
  273. package/src/core/webpieces-versions.d.ts +98 -0
  274. package/src/core/webpieces-versions.js +206 -0
  275. package/src/core/webpieces-versions.js.map +1 -0
  276. package/src/core/workflow-hook-rules.d.ts +5 -0
  277. package/src/core/workflow-hook-rules.js +15 -0
  278. package/src/core/workflow-hook-rules.js.map +1 -0
  279. package/src/index.d.ts +11 -0
  280. package/src/index.js +28 -0
  281. package/src/index.js.map +1 -0
  282. package/src/policy-keys.d.ts +2 -0
  283. package/src/policy-keys.js +6 -0
  284. package/src/policy-keys.js.map +1 -0
  285. package/src/rule-migrations.d.ts +3 -0
  286. package/src/rule-migrations.js +22 -0
  287. package/src/rule-migrations.js.map +1 -0
  288. package/src/rule-pack.d.ts +2 -0
  289. package/src/rule-pack.js +20 -0
  290. package/src/rule-pack.js.map +1 -0
  291. package/src/rule-settings.d.ts +5 -0
  292. package/src/rule-settings.js +31 -0
  293. package/src/rule-settings.js.map +1 -0
  294. package/src/safeguard-catalog.d.ts +3 -0
  295. package/src/safeguard-catalog.js +16 -0
  296. package/src/safeguard-catalog.js.map +1 -0
  297. package/templates/ai-hook.sh +497 -0
  298. package/templates/claude-settings-hook.json +28 -0
  299. package/templates/webpieces-reviewer.md +60 -0
@@ -0,0 +1,641 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_CHAINING_RULE = exports.SHIM_MARKER = void 0;
4
+ exports.shimPath = shimPath;
5
+ exports.renderShim = renderShim;
6
+ exports.findShimRoot = findShimRoot;
7
+ exports.healShim = healShim;
8
+ exports.governingShimRoot = governingShimRoot;
9
+ exports.committedShimStale = committedShimStale;
10
+ exports.isShimCureCommand = isShimCureCommand;
11
+ exports.installedShimRulesVersion = installedShimRulesVersion;
12
+ const tslib_1 = require("tslib");
13
+ const fs = tslib_1.__importStar(require("fs"));
14
+ const path = tslib_1.__importStar(require("path"));
15
+ const rules_config_1 = require("@webpieces/rules-config");
16
+ const rules_config_2 = require("@webpieces/rules-config");
17
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
18
+ const l0_allowlist_1 = require("./l0-allowlist");
19
+ const rules_config_3 = require("@webpieces/rules-config");
20
+ const rules_config_4 = require("@webpieces/rules-config");
21
+ const l0_codex_read_1 = require("./l0-codex-read");
22
+ const l0_ignored_tools_1 = require("./l0-ignored-tools");
23
+ const harness_vocabulary_1 = require("@webpieces/hook-runtime/harness-vocabulary");
24
+ const shim_audit_log_1 = require("./shim-audit-log");
25
+ const shim_drift_fix_1 = require("./shim-drift-fix");
26
+ const shim_version_drift_1 = require("./shim-version-drift");
27
+ // The allowlist moved to ./l0-allowlist (this module was over the file-size limit); re-exported here so
28
+ // every existing `from './shim'` import keeps working and there is still ONE name to import L0 by.
29
+ tslib_1.__exportStar(require("./l0-entry"), exports);
30
+ tslib_1.__exportStar(require("./l0-allowlist"), exports);
31
+ // …and its two siblings, split out for the same size reason: the decision (isAllowed / isRootManifest /
32
+ // READ_TOOLS) and the tool-shaped set it consults. ONE name to import L0 by, still.
33
+ tslib_1.__exportStar(require("./l0-decide"), exports);
34
+ tslib_1.__exportStar(require("./l0-ignored-tools"), exports);
35
+ // …and the harness-GATED half, split out for the same size reason: it owns the read-shaped vocabulary
36
+ // and the Codex-only union built from it. ONE name to import L0 by, still.
37
+ tslib_1.__exportStar(require("./l0-codex-read"), exports);
38
+ // Same treatment for the audit-log fragment: one name to import the whole rendered shim by.
39
+ tslib_1.__exportStar(require("./shim-audit-log"), exports);
40
+ // ---------------------------------------------------------------------------
41
+ // The single checked-in shim (.claude/webpieces/ai-hook.sh). Both project hooks point at it, passing
42
+ // their bin name as the first arg. settings.json points here (not at the bare bin) so a missing bin
43
+ // (fresh clone, package removed) yields a friendly message instead of the raw `sh: No such file or
44
+ // directory` on every Write/Edit/Bash tool call. `.claude` is committed, so the shim survives even
45
+ // when node_modules does not.
46
+ //
47
+ // This module is the SINGLE SOURCE OF TRUTH for the shim body + the installer allowlist. The
48
+ // installer (setup.ts) renders it on install; the running guards binary re-renders and self-heals it
49
+ // (healShim) so the committed .sh can never go stale — no human ever hand-edits it.
50
+ // ---------------------------------------------------------------------------
51
+ exports.SHIM_MARKER = '.claude/webpieces/ai-hook.sh';
52
+ // NO VERSION STAMP (removed 2026-07-24). The shim used to carry a per-release `# webpieces shim
53
+ // version: <v> (<sha>)` on line 2, rewritten by scripts/set-version.sh at publish. It was a pure
54
+ // human-eyeball diagnostic — nothing reads it (the deny's version note comes from the installed
55
+ // package.json) — but it made the committed shim go byte-different on EVERY release even when the
56
+ // logic was identical, so the committed-shim self-guard tripped on every upgrade over a comment (the
57
+ // DENY-SHIM-STALE churn). It also carried its own hazard: stamp one of the two lockstep artifacts and
58
+ // not the other and every consumer fail-closes forever on a phantom edit. Deleting it makes the shim
59
+ // byte-STABLE across releases, so the self-guard (now in the binary) fires only on a genuine logic
60
+ // change or a real tamper — which is what lets `pnpm install` be the fix for almost everything.
61
+ // webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container
62
+ function shimPath(projectRoot) {
63
+ return path.join(projectRoot, '.claude', 'webpieces', 'ai-hook.sh');
64
+ }
65
+ // ---------------------------------------------------------------------------
66
+ // HOW EVERY DENY MUST SPELL ITS CURE (added 2026-07-23, from a live audit-log post-mortem).
67
+ //
68
+ // The guards were right, the message was right, and the assistant STILL handed the block back to the
69
+ // human — because of one appended clause. From .webpieces/logs/L0-shim/<writer>.log in a consumer repo:
70
+ //
71
+ // DENY-SHIM-STALE cp node_modules/@webpieces/agent-workflow-rules/templates/ai-hook.sh .claude/webpieces/ai-hook.sh && git status --short
72
+ //
73
+ // That is the prescribed cure, verbatim, plus `&& git status --short`. Every allowlist here is anchored
74
+ // to `$`, so the trailing `&&` made it a different command and it was denied — and the assistant read
75
+ // its own denial as proof that "the guard blocks the very command that fixes it" and stopped.
76
+ //
77
+ // Widening the allowlist to accept `&& <anything>` is NOT the fix: these are fail-CLOSED escape hatches
78
+ // whose entire security property is that no shell operator can ride along (`cp … && rm -rf /`). The fix
79
+ // is to stop the assistant appending in the first place — so every deny that prescribes a command now
80
+ // (a) numbers its cures as OPTIONs, (b) quotes each one so the exact bytes are unambiguous, and
81
+ // (c) carries this rule, which says in plain words that adding `&&` gets it rejected again.
82
+ //
83
+ // CONSTRAINT on every string that reaches a deny REASON: no double quotes and no backslashes. The
84
+ // reason is interpolated into a `REASON="…"` shell assignment and then printf'd into a JSON string, so
85
+ // a `"` would break BOTH. Hence single quotes around the commands here — do not "improve" them.
86
+ // ---------------------------------------------------------------------------
87
+ // LENGTH IS PART OF THE FIX (2026-08-03). This block used to run ~153 words and was repeated verbatim
88
+ // in D, X and K — in X it was ~85% of the whole message, which buries the one sentence that matters.
89
+ // It now states the rule and the three tolerated additions, and nothing else: the tolerated set is
90
+ // exactly what CD_PREFIX_ERE + CAPTURE_TAIL_ERE accept (the single-quoted path branch of CD_PREFIX_ERE
91
+ // is why "single-quote a path containing spaces" is named), so this text cannot promise more or less
92
+ // than the allowlist grants.
93
+ exports.NO_CHAINING_RULE = 'Run it EXACTLY as written - the allowlist matches the whole command, so appending anything ' +
94
+ '(even && git status) makes it a different command and it is rejected; that is not the guard ' +
95
+ 'blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path ' +
96
+ 'containing spaces), a trailing 2>&1, and | tail -N.';
97
+ // Shell fragment: resolve the guard BIN by WALKING UP from ROOT, and remember WHERE it came from.
98
+ //
99
+ // THE BUG THIS CLOSES (it would have landed the day the hooks went relative). `ai-hook.sh` used to set
100
+ // `BIN="$ROOT/node_modules/.bin/$BIN_NAME"` — a LITERAL path with no upward walk, while Node's own
101
+ // resolver walks up. That was correct only while the hooks were registered ABSOLUTE, because then ROOT
102
+ // was always the primary clone and the bin was always there. The moment H2/H3 became relative, ROOT
103
+ // became the tree the call is in — and a nested worktree at `<primary>/.claude/worktrees/<name>` has NO
104
+ // node_modules of its own. Every subagent would have hard-blocked on fault X at its first tool call,
105
+ // fleet-wide, on the day of the flip. Walking up finds the primary's install, exactly as a `require()`
106
+ // from the same directory would; a SIBLING worktree finds nothing and correctly still faults X.
107
+ //
108
+ // BIN_ROOT is not a curiosity: walking up ALONE re-creates the version straddle documented above
109
+ // committedShimStale(), where the shim of one tree is paired with the binary of another and the cure
110
+ // can never converge. So BIN_ROOT is RECORDED, and the drift scan below uses it to decide WHOSE
111
+ // question this is: when BIN_ROOT == ROOT the pin and the install belong to one tree and fault D
112
+ // answers; when they differ the disagreement is CROSS-TREE and L0 stays silent so L1 row 8
113
+ // (VersionSyncGuard), which reads all four versions, answers instead. See VERSION_DRIFT_GUARD_SH.
114
+ const RESOLVE_BIN_SH = `BIN_ROOT="\$ROOT"
115
+ BIN="\$ROOT/node_modules/.bin/\$BIN_NAME"
116
+ WP_WALK="\$ROOT"
117
+ while [ ! -x "\$WP_WALK/node_modules/.bin/\$BIN_NAME" ]; do
118
+ WP_UP="\$(dirname -- "\$WP_WALK")"
119
+ [ "\$WP_UP" != "\$WP_WALK" ] || break
120
+ WP_WALK="\$WP_UP"
121
+ done
122
+ if [ -x "\$WP_WALK/node_modules/.bin/\$BIN_NAME" ]; then
123
+ BIN_ROOT="\$WP_WALK"
124
+ BIN="\$WP_WALK/node_modules/.bin/\$BIN_NAME"
125
+ fi`;
126
+ // Normal template literal (not String.raw): it carries #235's shell escapes verbatim (\${BIN_NAME},
127
+ // \$REASON, \\n for the deny JSON) AND my sed backslashes (doubled: \\(, \\), \\1, [^"\\\\]). The
128
+ // grep pattern is interpolated from INSTALLER_ALLOW_ERE (its value has no backslashes).
129
+ // Shell fragment: the two JSON escapes the deny text is built from, plus the one shared "what is still
130
+ // allowed" block. Hoisted to the TOP of the shim (it used to sit inside DENY_EMIT_SH's Bash branch,
131
+ // i.e. AFTER every REASON was already assembled) because the deny text now needs the newline escape
132
+ // while it is being BUILT, not only while it is being printed.
133
+ //
134
+ // THE MECHANISM IS THE ONE THE COLOUR ALREADY USED. `REASON` is interpolated into a `REASON="…"` shell
135
+ // assignment and then printf'd into a JSON string literal, so it may contain no RAW double-quote and no
136
+ // RAW backslash — and a RAW newline would be invalid JSON. That constraint is not "no newlines": it is
137
+ // "no raw backslash", and `${BS}` produces the backslash at RUNTIME, so `${ESC}` (six chars: \ u 0 0 1 b)
138
+ // and `${NL}` (two chars: \ n) both travel as legal JSON escapes that Claude Code's parser turns back
139
+ // into a real ESC and a real newline. Verified end to end through /bin/sh in setup.spec.ts: the payload
140
+ // still parses as JSON, the systemMessage still carries 31;1m, and the reason renders as many lines.
141
+ //
142
+ // WHY THE STRUCTURE MATTERS: every L1/L2 deny is rendered by formatReport() into a scannable shape —
143
+ // header, `[guard-name] (N violations)`, indented offenders each with a one-line `→ why`, then numbered
144
+ // `Fix Option N:` lines. L0 was the ONLY layer answering in one unbroken paragraph. It now uses the same
145
+ // skeleton, which is what WP_STILL_ALLOWED exists for: one definition of that section for all four
146
+ // sh-side faults, so they cannot drift into four different answers to the same question.
147
+ const ESCAPES_SH = `BS='\\' # one literal backslash, so no \\u001b / \\n escape sits in this source
148
+ ESC="\${BS}u001b" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\u001b → ESC
149
+ NL="\${BS}n" # the 2 chars: backslash n — parsed as a real newline inside the JSON string
150
+ WP_STILL_ALLOWED="Still allowed while this block is up:\${NL} - any Read, and ${rules_config_4.CODEX_READ_STILL_ALLOWED}\${NL} - any Write/Edit whose target is ${rules_config_1.CONFIG_FILENAME}, ${rules_config_3.WORKSPACE_MANIFEST} or ${rules_config_3.PACKAGE_MANIFEST}\${NL} - every command on the L0 allowlist, including the Fix Options below\${NL} THIS IS NOT A DEADLOCK - run one YOURSELF now; do not hand it back to the human."`;
151
+ // Shell fragment: run the installed guard bin and INSPECT its outcome, instead of exec'ing it.
152
+ //
153
+ // THE BUG THIS FIXES (guards silently fail-OPEN): the shim used to `exec "$BIN"`. exec REPLACES this
154
+ // shim process, so once the bin was executable the shim was GONE and could no longer make a decision.
155
+ // That is fine when the bin runs — but the bin can be INSTALLED YET BROKEN: a corrupt/partially-written
156
+ // node_modules makes node die at require() time with MODULE_NOT_FOUND, exiting 1. And in the PreToolUse
157
+ // protocol ONLY exit 2 blocks: any other non-zero is a NON-BLOCKING error, so Claude Code prints
158
+ // "Failed with non-blocking status code" and RUNS THE TOOL CALL ANYWAY — the guard is silently skipped.
159
+ // Result: every Write/Edit/Bash went UNGUARDED, for as long as node_modules stayed corrupt. The shim
160
+ // handled "bin missing" and "bin stale", but never "bin present and CRASHES" — the third failure mode.
161
+ //
162
+ // So: do not exec. Run the bin with the payload on stdin and branch on its exit code.
163
+ // rc 0 | 2 → a REAL decision (allow / block). Relay stdout, stderr and the code byte-faithfully.
164
+ // anything else → the guard CRASHED. Fall through to the fail-CLOSED path (BROKEN_BIN=1).
165
+ // stdout/stderr go through temp FILES, not $(command substitution), so the bin's bytes reach Claude
166
+ // Code exactly as written — command substitution strips trailing newlines and would corrupt the
167
+ // decision JSON. Reading the payload up-front ($PAYLOAD) is what replaces exec's stdin passthrough.
168
+ const RUN_BIN_SH = `if [ -x "\$BIN" ] && [ -z "\$DRIFT_PKG" ]; then
169
+ OUT_FILE="\${TMPDIR:-/tmp}/wp-ai-hook-out.\$\$"
170
+ ERR_FILE="\${TMPDIR:-/tmp}/wp-ai-hook-err.\$\$"
171
+ printf '%s' "\$PAYLOAD" | "\$BIN" "\$@" >"\$OUT_FILE" 2>"\$ERR_FILE"
172
+ RC=\$?
173
+ if [ "\$RC" = 0 ] || [ "\$RC" = 2 ]; then
174
+ cat "\$OUT_FILE" # the guard's real decision — verbatim
175
+ cat "\$ERR_FILE" >&2
176
+ rm -f "\$OUT_FILE" "\$ERR_FILE" 2>/dev/null
177
+ # THE HEALTHY CALL, which this log used to be silent about (see WP_LOG_SH's header). No sh-side
178
+ # fault, the bin ran, and its own exit code says how it ended — 0 allow, 2 block. Logged AFTER the
179
+ # decision bytes are already on stdout, so the audit trail never sits between the guard and Claude
180
+ # Code. Without this line, "no entry" meant either healthy or never-ran, and those are the two
181
+ # answers a reader most needs to tell apart.
182
+ WP_VERDICT=PASS-BIN-ALLOW
183
+ [ "\$RC" = 2 ] && WP_VERDICT=PASS-BIN-BLOCK
184
+ wp_log - "\$WP_VERDICT"
185
+ exit "\$RC"
186
+ fi
187
+ # Crashed. Keep the most useful stderr line for the human. Strip " and backslash so the text stays a
188
+ # valid JSON string, and cap the length so a giant node stack cannot blow up the deny payload.
189
+ CRASH_MSG="\$(grep -m1 'Cannot find module' "\$ERR_FILE" 2>/dev/null | tr -d '"\\\\' | cut -c1-120)"
190
+ [ -n "\$CRASH_MSG" ] || CRASH_MSG="\$(head -n1 "\$ERR_FILE" 2>/dev/null | tr -d '"\\\\' | cut -c1-120)"
191
+ [ -n "\$CRASH_MSG" ] || CRASH_MSG="exit code \$RC, no stderr"
192
+ rm -f "\$OUT_FILE" "\$ERR_FILE" 2>/dev/null
193
+ BROKEN_BIN=1
194
+ fi`;
195
+ // Shell fragment: pull the four fields the shim itself reasons about out of the tool payload.
196
+ //
197
+ // MOVED AHEAD OF THE BIN (it used to sit inside TRIAGE_SH, i.e. only on the fail-closed path) because
198
+ // the audit log now covers the HEALTHY call too, and a log line needs the tool and the command whether
199
+ // or not anything went wrong.
200
+ //
201
+ // `cwd` is Claude Code's documented "current working directory when the hook is invoked". It is used
202
+ // for ONE thing: deciding which tree's log directory this line belongs in (see RESOLVE_LOG_DIR_SH).
203
+ // It deliberately does NOT change what the drift guard MEASURES — that stays anchored to $ROOT, the
204
+ // tree the shim FILE lives in. Where a call is logged and what a call is judged against are separate
205
+ // questions and are kept separate here.
206
+ // TWO command variables, and the split is a SECURITY boundary — do not collapse them.
207
+ //
208
+ // $CMD is the DECISION input (the L0 allowlist greps it). Its pattern requires the CLOSING quote, so a
209
+ // JSON payload that escapes an embedded quote as \\" yields the EMPTY STRING for the whole command.
210
+ // That looks like a bug and is in fact the safe direction: an empty command matches no allowlist entry,
211
+ // so a quoted command falls through to the deny. FAIL CLOSED. Keep it that way.
212
+ //
213
+ // $CMD_LOG is the AUDIT input and must never reach a decision. It drops the closing quote from the
214
+ // pattern so it captures the command PREFIX instead of nothing.
215
+ //
216
+ // WHY THEY CANNOT BE ONE VARIABLE: every L0 allowlist ERE is anchored `^…[[:space:]]*$`, and trailing
217
+ // whitespace is tolerated — so `pnpm install "; rm -rf /"` would prefix-capture to `pnpm install `,
218
+ // which MATCHES, and the injection after the quote would ride through allowlisted. Measured 2026-08-06:
219
+ // 3,908 of 4,917 shim audit lines (79.5%) recorded an empty command, i.e. four out of five audit
220
+ // entries were blind. Fixing the LOG is worth doing; fixing the DECISION the same way is a hole.
221
+ const PARSE_PAYLOAD_SH = `CMD="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
222
+ CMD_LOG="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\).*/\\1/p')"
223
+ [ -n "\$CMD_LOG" ] || CMD_LOG="\$CMD"
224
+ TOOL="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
225
+ WP_SID="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
226
+ WP_AID="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"agent_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
227
+ FILE="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
228
+ WP_CWD="\$(printf '%s' "\$PAYLOAD" | sed -n 's/.*"cwd"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
229
+ [ -n "\$WP_CWD" ] || WP_CWD="\$ROOT" # no cwd in the payload (older client, or a hand-run) → the shim's own tree
230
+ # WHICH HARNESS sent this call — the ONE discriminator, imported from ../adapters/detect-ai so the sh
231
+ # half of L0 and the JS half answer the identical question from one definition (the same twin pattern
232
+ # L0_ALLOW_ERE_SH / L0_ALLOW_JS uses). One \`case\`, no JSON parser: consistent with how every field
233
+ # above is \`sed\`-scraped, and the values are the AiType union's own strings so the twin-agreement spec
234
+ # compares them byte for byte instead of translating between two vocabularies.
235
+ ${harness_vocabulary_1.AI_TYPE_SH}`;
236
+ // Shell fragment: the guards are DOWN (missing | stale | crashed). Classify the fault, then let THE L0
237
+ // ALLOWLIST through — everything else falls to the deny below.
238
+ //
239
+ // This asks the identical question isAllowed() asks in JS, in the same order: Read, then the
240
+ // webpieces.config.json target, then the one command union (L0_ALLOW_ERE). The sh and JS halves exist
241
+ // because D/X/K are decided BEFORE the bin runs (a stale/missing/broken validator cannot validate
242
+ // itself) while S/C/Y are decided inside it — one model, two enforcement points.
243
+ //
244
+ // NOTE the documented asymmetry: here the bin is never executed, so an allowed Read is TERMINAL and
245
+ // read-stale-guard does not run. In JS the same entry falls through and it does. See isAllowed().
246
+ const TRIAGE_SH = `# WHICH of the guards/L0-tooling.md faults fired, in the doc's own letters. Only the four sh-side
247
+ # codes can be decided here; S/C/Y live in the binary, which never got to run on this path.
248
+ WP_FAULT=${rules_config_2.L0_FAULT_BIN_MISSING} # X — bin missing (fresh clone, new worktree)
249
+ [ -z "\$WP_HOOK_PKG_DECLARED" ] && WP_FAULT=${rules_config_2.L0_FAULT_UNDECLARED} # U — X, but nothing declares the package: install is a no-op
250
+ [ -n "\$DRIFT_PKG" ] && WP_FAULT=${rules_config_2.L0_FAULT_DRIFT} # D — version drift; D and K are mutually exclusive
251
+ [ -n "\$BROKEN_BIN" ] && WP_FAULT=${rules_config_2.L0_FAULT_BIN_BROKEN} # K — bin present but CRASHED (corrupt node_modules)
252
+ DENY_LABEL="DENY"
253
+ [ -z "\$WP_HOOK_PKG_DECLARED" ] && DENY_LABEL="DENY-UNDECLARED" # nothing in package.json asks for the package
254
+ [ -n "\$DRIFT_PKG" ] && DENY_LABEL="DENY-STALE" # version drift, not a missing bin
255
+ [ -n "\$BROKEN_BIN" ] && DENY_LABEL="DENY-BROKEN" # bin present but CRASHED (corrupt node_modules)
256
+ # THE L0 ALLOWLIST, entry order identical to isAllowed(). No fault is consulted: a cure that cannot
257
+ # help a given fault also cannot hurt it, and gating each entry on a fault is what produced the four
258
+ # defects recorded above L0_ALLOW_ERE.
259
+ if [ "\$TOOL" = "Read" ]; then
260
+ wp_log "\$WP_FAULT" ALLOW-READ # you must be able to read to work out how to fix this
261
+ exit 0
262
+ fi
263
+ case "\$TOOL" in
264
+ ${l0_ignored_tools_1.L0_IGNORED_TOOLS_SH})
265
+ # Nothing to judge — the Codex tools that are neither a shell command nor a file edit. sh twin of
266
+ # isAllowed()'s L0_IGNORED_TOOLS branch; see there for why the list is EXPLICIT and why apply_patch
267
+ # (Codex's only WRITE) is not on it.
268
+ wp_log "\$WP_FAULT" ALLOW-IGNORED
269
+ exit 0 ;;
270
+ esac
271
+ case "\$FILE" in
272
+ */${rules_config_1.CONFIG_FILENAME}|${rules_config_1.CONFIG_FILENAME})
273
+ wp_log "\$WP_FAULT" ALLOW-CONFIG # the always-allowed recovery target — every guard is configured from it
274
+ exit 0 ;;
275
+ */${rules_config_3.WORKSPACE_MANIFEST}|${rules_config_3.WORKSPACE_MANIFEST}|*/${rules_config_3.PACKAGE_MANIFEST}|${rules_config_3.PACKAGE_MANIFEST})
276
+ # A manifest AT THE ROOT OF A GOVERNED TREE, which is the only place the version pin lives. The test
277
+ # is the sibling ${rules_config_1.CONFIG_FILENAME} — TRACKED, so the main clone has one and every worktree has its
278
+ # own — and NOT \$ROOT, which names whichever tree supplied this shim and would deny the other's.
279
+ # Basename alone would be far worse here than in the JS half: this arm is TERMINAL (exit 0, the bin
280
+ # never runs), so every packages/**/package.json would be editable with nothing judging it.
281
+ if [ -f "\$(dirname -- "\$FILE")/${rules_config_1.CONFIG_FILENAME}" ]; then
282
+ wp_log "\$WP_FAULT" ALLOW-MANIFEST # raising the pin must be typable from inside the block
283
+ exit 0
284
+ fi ;;
285
+ esac
286
+ if printf '%s' "\$CMD" | grep -Eq '${l0_allowlist_1.L0_ALLOW_ERE_SH}'; then
287
+ wp_log "\$WP_FAULT" ALLOW-CURE # record the self-heal we let through (re-enables the guards)
288
+ exit 0 # allow the cure so the assistant can break the deadlock
289
+ fi
290
+ # THE HARNESS-GATED TAIL OF THE SAME LIST, and the ONLY place \$AI changes a decision. Under Claude Code
291
+ # the guard is false and the next line is the deny — byte for byte the path a Claude payload took before
292
+ # this branch existed. Under Codex it is the twin of the ALLOW-READ arm above: Codex has NO Read tool, so
293
+ # a read arrives as this Bash command, and without this every L0 fault denies a Codex session the very
294
+ # reads the deny is telling it to perform. The pattern is anchored on its own (no cd prefix, no capture
295
+ # tail) — see L0_CODEX_ALLOW_ERE. TERMINAL, exactly like the Read arm, and for the same reason: on this
296
+ # path the bin never runs, so there is nothing to fall through to.
297
+ if [ "\$AI" = codex ] && printf '%s' "\$CMD" | grep -Eq '${l0_codex_read_1.L0_CODEX_ALLOW_ERE_SH}'; then
298
+ wp_log "\$WP_FAULT" ALLOW-CODEX-READ
299
+ exit 0
300
+ fi
301
+ wp_log "\$WP_FAULT" "\$DENY_LABEL" # every fail-closed block, with the fault that caused it`;
302
+ // Shell fragment: emit the deny. FAIL CLOSED via Claude Code's PreToolUse JSON protocol
303
+ // (permissionDecision "deny" on stdout, then exit 0) rather than a bare "exit 2". BOTH block the call,
304
+ // but the reason must be made VISIBLE, and HOW depends on the tool (verified by live tests; the docs
305
+ // are wrong here):
306
+ // - Bash deny: permissionDecisionReason is NOT shown to the human — ONLY a top-level systemMessage
307
+ // is, and it honors ANSI. So for Bash we emit systemMessage wrapped in ANSI red so the
308
+ // recovery command is visible (without it, on Bash, it is invisible).
309
+ // - Write/Edit/MultiEdit deny: permissionDecisionReason renders as a RED "Error:" block natively —
310
+ // no systemMessage needed (a second line would be redundant).
311
+ // - NEVER exit 2 (stdout JSON ignored; stderr not reliably shown on a blocked Bash call).
312
+ // The ESC and the newline escape are both built in ESCAPES_SH at the TOP of the shim (see its header):
313
+ // ${ESC} is the literal 6-char JSON escape \\u001b and ${NL} the 2-char \\n, so no raw ESC byte, no raw
314
+ // newline and no \\uXXXX sits in this source, and Claude Code's JSON parser turns both back. The reason
315
+ // is a single JSON string with no RAW double-quotes/backslashes, so it stays valid JSON after the subs.
316
+ //
317
+ // ONLY THE HEADLINE IS RED, and that is deliberate — the same call redSystemMessage() makes on the JS
318
+ // side. The reason is MULTI-LINE now, and a whole page in bold red is harder to read than the paragraph
319
+ // it replaced: the indentation carrying the structure stops registering when every line shouts. So
320
+ // \$WP_HEAD (each branch's own first line, kept in its own variable for exactly this) is wrapped in
321
+ // [31;1m … [0m, and \${REASON#"\$WP_HEAD"} — POSIX prefix removal with a QUOTED pattern, so the
322
+ // headline is matched literally and not as a glob — supplies the plain body after it.
323
+ const DENY_EMIT_SH = `if [ "\$TOOL" = "Bash" ]; then
324
+ printf '{"systemMessage":"%s🛑 %s%s%s","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\\n' "\${ESC}[31;1m" "\$WP_HEAD" "\${ESC}[0m" "\${REASON#"\$WP_HEAD"}" "\$REASON"
325
+ else
326
+ printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\\n' "\$REASON"
327
+ fi
328
+ exit 0 # decision is carried by permissionDecision "deny", not the exit code`;
329
+ // Shell fragment: pick the fail-closed deny REASON — a crashed-bin message (corrupt node_modules) vs a
330
+ // version-drift message (bin present but stale) vs the missing-bin message. Extracted alongside
331
+ // VERSION_DRIFT_GUARD_SH / RUN_BIN_SH to keep renderShim() within the method-line budget.
332
+ const DENY_REASON_SH = `if [ -n "\$BROKEN_BIN" ]; then
333
+ # Report (do NOT auto-clean) the orphaned pnpm staging dirs — a package pnpm was mid-way through
334
+ # writing is left behind as <name>_<pid>_<hash>. Their presence is the fingerprint of an install that
335
+ # was killed, which is what corrupts node_modules in the first place. Best-effort; never fatal.
336
+ STAGING_N="\$(ls "\$BIN_ROOT/node_modules" 2>/dev/null | grep -Ec '_[0-9a-f]+_[0-9a-f]+\$' || true)"
337
+ STAGING_NOTE=""
338
+ if [ "\${STAGING_N:-0}" -gt 0 ] 2>/dev/null; then
339
+ STAGING_NOTE="\${NL} → also found \$STAGING_N orphaned pnpm staging dirs (name_pid_hash) under node_modules - the fingerprint of an install that was killed mid-write." # only when N > 0
340
+ fi
341
+ # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
342
+ WP_HEAD="❌ webpieces ai-hooks blocked this call: the webpieces guards are DOWN."
343
+ REASON="\$WP_HEAD\${NL}\${NL}${(0, rules_config_2.l0GuardHeader)(rules_config_2.L0_FAULT_BIN_BROKEN, '1 violation')}\${NL} \${BIN_NAME} (\$CRASH_MSG)\${NL} → it is installed but CRASHED, so your node_modules is corrupt or partially written; the guards cannot run and they must not be silently skipped. Every OTHER tool call is BLOCKED until they can.\${STAGING_NOTE}\${NL} → ${(0, rules_config_2.l0MatrixCitation)(rules_config_2.L0_FAULT_BIN_BROKEN)}\${NL}\${NL}\${WP_STILL_ALLOWED}\${NL}\${NL} Fix Option 1: (preferred) the only cure. A bare 'pnpm install' will NOT fix this, because pnpm sees the correct version on disk and skips the broken package\${NL} run EXACTLY: '${l0_allowlist_1.RECOVERY_CMD}'\${NL}\${NL}${exports.NO_CHAINING_RULE}"
344
+ elif [ -n "\$DRIFT_PKG" ]; then
345
+ # DECIDE THE DIRECTION, do not make the reader do it (2026-08-03). The detection is a plain !=, so it
346
+ # fires BOTH ways, and the message used to carry OPTION 1/2/3 covering every direction at once — 3343
347
+ # chars of which only about a third was the decision. A reader on the wrong branch of that menu was
348
+ # one misread away from a downgrade. So compare the two versions HERE and emit only the relevant half.
349
+ #
350
+ # WITH AWK, not \`sort -V\`: -V is a GNU extension (absent/different on BSD sort), while the shim
351
+ # already runs an awk pass to resolve catalog: specs, so awk adds no dependency. The program compares
352
+ # the numeric cores component-by-component; a pre-release/build suffix (-rc.1, +sha) is stripped from
353
+ # the core, and when the cores are EQUAL the side carrying a PRE-RELEASE suffix is the older one
354
+ # (semver precedence). Build metadata (+sha) carries NO precedence, so two versions differing only
355
+ # there come back undecidable rather than ordered. Anything it cannot parse prints NOTHING, and an
356
+ # empty answer falls through to the ambiguous wording below rather than guessing a direction.
357
+ #
358
+ # WHAT WAS DELETED, so it does not creep back: the "how to get main itself current" paragraph and the
359
+ # "do NOT reach for git merge --ff-only / reset --hard / checkout -B main" paragraph both belong to
360
+ # redirect-how-to-merge-main, which fires on its own with its own message; and the sentence that named
361
+ # wp-start-update / wp-start-upsert-pr ONLY to forbid them while the block is up — naming a command
362
+ # purely to forbid it is pure cost, and the install that clears this fault comes first regardless.
363
+ DRIFT_DIR="\$(awk -v i="\$DRIFT_INSTALLED" -v d="\$DRIFT_DECLARED" 'BEGIN {
364
+ iv = i; sub(/\\+.*/, "", iv); ic = iv; sub(/-.*/, "", ic); ip = substr(iv, length(ic) + 1)
365
+ dv = d; sub(/\\+.*/, "", dv); dc = dv; sub(/-.*/, "", dc); dp = substr(dv, length(dc) + 1)
366
+ if (ic !~ /^[0-9]+(\\.[0-9]+)*\$/ || dc !~ /^[0-9]+(\\.[0-9]+)*\$/) exit
367
+ n = split(ic, ia, "."); m = split(dc, da, "."); k = (n > m) ? n : m
368
+ for (x = 1; x <= k; x++) {
369
+ av = (x <= n) ? ia[x] + 0 : 0; bv = (x <= m) ? da[x] + 0 : 0
370
+ if (av < bv) { print "older"; exit }
371
+ if (av > bv) { print "newer"; exit }
372
+ }
373
+ if (ip == dp) exit
374
+ if (ip != "" && dp == "") print "older"
375
+ if (ip == "" && dp != "") print "newer"
376
+ }' 2>/dev/null)"
377
+ if [ "\$DRIFT_DIR" = older ]; then
378
+ # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
379
+ WP_HEAD="❌ webpieces ai-hooks blocked this call: webpieces version drift."
380
+ REASON="\$WP_HEAD\${NL}\${NL}${(0, rules_config_2.l0GuardHeader)(rules_config_2.L0_FAULT_DRIFT, '1 violation')}\${NL} package.json pins \$DRIFT_PKG@\$DRIFT_DECLARED but node_modules has \$DRIFT_INSTALLED\${NL} → node_modules is OLDER, so the pin is what you want. Every OTHER tool call is BLOCKED until the two agree.\${NL} → ${(0, rules_config_2.l0MatrixCitation)(rules_config_2.L0_FAULT_DRIFT)}\${NL}\${NL}\${WP_STILL_ALLOWED}\${NL}\${NL} Fix Option 1: (preferred) the only cure - it makes node_modules match the pin\${NL} run EXACTLY: 'pnpm install'\${NL}\${NL}${exports.NO_CHAINING_RULE}"
381
+ else
382
+ # NEWER, or undecidable — the same choices apply either way, so the only thing the ambiguous
383
+ # case changes is the claim about which side is stale.
384
+ DRIFT_NOTE="node_modules is NEWER, so the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \$DRIFT_DECLARED"
385
+ [ "\$DRIFT_DIR" = newer ] || DRIFT_NOTE="these two versions could not be ordered automatically - compare them yourself: if node_modules is the NEWER side then the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \$DRIFT_DECLARED"
386
+ ${shim_drift_fix_1.DRIFT_INVERSE_FIX_SH}
387
+ # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
388
+ WP_HEAD="❌ webpieces ai-hooks blocked this call: webpieces version drift."
389
+ REASON="\$WP_HEAD\${NL}\${NL}${(0, rules_config_2.l0GuardHeader)(rules_config_2.L0_FAULT_DRIFT, '1 violation')}\${NL} package.json pins \$DRIFT_PKG@\$DRIFT_DECLARED but node_modules has \$DRIFT_INSTALLED\${NL} → \$DRIFT_NOTE. That may be exactly what you want. Every OTHER tool call is BLOCKED until the two agree.\${NL} → ${(0, rules_config_2.l0MatrixCitation)(rules_config_2.L0_FAULT_DRIFT)}\${NL}\${NL}\${WP_STILL_ALLOWED}\${NL}\${NL}\${WP_FIX}\${NL}\${NL}${exports.NO_CHAINING_RULE}"
390
+ fi
391
+ else
392
+ # A LINKED WORKTREE is the overwhelmingly common way to land here with a perfectly healthy repo:
393
+ # git gives the new worktree a .git FILE (the primary clone has a .git directory) and copies no
394
+ # node_modules, so the very first tool call in a brand-new worktree fail-closes on a missing bin.
395
+ # Naming that explicitly turns a baffling "not installed" into a one-command fix, and the HERE is
396
+ # load-bearing: installing in the primary clone does nothing for this tree.
397
+ WORKTREE_NOTE=""
398
+ if [ -f "\$ROOT/.git" ]; then
399
+ WORKTREE_NOTE="\${NL} → \$ROOT is a LINKED WORKTREE - git does not copy node_modules into a new worktree, so this is expected on a fresh one. Run the Fix Option HERE, in this worktree, not in the primary clone."
400
+ fi
401
+ if [ -z "\$WP_HOOK_PKG_DECLARED" ]; then
402
+ # FAULT U — the one shape where the X message is not merely unhelpful but actively WRONG. It asserted
403
+ # "declared in package.json" without ever checking, and prescribed the one command that provably
404
+ # cannot help: with nothing asking for the package, \`pnpm install\` reports "Lockfile is up to date"
405
+ # and converges to the identical broken tree, forever. So say what is actually true, say out loud
406
+ # that the install is a no-op (an agent that has already run it needs to be told to STOP), and
407
+ # prescribe the add — which is allowlist entry ADD_HOOK_PKG, so it is reachable while this block is up.
408
+ WP_ADD_CMD="${l0_allowlist_1.ADD_HOOK_PKG_CMD}"
409
+ [ -n "\$WP_PIN" ] && WP_ADD_CMD="\${WP_ADD_CMD}@\$WP_PIN"
410
+ # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
411
+ WP_HEAD="❌ webpieces ai-hooks blocked this call: the guard package is not declared anywhere."
412
+ REASON="\$WP_HEAD\${NL}\${NL}${(0, rules_config_2.l0GuardHeader)(rules_config_2.L0_FAULT_UNDECLARED, '1 violation')}\${NL} ${l0_allowlist_1.HOOK_PKG} is NOT declared in this tree's root package.json, and is not installed (\${BIN_NAME} not found)\${NL} → .claude/settings.json still runs its hooks, so every OTHER tool call is BLOCKED. A BARE 'pnpm install' is a NO-OP here: the root manifest asks for nothing, so it reports 'Lockfile is up to date' and converges to this same state. CHANGE something first - sync, or the pin - and install AFTER that.\${NL} → ${(0, rules_config_2.l0MatrixCitation)(rules_config_2.L0_FAULT_UNDECLARED)}\${NL}\${NL}\${WP_STILL_ALLOWED}\${NL}\${NL} Fix Option 1: (preferred) ${l0_allowlist_1.HOOK_PKG} normally arrives WITH @webpieces/webpieces-tooling, the umbrella that bundles the whole toolchain - so the usual cause is a tree that is behind, not a missing declaration. Sync, then install:\${NL} run EXACTLY: '${l0_allowlist_1.CHECKOUT_MAIN_PULL_CMD}'\${NL} then run EXACTLY: 'pnpm install'\${NL} Fix Option 2: still missing? the pinned release predates the umbrella carrying it. If the root still declares @webpieces/nx-webpieces-rules as its umbrella, replace that declaration in package.json and its catalog key in ${rules_config_3.WORKSPACE_MANIFEST} with @webpieces/webpieces-tooling. Pin the ONE new catalog entry to a release that carries the guard package - editing those files is allowed while this block is up - then:\${NL} run EXACTLY: 'pnpm install'\${NL} Fix Option 3: LAST RESORT, only to unblock yourself right now\${NL} run EXACTLY: '\$WP_ADD_CMD'\${NL} then REVERT IT BEFORE YOU COMMIT: 'pnpm remove ${l0_allowlist_1.HOOK_PKG}'. A direct root dependency on ${l0_allowlist_1.HOOK_PKG} violates the umbrella rule - the root manifest depends on @webpieces/webpieces-tooling ALONE - so it must never reach a PR. It unblocks this session; it is not the fix.\${NL} NOT an option: if you removed ${l0_allowlist_1.HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\${NL}\${NL}${exports.NO_CHAINING_RULE}"
413
+ else
414
+ # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
415
+ WP_HEAD="❌ webpieces ai-hooks blocked this call: the webpieces guard bin is not installed."
416
+ REASON="\$WP_HEAD\${NL}\${NL}${(0, rules_config_2.l0GuardHeader)(rules_config_2.L0_FAULT_BIN_MISSING, '1 violation')}\${NL} ${l0_allowlist_1.HOOK_PKG} is declared in package.json but is not installed (\${BIN_NAME} not found)\${NL} → the guards cannot run, so every OTHER tool call is BLOCKED until they can.\${WORKTREE_NOTE}\${NL} → ${(0, rules_config_2.l0MatrixCitation)(rules_config_2.L0_FAULT_BIN_MISSING)}\${NL}\${NL}\${WP_STILL_ALLOWED}\${NL}\${NL} Fix Option 1: (preferred) the only cure - it materializes what package.json already asks for\${NL} run EXACTLY: 'pnpm install'\${NL} NOT an option: if you removed ${l0_allowlist_1.HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\${NL}\${NL}${exports.NO_CHAINING_RULE}"
417
+ fi
418
+ fi`;
419
+ // webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container
420
+ function renderShim() {
421
+ return `#!/bin/sh
422
+ # Managed by @webpieces/agent-workflow-rules (wp-install-ai-hooks) — do not edit. This file is GENERATED from
423
+ # renderShim() and is intentionally VERSION-AGNOSTIC and byte-STABLE across releases: it carries no
424
+ # version stamp, so it only changes when its own logic changes. The installed guards binary is what
425
+ # checks that this committed copy still matches renderShim() (the committed-shim self-guard); if you
426
+ # revert or hand-edit this file the binary fails closed and names the cure. Checked in on purpose so
427
+ # the hook has a stable entry point even when node_modules is absent. Safe to delete along with the
428
+ # matching .claude/settings.json entries if you remove @webpieces/agent-workflow-rules.
429
+ #
430
+ # Usage (wired into .claude/settings.json, ABSOLUTE so the MAIN tree governs every tree):
431
+ # sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh" <bin-name>
432
+ BIN_NAME="$1"
433
+ shift
434
+ # Resolve the tree relative to THIS script (…/<root>/.claude/webpieces/ai-hook.sh → <root>), not the
435
+ # caller's cwd — the hook can be invoked from any directory (a subdir, or a nested clone).
436
+ ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
437
+ # The JSON escapes every deny message below is assembled from (ANSI red, and the newlines that give the
438
+ # deny the same scannable shape formatReport() gives every L1/L2 deny). See ESCAPES_SH's header.
439
+ ${ESCAPES_SH}
440
+ # The BIN is resolved by walking UP from ROOT (as Node does), and BIN_ROOT records which tree supplied
441
+ # it — the version-drift guard below compares THIS tree's pin against THAT tree's installed version.
442
+ ${RESOLVE_BIN_SH}
443
+ ${shim_version_drift_1.VERSION_DRIFT_GUARD_SH}
444
+ # Read the tool payload ONCE, up front. The shim no longer exec's the bin (see RUN_BIN_SH), so it must
445
+ # forward stdin to the bin itself — and it needs the payload again on the fail-closed path below.
446
+ PAYLOAD="$(cat)"
447
+ ${PARSE_PAYLOAD_SH}
448
+ # Best-effort AUDIT TRAIL of what L0 did with this call — every call, not just the broken ones. One
449
+ # tab-separated line per invocation into this TREE's own
450
+ # logs/L0-shim/<session>-<agent|coordinator>-<binName>.log (gitignored), so the
451
+ # observed behaviour can be diffed against the matrix in guards/L0-tooling.md. NEVER breaks or blocks the
452
+ # hook: every write is swallowed, and nothing ever goes to stdout (stdout is the PreToolUse decision
453
+ # channel — a stray byte there would corrupt allow/deny).
454
+ ${shim_audit_log_1.WP_LOG_SH}
455
+ BROKEN_BIN=""
456
+ CRASH_MSG=""
457
+ ${RUN_BIN_SH}
458
+ # Bin missing (fresh clone before install) OR a version drift (stale node_modules) OR the bin is
459
+ # installed but CRASHED (corrupt node_modules). The webpieces guards CANNOT safely run.
460
+ # Before failing closed, peek at the tool payload and let ONLY package-manager install/recovery commands
461
+ # through: the assistant's own Bash tool routes through this hook too, so blocking everything would
462
+ # deadlock the very commands (pnpm install / rm -rf node_modules && pnpm install) that re-enable the
463
+ # guards. A silent exit 0 = "allow" in the PreToolUse protocol; the guards resume once the tree is sane.
464
+ ${TRIAGE_SH}
465
+ ${DENY_REASON_SH}
466
+ ${DENY_EMIT_SH}
467
+ `;
468
+ }
469
+ // Find the repo root that owns the committed shim to heal: walk up from `cwd` (the invocation's
470
+ // actual dir) to the nearest ancestor holding a shim, falling back to $CLAUDE_PROJECT_DIR (which
471
+ // Claude Code exports to hooks) only if the walk finds nothing. cwd-first keeps this correct for a
472
+ // nested clone and testable (a temp root is honoured over the ambient project env). Returns null when
473
+ // no committed shim exists (e.g. a global / absolute install, which has none to heal).
474
+ //
475
+ // Exported for install-entry.ts: on a CORRUPT node_modules, healShim is the only installer step that
476
+ // can still run, so the installer must be able to tell the human whether a committed shim was actually
477
+ // there to re-arm. Pure existsSync walk — never throws, so it needs no try/catch of its own.
478
+ // webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module; it must not depend on DI (install-entry.ts relies on this loading on a corrupt tree).
479
+ function findShimRoot(cwd) {
480
+ let dir = cwd;
481
+ for (;;) {
482
+ if (fs.existsSync(shimPath(dir)))
483
+ return dir;
484
+ const parent = path.dirname(dir);
485
+ if (parent === dir)
486
+ break;
487
+ dir = parent;
488
+ }
489
+ const env = process.env['CLAUDE_PROJECT_DIR'];
490
+ if (env && fs.existsSync(shimPath(env)))
491
+ return env;
492
+ return null;
493
+ }
494
+ // Best-effort: keep the committed shim identical to renderShim() so the fail-closed escape hatch and
495
+ // allowlist never drift. Only rewrites an EXISTING shim (never creates one) so global installs are
496
+ // untouched. NEVER throws — a self-heal must never block or crash a tool call.
497
+ //
498
+ // The overwrite itself is correct and deliberate — shim and binary are two halves of one L0 and MUST
499
+ // come from the same release (see shimStaleRecoveryDecision's header in ../adapters/hook-core).
500
+ //
501
+ // It needs no backup and no notice: the shim is a TRACKED file, so whatever it replaced is already in
502
+ // git — `git diff` shows the rewrite, and a tamper is a working-tree modification git surfaces on its
503
+ // own. In a consistent repo this is a no-op (committed shim already equals renderShim()); it earns its
504
+ // keep on the upgrade path, where bumping the pin and installing leaves the committed shim behind and
505
+ // this quietly brings it forward to be committed.
506
+ // webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container
507
+ function healShim(cwd) {
508
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
509
+ try {
510
+ const root = findShimRoot(cwd);
511
+ if (!root)
512
+ return;
513
+ const target = shimPath(root);
514
+ const desired = renderShim();
515
+ if (fs.readFileSync(target, 'utf8') === desired)
516
+ return;
517
+ fs.writeFileSync(target, desired, { mode: 0o755 });
518
+ fs.chmodSync(target, 0o755);
519
+ }
520
+ catch (err) {
521
+ //const error = toError(err);
522
+ // Ignore: healing is a convenience, not part of the guard decision.
523
+ }
524
+ }
525
+ // ---------------------------------------------------------------------------
526
+ // COMMITTED-SHIM SELF-GUARD — now enforced by the guards BINARY, not the shim (moved 2026-07-24).
527
+ //
528
+ // It used to live in the rendered shim (`cmp -s "$0" "$WP_TEMPLATE"` → fail closed). That was a
529
+ // double-edged fix trap: the shim-matching logic lived IN the committed shim, so a bug in it could
530
+ // only be fixed by regenerating the committed shim — which required passing the buggy shim's own gate
531
+ // (via wp-upgrade-shim). The fix was locked behind the gate it needed to open.
532
+ //
533
+ // The drift guard MUST stay pre-binary (a stale validator can't be trusted to guard itself), but this
534
+ // check's rationale — "don't run possibly-stale shim logic" — evaporates once the check is in the
535
+ // binary: at that point the deciding code is the CURRENT binary from node_modules, not the reverted
536
+ // shim. So the shim now only checks drift + bin-presence and always hands off; the binary (hook-core)
537
+ // calls committedShimStale() and, on a mismatch, fails closed with shimStaleDenyReason() — the SAME
538
+ // OPTION 1/2/3 message — while isShimCureCommand() lets the three cures through so the AI self-heals.
539
+ // We deny + tell the AI; we do NOT silently rewrite the file under it. With the version stamp gone the
540
+ // shim is byte-stable across releases, so this fires only on a genuine logic change or a real tamper.
541
+ // ---------------------------------------------------------------------------
542
+ // The root whose committed shim this BINARY governs — resolved from the RUNNING MODULE's own location,
543
+ // never from process.cwd() and never from $CLAUDE_PROJECT_DIR. Same premise as installedShimRulesVersion()
544
+ // below: the binary IS this package, so it can point at its OWN install.
545
+ //
546
+ // WHY IT MUST BE THE MODULE AND NOT THE CWD (the two-tree straddle, fixed 2026-08-03).
547
+ // committedShimStale used to resolve its root by walking up from the invocation cwd, then compare that
548
+ // tree's shim FILE against renderShim() — which is compiled into whichever binary is actually running.
549
+ //
550
+ // Which tree supplies the binary? settings.json runs $CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh,
551
+ // and that shim derives ROOT (hence BIN) from its own $0 — so the SESSION ROOT's tree supplies BOTH the
552
+ // shim and the binary, and that pair is self-consistent by construction. A session rooted in a linked
553
+ // worktree runs the worktree's shim and the worktree's binary; that is fine and is NOT the bug.
554
+ //
555
+ // The straddle appears when an agent's SESSION ROOT and its CWD are different trees — CLAUDE_PROJECT_DIR
556
+ // is fixed at session start, so an agent that `cd`s into another checkout keeps running the session-root
557
+ // tree's binary while findShimRoot(cwd) walks up into the OTHER tree. Each tree carries its own
558
+ // node_modules at its own @webpieces version (seen in the wild: 0.4.545, 0.4.560 and 0.4.526 side by
559
+ // side, every tree internally consistent). The comparison then straddles the two and can NEVER converge:
560
+ // curing in the cwd tree renders with THAT tree's renderShim(), which the running binary's renderShim()
561
+ // still rejects, so the cure re-fires the deny forever (observed: an agent gave up after four cures).
562
+ //
563
+ // Anchoring on __dirname makes the straddle UNCONSTRUCTIBLE rather than merely discouraged. It does not
564
+ // pick a tree and privileges none: whichever tree the running binary came from is the tree whose shim it
565
+ // compares, so the two halves of the comparison provably come from the same install either way.
566
+ //
567
+ // OUTERMOST node_modules wins, not innermost: under pnpm's linked layout __dirname realpaths to
568
+ // <root>/node_modules/.pnpm/@webpieces+agent-workflow-rules@X/node_modules/@webpieces/agent-workflow-rules/src/bin —
569
+ // the outermost segment lands on <root>, an innermost/first-ancestor rule lands inside the store.
570
+ // With no node_modules segment at all we are running from a SOURCE checkout (vitest via tsconfig paths),
571
+ // so walk up to the nearest ancestor that owns a shim. null = no committed shim to guard.
572
+ // webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module, beside findShimRoot/healShim.
573
+ function governingShimRoot(moduleDir = __dirname) {
574
+ const segments = moduleDir.split(path.sep);
575
+ const outermost = segments.indexOf('node_modules');
576
+ if (outermost > 0) {
577
+ const root = segments.slice(0, outermost).join(path.sep);
578
+ return fs.existsSync(shimPath(root)) ? root : null;
579
+ }
580
+ // A moduleDir that STARTS with node_modules is relative, so the root before it would be '' — i.e.
581
+ // cwd-relative, the exact input this function exists to refuse. Nothing to govern.
582
+ if (outermost === 0)
583
+ return null;
584
+ let dir = moduleDir;
585
+ for (;;) {
586
+ if (fs.existsSync(shimPath(dir)))
587
+ return dir;
588
+ const parent = path.dirname(dir);
589
+ if (parent === dir)
590
+ return null;
591
+ dir = parent;
592
+ }
593
+ }
594
+ // True when a committed shim EXISTS but no longer equals renderShim() (reverted, hand-edited, or a shim
595
+ // whose LOGIC predates the installed binary). Missing shim → false: a fresh clone / global install has
596
+ // nothing to guard, matching the old shim's `[ -f "$WP_TEMPLATE" ]` skip. Same comparison healShim
597
+ // makes; never throws (an unreadable tree is treated as "not stale" so it can't wedge a tool call).
598
+ //
599
+ // The root defaults to governingShimRoot() — the decision's input is the MODULE's tree, never the cwd
600
+ // (see governingShimRoot for the straddle this closes). The parameter exists ONLY so unit tests can
601
+ // stage a temp root; nothing in production should pass one.
602
+ // webpieces-disable no-function-outside-class -- pure fs+path helper in the shim module, beside healShim/renderShim.
603
+ function committedShimStale(root = governingShimRoot()) {
604
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
605
+ try {
606
+ if (root === null)
607
+ return false;
608
+ return fs.readFileSync(shimPath(root), 'utf8') !== renderShim();
609
+ }
610
+ catch (err) {
611
+ const error = (0, to_error_1.toError)(err);
612
+ void error; // best-effort: an unreadable tree counts as "not stale" so this never wedges a tool call
613
+ return false;
614
+ }
615
+ }
616
+ // True when `command` re-arms the committed shim — the two prescribed cures plus the installer, which
617
+ // also heals the shim as its first step. These are the only commands allowed through while a stale
618
+ // committed shim blocks everything else, so the AI can re-arm it. Each JS twin already tolerates
619
+ // a trailing `2>&1 | tail -N` and rejects any `&&`-chained tail (see CAPTURE_TAIL_JS_SRC).
620
+ // webpieces-disable no-function-outside-class -- pure predicate over the exported allowlist twins; belongs beside them in the shim module.
621
+ function isShimCureCommand(command) {
622
+ const cmd = command.trim();
623
+ return l0_allowlist_1.INSTALL_HOOKS_ALLOW_JS.test(cmd) || l0_allowlist_1.UPGRADE_SHIM_ALLOW_JS.test(cmd) || l0_allowlist_1.RESTORE_SHIM_ALLOW_JS.test(cmd);
624
+ }
625
+ // The installed @webpieces/agent-workflow-rules version, for shimStaleDenyReason's note. The binary IS this
626
+ // package, so it reads its OWN package.json (two dirs up from src/bin). Best-effort: '' on any failure,
627
+ // which shimStaleDenyReason renders as no note rather than a broken one.
628
+ // webpieces-disable no-function-outside-class -- pure fs helper beside the shim module's other version plumbing.
629
+ function installedShimRulesVersion() {
630
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
631
+ try {
632
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'));
633
+ return pkg.version ?? '';
634
+ }
635
+ catch (err) {
636
+ const error = (0, to_error_1.toError)(err);
637
+ void error; // best-effort: no readable version → shimStaleDenyReason prints no note
638
+ return '';
639
+ }
640
+ }
641
+ //# sourceMappingURL=shim.js.map