@countinghouse/ch-local 0.0.0-stage → 1.0.0

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 (262) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +361 -2
  3. package/bin/ch-local.js +472 -0
  4. package/clients/claude-code/.claude-plugin/plugin.json +6 -0
  5. package/clients/claude-code/.mcp.json +11 -0
  6. package/clients/claude-code/bin/launch.js +235 -0
  7. package/clients/claude-code/bin/win-acl.js +420 -0
  8. package/clients/claude-code/skills/ci-failure-triage/SKILL.md +21 -0
  9. package/clients/claude-code/skills/countinghouse-module/SKILL.md +177 -0
  10. package/clients/claude-code/skills/countinghouse-setup/SKILL.md +74 -0
  11. package/lib/allowlist.js +65 -0
  12. package/lib/aside.js +16 -0
  13. package/lib/atomic.js +45 -0
  14. package/lib/auto-apply.js +245 -0
  15. package/lib/auto-upgrade.js +98 -0
  16. package/lib/availability.js +307 -0
  17. package/lib/ceiling.js +280 -0
  18. package/lib/clean-text.js +20 -0
  19. package/lib/cli-change.js +38 -0
  20. package/lib/client-conditions-fixtures.js +143 -0
  21. package/lib/client-conditions.js +656 -0
  22. package/lib/clients.js +179 -0
  23. package/lib/command-line.js +202 -0
  24. package/lib/conditions-command.js +116 -0
  25. package/lib/control.js +134 -0
  26. package/lib/credential-store.js +414 -0
  27. package/lib/credentials-command.js +344 -0
  28. package/lib/daemon-requests.js +137 -0
  29. package/lib/daemon.js +888 -0
  30. package/lib/describe-module.js +137 -0
  31. package/lib/description-check.js +175 -0
  32. package/lib/failed-json.js +43 -0
  33. package/lib/gc.js +274 -0
  34. package/lib/github-token.js +57 -0
  35. package/lib/handoff-io.js +73 -0
  36. package/lib/held-back.js +116 -0
  37. package/lib/hidden-input.js +64 -0
  38. package/lib/history.js +49 -0
  39. package/lib/home.js +372 -0
  40. package/lib/in-place.js +1036 -0
  41. package/lib/install-plan.js +142 -0
  42. package/lib/install.js +846 -0
  43. package/lib/installed-description.js +153 -0
  44. package/lib/integrity.js +7 -0
  45. package/lib/lock.js +456 -0
  46. package/lib/lockfile-rules.js +98 -0
  47. package/lib/machine.js +20 -0
  48. package/lib/module-credentials.js +403 -0
  49. package/lib/module-record.js +298 -0
  50. package/lib/module-roles.js +44 -0
  51. package/lib/module-seams.js +26 -0
  52. package/lib/module-store.js +202 -0
  53. package/lib/module-values.js +334 -0
  54. package/lib/names.js +31 -0
  55. package/lib/next-steps.js +8 -0
  56. package/lib/node-check.js +56 -0
  57. package/lib/npm-fetch.js +123 -0
  58. package/lib/npm-release.js +99 -0
  59. package/lib/npm-upgrade.js +146 -0
  60. package/lib/npm.js +41 -0
  61. package/lib/outside-edits.js +162 -0
  62. package/lib/own-applied.js +175 -0
  63. package/lib/own-command.js +380 -0
  64. package/lib/own-file.js +120 -0
  65. package/lib/own-record.js +96 -0
  66. package/lib/own-tree.js +336 -0
  67. package/lib/pack-table.js +290 -0
  68. package/lib/packs-command.js +570 -0
  69. package/lib/packs.js +219 -0
  70. package/lib/pins.js +64 -0
  71. package/lib/pipe-probe.js +82 -0
  72. package/lib/plain-read.js +63 -0
  73. package/lib/private-file.js +90 -0
  74. package/lib/private-write.js +33 -0
  75. package/lib/provenance.js +234 -0
  76. package/lib/record.js +82 -0
  77. package/lib/registry.js +22 -0
  78. package/lib/release-pins.js +350 -0
  79. package/lib/release-pins.json +4225 -0
  80. package/lib/release-tags.js +12 -0
  81. package/lib/release.js +36 -0
  82. package/lib/restart-command.js +161 -0
  83. package/lib/rollback.js +227 -0
  84. package/lib/run-liveness.js +15 -0
  85. package/lib/runtime-log.js +287 -0
  86. package/lib/sandbox-support.js +17 -0
  87. package/lib/semver-order.js +40 -0
  88. package/lib/session-socket.js +69 -0
  89. package/lib/session-table.js +238 -0
  90. package/lib/session.js +281 -0
  91. package/lib/settings-command.js +82 -0
  92. package/lib/settings.js +564 -0
  93. package/lib/shim-binary.js +152 -0
  94. package/lib/shim-config.js +159 -0
  95. package/lib/shim-install.js +365 -0
  96. package/lib/sigstore/README.md +44 -0
  97. package/lib/sigstore/npm-keys.json +18 -0
  98. package/lib/sigstore/trusted-root.json +126 -0
  99. package/lib/snippets.js +76 -0
  100. package/lib/start.js +721 -0
  101. package/lib/store-files.js +48 -0
  102. package/lib/store-paths.js +33 -0
  103. package/lib/swap-preload.js +38 -0
  104. package/lib/tar.js +220 -0
  105. package/lib/uninstall.js +314 -0
  106. package/lib/unpack.js +41 -0
  107. package/lib/upgrade-stamp.js +63 -0
  108. package/lib/upgrade.js +281 -0
  109. package/lib/watch.js +40 -0
  110. package/lib/win-acl.js +420 -0
  111. package/node_modules/@sigstore/bundle/LICENSE +202 -0
  112. package/node_modules/@sigstore/bundle/README.md +19 -0
  113. package/node_modules/@sigstore/bundle/dist/build.d.ts +18 -0
  114. package/node_modules/@sigstore/bundle/dist/build.js +100 -0
  115. package/node_modules/@sigstore/bundle/dist/bundle.d.ts +74 -0
  116. package/node_modules/@sigstore/bundle/dist/bundle.js +24 -0
  117. package/node_modules/@sigstore/bundle/dist/error.d.ts +4 -0
  118. package/node_modules/@sigstore/bundle/dist/error.js +25 -0
  119. package/node_modules/@sigstore/bundle/dist/index.d.ts +8 -0
  120. package/node_modules/@sigstore/bundle/dist/index.js +43 -0
  121. package/node_modules/@sigstore/bundle/dist/serialized.d.ts +74 -0
  122. package/node_modules/@sigstore/bundle/dist/serialized.js +49 -0
  123. package/node_modules/@sigstore/bundle/dist/utility.d.ts +14 -0
  124. package/node_modules/@sigstore/bundle/dist/utility.js +2 -0
  125. package/node_modules/@sigstore/bundle/dist/validate.d.ts +7 -0
  126. package/node_modules/@sigstore/bundle/dist/validate.js +199 -0
  127. package/node_modules/@sigstore/bundle/package.json +35 -0
  128. package/node_modules/@sigstore/core/LICENSE +202 -0
  129. package/node_modules/@sigstore/core/README.md +10 -0
  130. package/node_modules/@sigstore/core/dist/asn1/error.d.ts +4 -0
  131. package/node_modules/@sigstore/core/dist/asn1/error.js +24 -0
  132. package/node_modules/@sigstore/core/dist/asn1/index.d.ts +1 -0
  133. package/node_modules/@sigstore/core/dist/asn1/index.js +20 -0
  134. package/node_modules/@sigstore/core/dist/asn1/length.d.ts +3 -0
  135. package/node_modules/@sigstore/core/dist/asn1/length.js +62 -0
  136. package/node_modules/@sigstore/core/dist/asn1/obj.d.ts +14 -0
  137. package/node_modules/@sigstore/core/dist/asn1/obj.js +155 -0
  138. package/node_modules/@sigstore/core/dist/asn1/parse.d.ts +6 -0
  139. package/node_modules/@sigstore/core/dist/asn1/parse.js +124 -0
  140. package/node_modules/@sigstore/core/dist/asn1/tag.d.ts +16 -0
  141. package/node_modules/@sigstore/core/dist/asn1/tag.js +89 -0
  142. package/node_modules/@sigstore/core/dist/crypto.d.ts +6 -0
  143. package/node_modules/@sigstore/core/dist/crypto.js +69 -0
  144. package/node_modules/@sigstore/core/dist/dsse.d.ts +1 -0
  145. package/node_modules/@sigstore/core/dist/dsse.js +29 -0
  146. package/node_modules/@sigstore/core/dist/encoding.d.ts +2 -0
  147. package/node_modules/@sigstore/core/dist/encoding.js +27 -0
  148. package/node_modules/@sigstore/core/dist/index.d.ts +9 -0
  149. package/node_modules/@sigstore/core/dist/index.js +66 -0
  150. package/node_modules/@sigstore/core/dist/json.d.ts +1 -0
  151. package/node_modules/@sigstore/core/dist/json.js +60 -0
  152. package/node_modules/@sigstore/core/dist/oid.d.ts +3 -0
  153. package/node_modules/@sigstore/core/dist/oid.js +20 -0
  154. package/node_modules/@sigstore/core/dist/pem.d.ts +2 -0
  155. package/node_modules/@sigstore/core/dist/pem.js +43 -0
  156. package/node_modules/@sigstore/core/dist/rfc3161/error.d.ts +2 -0
  157. package/node_modules/@sigstore/core/dist/rfc3161/error.js +21 -0
  158. package/node_modules/@sigstore/core/dist/rfc3161/index.d.ts +1 -0
  159. package/node_modules/@sigstore/core/dist/rfc3161/index.js +20 -0
  160. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.d.ts +36 -0
  161. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +212 -0
  162. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.d.ts +12 -0
  163. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +72 -0
  164. package/node_modules/@sigstore/core/dist/stream.d.ts +21 -0
  165. package/node_modules/@sigstore/core/dist/stream.js +117 -0
  166. package/node_modules/@sigstore/core/dist/x509/cert.d.ts +43 -0
  167. package/node_modules/@sigstore/core/dist/x509/cert.js +245 -0
  168. package/node_modules/@sigstore/core/dist/x509/ext.d.ts +41 -0
  169. package/node_modules/@sigstore/core/dist/x509/ext.js +146 -0
  170. package/node_modules/@sigstore/core/dist/x509/index.d.ts +2 -0
  171. package/node_modules/@sigstore/core/dist/x509/index.js +23 -0
  172. package/node_modules/@sigstore/core/dist/x509/sct.d.ts +25 -0
  173. package/node_modules/@sigstore/core/dist/x509/sct.js +158 -0
  174. package/node_modules/@sigstore/core/package.json +31 -0
  175. package/node_modules/@sigstore/protobuf-specs/LICENSE +202 -0
  176. package/node_modules/@sigstore/protobuf-specs/README.md +5 -0
  177. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.d.ts +44 -0
  178. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +59 -0
  179. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.d.ts +64 -0
  180. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +174 -0
  181. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.d.ts +74 -0
  182. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +141 -0
  183. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.d.ts +74 -0
  184. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +35 -0
  185. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.d.ts +1309 -0
  186. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +2191 -0
  187. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.d.ts +113 -0
  188. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +29 -0
  189. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.d.ts +23 -0
  190. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js +55 -0
  191. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.d.ts +43 -0
  192. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js +81 -0
  193. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.d.ts +22 -0
  194. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js +56 -0
  195. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.d.ts +35 -0
  196. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js +74 -0
  197. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.d.ts +146 -0
  198. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +103 -0
  199. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.d.ts +304 -0
  200. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +612 -0
  201. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.d.ts +33 -0
  202. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.js +55 -0
  203. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.d.ts +144 -0
  204. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +137 -0
  205. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.d.ts +386 -0
  206. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +284 -0
  207. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.d.ts +191 -0
  208. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +281 -0
  209. package/node_modules/@sigstore/protobuf-specs/dist/index.d.ts +6 -0
  210. package/node_modules/@sigstore/protobuf-specs/dist/index.js +37 -0
  211. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.d.ts +4 -0
  212. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js +35 -0
  213. package/node_modules/@sigstore/protobuf-specs/package.json +35 -0
  214. package/node_modules/@sigstore/verify/README.md +9 -0
  215. package/node_modules/@sigstore/verify/dist/bundle/dsse.d.ts +12 -0
  216. package/node_modules/@sigstore/verify/dist/bundle/dsse.js +44 -0
  217. package/node_modules/@sigstore/verify/dist/bundle/index.d.ts +4 -0
  218. package/node_modules/@sigstore/verify/dist/bundle/index.js +59 -0
  219. package/node_modules/@sigstore/verify/dist/bundle/message.d.ts +13 -0
  220. package/node_modules/@sigstore/verify/dist/bundle/message.js +54 -0
  221. package/node_modules/@sigstore/verify/dist/error.d.ts +16 -0
  222. package/node_modules/@sigstore/verify/dist/error.js +34 -0
  223. package/node_modules/@sigstore/verify/dist/index.d.ts +6 -0
  224. package/node_modules/@sigstore/verify/dist/index.js +28 -0
  225. package/node_modules/@sigstore/verify/dist/key/certificate.d.ts +21 -0
  226. package/node_modules/@sigstore/verify/dist/key/certificate.js +216 -0
  227. package/node_modules/@sigstore/verify/dist/key/index.d.ts +10 -0
  228. package/node_modules/@sigstore/verify/dist/key/index.js +75 -0
  229. package/node_modules/@sigstore/verify/dist/key/sct.d.ts +4 -0
  230. package/node_modules/@sigstore/verify/dist/key/sct.js +78 -0
  231. package/node_modules/@sigstore/verify/dist/policy.d.ts +5 -0
  232. package/node_modules/@sigstore/verify/dist/policy.js +50 -0
  233. package/node_modules/@sigstore/verify/dist/shared.types.d.ts +50 -0
  234. package/node_modules/@sigstore/verify/dist/shared.types.js +2 -0
  235. package/node_modules/@sigstore/verify/dist/timestamp/index.d.ts +11 -0
  236. package/node_modules/@sigstore/verify/dist/timestamp/index.js +24 -0
  237. package/node_modules/@sigstore/verify/dist/timestamp/tsa.d.ts +3 -0
  238. package/node_modules/@sigstore/verify/dist/timestamp/tsa.js +63 -0
  239. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.d.ts +11 -0
  240. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.js +154 -0
  241. package/node_modules/@sigstore/verify/dist/tlog/dsse.d.ts +6 -0
  242. package/node_modules/@sigstore/verify/dist/tlog/dsse.js +106 -0
  243. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.d.ts +6 -0
  244. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +94 -0
  245. package/node_modules/@sigstore/verify/dist/tlog/index.d.ts +5 -0
  246. package/node_modules/@sigstore/verify/dist/tlog/index.js +92 -0
  247. package/node_modules/@sigstore/verify/dist/tlog/intoto.d.ts +3 -0
  248. package/node_modules/@sigstore/verify/dist/tlog/intoto.js +62 -0
  249. package/node_modules/@sigstore/verify/dist/tlog/merkle.d.ts +3 -0
  250. package/node_modules/@sigstore/verify/dist/tlog/merkle.js +104 -0
  251. package/node_modules/@sigstore/verify/dist/tlog/set.d.ts +3 -0
  252. package/node_modules/@sigstore/verify/dist/tlog/set.js +60 -0
  253. package/node_modules/@sigstore/verify/dist/trust/filter.d.ts +8 -0
  254. package/node_modules/@sigstore/verify/dist/trust/filter.js +23 -0
  255. package/node_modules/@sigstore/verify/dist/trust/index.d.ts +5 -0
  256. package/node_modules/@sigstore/verify/dist/trust/index.js +90 -0
  257. package/node_modules/@sigstore/verify/dist/trust/trust.types.d.ts +29 -0
  258. package/node_modules/@sigstore/verify/dist/trust/trust.types.js +2 -0
  259. package/node_modules/@sigstore/verify/dist/verifier.d.ts +31 -0
  260. package/node_modules/@sigstore/verify/dist/verifier.js +160 -0
  261. package/node_modules/@sigstore/verify/package.json +36 -0
  262. package/package.json +37 -4
@@ -0,0 +1,656 @@
1
+ 'use strict';
2
+ // Before every dialog (countinghouse part 3 P2, Task 4; plan
3
+ // docs/superpowers/plans/2026-11-14-part3-p2-elicitation.md in countinghouse):
4
+ // may the client be asked to confirm a loosening? The runtime asks start
5
+ // (control may-elicit); start answers from the client's own configuration.
6
+ //
7
+ // The scan follows Claude Code 2.1.323's known parsing (its front matter,
8
+ // its sources); drift in a later version is covered by the exact-version
9
+ // tested list and the automated re-test's surface diff, not by this file.
10
+ //
11
+ // MCP elicitation is not proof of a person: a client's own configuration can
12
+ // answer a dialog for the user. For Claude Code that is any Elicitation or
13
+ // ElicitationResult hook (whatever its matcher: start cannot know the name
14
+ // the user gave this server), a plugin a project brings, or an installed
15
+ // plugin's hook. So the answer is yes only when none is found in any source
16
+ // below, the session says it is an interactive CLI one, and its project
17
+ // directory is known. Anything that cannot be read is no.
18
+ //
19
+ // A list of sources is fail-open by nature: the next Claude Code version may
20
+ // read one more. So what start does not know is no too: a flag on the
21
+ // client's command line that is not on SAFE_FLAGS (known not to touch hooks
22
+ // or plugins), and a CLAUDE_CODE_* variable naming a plugin, settings, hook,
23
+ // managed or policy source that the scan does not handle. And the runtime's
24
+ // tested-client list (countinghouse lib/elicitation-clients.json) names
25
+ // exact tested version ranges, so a new version gets no form until it is
26
+ // re-tested (automatically: lib/client-conditions-fixtures.js holds that
27
+ // harness's fixtures, one per source).
28
+ //
29
+ // A relative --settings, --plugin-dir or --add-dir (the client's own
30
+ // directory is not known for certain) is unreadable: no dialog. A plugin
31
+ // developer running Claude Code with one uses the terminal command instead.
32
+ //
33
+ // The entrypoint gate is a hint for honest unattended hosts only: a session
34
+ // nested under a shell inherits 'cli'. That residual is documented (the
35
+ // plan's Q1: "this start only" is one runtime process).
36
+ const fs = require('node:fs');
37
+ const os = require('node:os');
38
+ const path = require('node:path');
39
+ const {execFile} = require('node:child_process');
40
+
41
+ const MAX_BYTES = 1024 * 1024;
42
+ const MAX_PLUGINS = 2000;
43
+ const MAX_TEXT_FILES = 2000;
44
+ const EVENTS = ['Elicitation', 'ElicitationResult'];
45
+ const CLAUDE_CODE = 'claude-code';
46
+ // the hits, in the order they are said; each holds for the whole start
47
+ const HITS = Object.freeze(['client hook present', 'project plugin or marketplace', 'plugin hook present']);
48
+ const UNREADABLE = 'client settings unreadable';
49
+ // every reason a verdict of no can carry: a closed set, so a why that leaves
50
+ // this process (the conditions line) is never free text
51
+ const REASONS = Object.freeze([...HITS, UNREADABLE, 'no conditions known', 'not an interactive session', 'project directory unknown']);
52
+
53
+ const MANAGED = {
54
+ darwin: '/Library/Application Support/ClaudeCode/managed-settings.json',
55
+ linux: '/etc/claude-code/managed-settings.json',
56
+ win32: 'C:\\Program Files\\ClaudeCode\\managed-settings.json'
57
+ };
58
+ // Other managed sources (said by the reviews of Task 4; checked by the
59
+ // re-test): read as JSON when they are JSON; when they are not (a
60
+ // configuration profile, a policy key), present is unreadable, so no form.
61
+ const MANAGED_JSON_ALSO = {win32: ['C:\\ProgramData\\ClaudeCode\\managed-settings.json']};
62
+ const MANAGED_WSL = '/mnt/c/Program Files/ClaudeCode/managed-settings.json';
63
+ const MANAGED_PRESENT = {darwin: ['/Library/Managed Preferences/com.anthropic.claudecode.plist']};
64
+
65
+ // The client's flags known not to add a hook or a plugin. Any other flag
66
+ // (one a new version adds) is unreadable. A flag's value is never checked
67
+ // here: a token that does not start with '-' is a value or the prompt.
68
+ const SAFE_FLAGS = new Set([
69
+ '--resume', '-r', '--continue', '-c', '--model', '--fallback-model', '--verbose', '--debug', '-d', '--mcp-debug',
70
+ '--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools',
71
+ '--mcp-config', '--strict-mcp-config', '--append-system-prompt', '--system-prompt', '--session-id', '--fork-session',
72
+ '--ide', '--setting-sources', '--version', '-v', '--help', '-h'
73
+ ]);
74
+ // The flags the scan reads (on any ancestor's command line), and those that
75
+ // are unreadable whatever their value.
76
+ const SCANNED_FLAGS = {'--settings': 'settings', '--managed-settings': 'settings', '--plugin-dir': 'pluginDirs', '--plugin-dir-no-mcp': 'pluginDirs', '--add-dir': 'addDirs'};
77
+ const UNREADABLE_FLAGS = new Set(['--plugin-url']);
78
+
79
+ // Environment: the plugin sources the scan reads, those it cannot, and the
80
+ // rule for any other.
81
+ // Names compared in upper case (Windows' environment is case-insensitive).
82
+ const ENV_SCANNED = new Set(['CLAUDE_CODE_PLUGIN_CACHE_DIR', 'CLAUDE_CODE_PLUGIN_DIRS', 'CLAUDE_CODE_PLUGIN_SEED_DIR', 'CLAUDE_CONFIG_DIR']);
83
+ const ENV_UNREADABLE = new Set(['CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE', 'CLAUDE_CODE_USE_COWORK_PLUGINS']);
84
+ // What Claude Code (2.1.326-2.1.330, read in its binary) sets for a plugin's
85
+ // own process -- its stdio MCP server, a hook: CLAUDE_PLUGIN_ROOT, the
86
+ // plugin's directory, known only when it is one of the plugins the scan
87
+ // reads (below); CLAUDE_PLUGIN_DATA, the plugin's data directory
88
+ // (<plugins>/data/<id>, only ever handed to the plugin's processes, never
89
+ // loaded from). Each by its exact name; any other CLAUDE_PLUGIN_* is still
90
+ // unreadable -- CLAUDE_PLUGIN_OPTION_<KEY> among them: set only in a hook's
91
+ // environment, so it says this process descends from a hook. In the process environment only: a settings file's env block
92
+ // naming them stays unreadable.
93
+ const ENV_PLUGIN_OWN = new Set(['CLAUDE_PLUGIN_ROOT', 'CLAUDE_PLUGIN_DATA']);
94
+ const envRisky = (name) => /^CLAUDE_/.test(String(name).toUpperCase())
95
+ && /(PLUGIN|SETTINGS|HOOK|MANAGED|POLICY|SKILL|MARKETPLACE|MODS|CONFIG_DIR)/.test(String(name).toUpperCase());
96
+
97
+ class Unreadable extends Error {}
98
+
99
+ // CLAUDE_PLUGIN_ROOT, a plugin the scan reads: absolute, named by its own
100
+ // real path (no link: a manifest's relative hook paths resolve from it), and
101
+ // that real path one of the scanned plugins' -> true, or false. Compared as
102
+ // the platform's file system compares names: on Windows and macOS without
103
+ // case (Claude Code may hand over `c:\…` where the real path says `C:\…`),
104
+ // separators made one by resolve; a link, or a Windows short name, differs
105
+ // by more than case and is still refused. And the same file (dev and inode,
106
+ // as bigints): on a case-sensitive volume (a macOS APFS one) two names that
107
+ // differ only by case are two directories
108
+ function pluginRootScanned(given, plugins, platform = process.platform) {
109
+ if (typeof given !== 'string' || !path.isAbsolute(given)) return false;
110
+ const same = (a, b) => ((platform === 'win32' || platform === 'darwin') ? a.toLowerCase() === b.toLowerCase() : a === b);
111
+ let real;
112
+ try { real = path.resolve(fs.realpathSync.native(given)); } catch (err) { return false; }
113
+ if (!same(real, path.resolve(given))) return false;
114
+ const id = (p) => { try { const st = fs.statSync(p, {bigint: true}); return `${st.dev}:${st.ino}`; } catch (err) { return null; } };
115
+ const mine = id(real);
116
+ if (mine == null) return false;
117
+ for (const d of plugins) {
118
+ let r;
119
+ try { r = path.resolve(fs.realpathSync.native(d)); } catch (err) { continue; }
120
+ // (two kernel real paths, compared as they are, and the same file)
121
+ if (r === real && id(r) === mine) return true;
122
+ }
123
+ return false;
124
+ }
125
+
126
+ // A file's bytes as text: null when it does not exist, or Unreadable.
127
+ function readText(file) {
128
+ let st;
129
+ try { st = fs.statSync(file); } catch (err) {
130
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;
131
+ throw new Unreadable(file);
132
+ }
133
+ if (!st.isFile() || st.size > MAX_BYTES) throw new Unreadable(file);
134
+ try { return fs.readFileSync(file, 'utf8'); } catch (err) { throw new Unreadable(file); }
135
+ }
136
+
137
+ // A JSON file: its value, null when it does not exist, or Unreadable.
138
+ function readJson(file) {
139
+ const text = readText(file);
140
+ if (text == null) return null;
141
+ try { return JSON.parse(text); } catch (err) { throw new Unreadable(file); }
142
+ }
143
+
144
+ // A directory's subdirectories (or files), a symlink to one included: []
145
+ // when it does not exist, or Unreadable (an entry that cannot be told counts).
146
+ function list(dir, {files = false} = {}) {
147
+ let names;
148
+ try { names = fs.readdirSync(dir); } catch (err) {
149
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return [];
150
+ throw new Unreadable(dir);
151
+ }
152
+ const out = [];
153
+ for (const n of names) {
154
+ const p = path.join(dir, n);
155
+ let st;
156
+ try { st = fs.statSync(p); } catch (err) { throw new Unreadable(p); }
157
+ if (files ? st.isFile() : st.isDirectory()) out.push(p);
158
+ }
159
+ return out;
160
+ }
161
+
162
+ const isObject = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
163
+
164
+ // A hooks configuration, as a settings file or hooks.json has it ({hooks:
165
+ // {Event: [...]}}) or inline ({Event: [...]}): any Elicitation or
166
+ // ElicitationResult entry that is not an empty list counts.
167
+ function hasElicitationHook(config) {
168
+ for (const o of [config, isObject(config) ? config.hooks : null]) {
169
+ if (!isObject(o)) continue;
170
+ for (const e of EVENTS) {
171
+ if (Object.prototype.hasOwnProperty.call(o, e) && !(Array.isArray(o[e]) && o[e].length === 0)) return true;
172
+ }
173
+ }
174
+ return false;
175
+ }
176
+
177
+ // A settings object's env block naming a source (a project file can set
178
+ // one): unreadable.
179
+ function envBlockUnreadable(settings) {
180
+ if (!isObject(settings) || settings.env == null) return false;
181
+ if (!isObject(settings.env)) return true;
182
+ return Object.keys(settings.env).some((k) => envRisky(k) || ENV_SCANNED.has(String(k).toUpperCase()) || ENV_UNREADABLE.has(String(k).toUpperCase()));
183
+ }
184
+
185
+ // Markdown a hook may be declared in (skills, agents and commands carry
186
+ // hooks in their front matter): any mention of the events counts, unparsed.
187
+ // What could spell one without the plain word is unreadable: a NUL or a
188
+ // UTF-16 byte-order mark in the file, a backslash in its front matter (a
189
+ // YAML escape), a tree past the depth limit.
190
+ const MD_DEPTH = 8;
191
+ function mdMentions(file) {
192
+ let st;
193
+ try { st = fs.statSync(file); } catch (err) {
194
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return false;
195
+ throw new Unreadable(file);
196
+ }
197
+ if (!st.isFile() || st.size > MAX_BYTES) throw new Unreadable(file);
198
+ let bytes;
199
+ try { bytes = fs.readFileSync(file); } catch (err) { throw new Unreadable(file); }
200
+ if (bytes.includes(0) || (bytes.length >= 2 && ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)))) throw new Unreadable(file);
201
+ const text = bytes.toString('utf8');
202
+ if (EVENTS.some((e) => text.includes(e))) return true;
203
+ // front matter as broadly as any parser could take it (2.1.323's is
204
+ // /^---\s*\n([\s\S]*?)---\s*\n?/): after a byte-order mark and leading
205
+ // white space, a '---' opens it, whatever follows on its line, and it runs
206
+ // to the next '---' anywhere, or to the end
207
+ const lead = text.replace(/^\uFEFF/, '').replace(/^\s*/, '');
208
+ if (lead.startsWith('---')) {
209
+ const rest = lead.slice(3);
210
+ const end = rest.indexOf('---');
211
+ if ((end === -1 ? rest : rest.slice(0, end)).includes('\\')) throw new Unreadable(file);
212
+ }
213
+ return false;
214
+ }
215
+ // Every *.md under dir, to MD_DEPTH (past it: unreadable, never skipped).
216
+ function mdFiles(dir, count, depth = 0) {
217
+ if (depth > MD_DEPTH) throw new Unreadable(dir);
218
+ const out = [];
219
+ for (const f of list(dir, {files: true})) {
220
+ if (!f.toLowerCase().endsWith('.md')) continue;
221
+ count.n += 1;
222
+ if (count.n > MAX_TEXT_FILES) throw new Unreadable(dir);
223
+ out.push(f);
224
+ }
225
+ for (const sub of list(dir)) { if (path.basename(sub) !== '.git') out.push(...mdFiles(sub, count, depth + 1)); }
226
+ return out;
227
+ }
228
+ // A .claude directory's skills, agents and commands.
229
+ function textMentions(dir, count) {
230
+ for (const sub of ['skills', 'agents', 'commands']) {
231
+ for (const f of mdFiles(path.join(dir, sub), count)) if (mdMentions(f)) return true;
232
+ }
233
+ return false;
234
+ }
235
+
236
+ // One plugin's directory: its hooks/hooks.json, plugin.json's inline hooks,
237
+ // every hook file plugin.json lists (one that is missing: unreadable), and
238
+ // every *.md in its whole tree (its skills, agents and commands, wherever
239
+ // plugin.json points them).
240
+ function pluginHasHook(dir, count) {
241
+ if (hasElicitationHook(readJson(path.join(dir, 'hooks', 'hooks.json')))) return true;
242
+ const manifest = readJson(path.join(dir, '.claude-plugin', 'plugin.json'));
243
+ if (isObject(manifest) && manifest.hooks != null) {
244
+ for (const h of Array.isArray(manifest.hooks) ? manifest.hooks : [manifest.hooks]) {
245
+ if (typeof h === 'string') {
246
+ const config = readJson(path.resolve(dir, h));
247
+ if (config == null) throw new Unreadable(h);
248
+ if (hasElicitationHook(config)) return true;
249
+ } else if (hasElicitationHook(h)) {
250
+ return true;
251
+ }
252
+ }
253
+ }
254
+ for (const f of mdFiles(dir, count)) if (mdMentions(f)) return true;
255
+ return false;
256
+ }
257
+
258
+ // A token naming the client: Claude Code's native binary (claude,
259
+ // claude.exe) or its npm package (a path with claude-code).
260
+ const isClientToken = (a) => {
261
+ const base = path.basename(String(a).replace(/\\/g, '/')).toLowerCase();
262
+ return /^claude(\.exe|\.cmd)?$/.test(base) || /claude-code/i.test(String(a));
263
+ };
264
+
265
+ // Flags from every ancestor's command line: the scanned ones, anything
266
+ // unreadable, and after the client's own token (wherever it sits) any flag
267
+ // not known safe. Never stopped at '--' (macOS splits a command line on
268
+ // whitespace, so a prompt's own '--' could hide a later flag). --add-dir
269
+ // takes every following token that is not a flag.
270
+ const VARIADIC = new Set(['--add-dir']);
271
+ function flagsOf(lines) {
272
+ const out = {settings: [], pluginDirs: [], addDirs: [], unreadable: false};
273
+ for (const argv of lines) {
274
+ if (!Array.isArray(argv) || argv.some((a) => typeof a !== 'string')) { out.unreadable = true; continue; }
275
+ const at = argv.findIndex(isClientToken);
276
+ for (let i = 0; i < argv.length; i++) {
277
+ const t = argv[i];
278
+ if (!t.startsWith('-') || t === '-' || t === '--') continue;
279
+ const eq = t.indexOf('=');
280
+ const name = eq === -1 ? t : t.slice(0, eq);
281
+ if (Object.prototype.hasOwnProperty.call(SCANNED_FLAGS, name)) {
282
+ const into = out[SCANNED_FLAGS[name]];
283
+ if (eq !== -1) {
284
+ into.push(t.slice(eq + 1));
285
+ } else if (VARIADIC.has(name)) {
286
+ let n = 0;
287
+ while (i + 1 < argv.length && !argv[i + 1].startsWith('-')) { into.push(argv[i + 1]); i += 1; n += 1; }
288
+ if (n === 0) out.unreadable = true;
289
+ } else if (i + 1 < argv.length) {
290
+ into.push(argv[i + 1]);
291
+ i += 1;
292
+ } else {
293
+ out.unreadable = true;
294
+ }
295
+ } else if (UNREADABLE_FLAGS.has(name)) {
296
+ out.unreadable = true;
297
+ } else if (at !== -1 && i > at && !SAFE_FLAGS.has(name)) {
298
+ out.unreadable = true; // a flag start does not know
299
+ }
300
+ }
301
+ }
302
+ return out;
303
+ }
304
+
305
+ // dir and every directory above it, up to the filesystem root, or up to
306
+ // stopAt (included) when dir is inside it: a test's own world, so the walk
307
+ // never reaches the developer's real home whatever the temp directory
308
+ const ancestorsOf = (dir, stopAt = null) => {
309
+ const out = [];
310
+ const stop = stopAt != null ? path.resolve(stopAt) : null;
311
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
312
+ out.push(d);
313
+ if (d === stop || path.dirname(d) === d) return out;
314
+ }
315
+ };
316
+
317
+ // Directories from depth 0 (root itself) to `depth` below it.
318
+ function dirsUnder(root, depth) {
319
+ const out = [root];
320
+ let level = [root];
321
+ for (let d = 0; d < depth; d++) {
322
+ const next = [];
323
+ for (const dir of level) next.push(...list(dir));
324
+ if (out.length + next.length > MAX_PLUGINS) throw new Unreadable(root);
325
+ out.push(...next);
326
+ level = next;
327
+ }
328
+ return out;
329
+ }
330
+
331
+ // parentCommandLines: the client's ancestry as clientLines gives it (start
332
+ // reads it once, asynchronously: readClientContext). managedPresent: a
333
+ // managed source start cannot read (a policy key). Any error is no.
334
+ function clientConditions(args = {}) {
335
+ try {
336
+ return scan(args);
337
+ } catch (err) {
338
+ return {mayElicit: false, why: UNREADABLE};
339
+ }
340
+ }
341
+
342
+ // stopAt: tests only, their own temp root: the walk up from the project
343
+ // stops there. withAt: a hit's verdict also says where it was first seen (`at`: a file or
344
+ // directory, or null), for the conditions line's why; otherwise the verdict
345
+ // is {mayElicit, why} alone
346
+ function scan({client, home = os.homedir(), cwd, env = process.env, platform = process.platform, managedFile, managedPresent = false, parentCommandLines = () => null, withAt = false, stopAt = null} = {}) {
347
+ if (client == null || client.name !== CLAUDE_CODE) return {mayElicit: false, why: 'no conditions known'};
348
+ if (env.CLAUDE_CODE_ENTRYPOINT !== 'cli' || env.CLAUDECODE !== '1') return {mayElicit: false, why: 'not an interactive session'};
349
+ const projectDir = env.CLAUDE_PROJECT_DIR;
350
+ let projectOk = false;
351
+ try { projectOk = typeof projectDir === 'string' && path.isAbsolute(projectDir) && fs.statSync(projectDir).isDirectory(); } catch (err) { projectOk = false; }
352
+ if (!projectOk) return {mayElicit: false, why: 'project directory unknown'};
353
+
354
+ const found = new Set();
355
+ // where each hit was first seen (a file or a directory), for the why
356
+ const firstAt = new Map();
357
+ const hit = (why, at = null) => { found.add(why); if (!firstAt.has(why) && typeof at === 'string') firstAt.set(why, at); };
358
+ // a cwd removed or unknown; a managed source start cannot read
359
+ let unreadable = typeof cwd !== 'string' || !path.isAbsolute(cwd) || managedPresent === true;
360
+ const attempt = (fn) => {
361
+ try { fn(); } catch (err) {
362
+ if (err instanceof Unreadable) unreadable = true; else throw err;
363
+ }
364
+ };
365
+ const count = {n: 0};
366
+ const sameDir = (a, b) => ((platform === 'win32' || platform === 'darwin') ? a.toLowerCase() === b.toLowerCase() : a === b);
367
+
368
+ // the environment: a source the scan does not know is unreadable
369
+ for (const [k, v] of Object.entries(env)) {
370
+ if (v == null || v === '') continue;
371
+ const K = String(k).toUpperCase();
372
+ // (the plugin's own, by its exact name: known; ROOT and DATA absolute)
373
+ if (K === k && ENV_PLUGIN_OWN.has(K)) {
374
+ if (!path.isAbsolute(v)) unreadable = true;
375
+ continue;
376
+ }
377
+ if (ENV_UNREADABLE.has(K) || (envRisky(K) && !ENV_SCANNED.has(K))) unreadable = true;
378
+ if (ENV_SCANNED.has(K) && K !== k) unreadable = true; // read by its exact name below: another spelling is not
379
+ }
380
+ if (env.CLAUDE_CONFIG_DIR && !path.isAbsolute(env.CLAUDE_CONFIG_DIR)) unreadable = true;
381
+ const configDir = path.resolve(env.CLAUDE_CONFIG_DIR ? env.CLAUDE_CONFIG_DIR : path.join(home, '.claude'));
382
+
383
+ // the command lines (every ancestor's; the client's own against SAFE_FLAGS)
384
+ let lines = null;
385
+ try { lines = parentCommandLines(); } catch (err) { lines = null; }
386
+ const flags = Array.isArray(lines) ? flagsOf(lines) : {settings: [], pluginDirs: [], addDirs: [], unreadable: true};
387
+ if (flags.unreadable) unreadable = true;
388
+
389
+ // settings: hooks, a project's plugins, an env block naming a source
390
+ const check = (s, {project = false, file = null} = {}) => {
391
+ if (hasElicitationHook(s)) hit('client hook present', file);
392
+ if (project && isObject(s) && (s.enabledPlugins != null || s.extraKnownMarketplaces != null)) hit('project plugin or marketplace', file);
393
+ if (envBlockUnreadable(s)) unreadable = true;
394
+ };
395
+ const settingsFiles = ['settings.json', 'settings.local.json', 'remote-settings.json'].map((n) => path.join(configDir, n));
396
+ const managed = managedFile || MANAGED[platform] || MANAGED.linux;
397
+ const managedFiles = [managed];
398
+ if (managedFile == null) {
399
+ managedFiles.push(...(MANAGED_JSON_ALSO[platform] || []));
400
+ if (platform === 'linux' && env.WSL_DISTRO_NAME) managedFiles.push(MANAGED_WSL);
401
+ for (const p of MANAGED_PRESENT[platform] || []) { if (fs.existsSync(p)) unreadable = true; }
402
+ }
403
+ for (const m of managedFiles) {
404
+ settingsFiles.push(m);
405
+ attempt(() => {
406
+ const d = path.join(path.dirname(m), 'managed-settings.d');
407
+ let names = [];
408
+ try { names = fs.readdirSync(d).filter((n) => n.endsWith('.json')); } catch (err) {
409
+ if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw new Unreadable(d);
410
+ }
411
+ for (const n of names) settingsFiles.push(path.join(d, n));
412
+ });
413
+ }
414
+ for (const file of settingsFiles) attempt(() => check(readJson(file), {file}));
415
+ // server-managed settings: any mention of the events, anywhere in it
416
+ attempt(() => {
417
+ const text = readText(path.join(configDir, 'remote-settings.json'));
418
+ if (text != null && EVENTS.some((e) => text.includes(e))) hit('client hook present', path.join(configDir, 'remote-settings.json'));
419
+ });
420
+
421
+ // projects: the project's, the cwd's and every --add-dir's .claude, with
422
+ // their ancestors (the user's own .claude, met on the way, read above)
423
+ const dirs = new Set([...ancestorsOf(projectDir, stopAt), ...(typeof cwd === 'string' && path.isAbsolute(cwd) ? ancestorsOf(cwd, stopAt) : [])]);
424
+ for (const d of flags.addDirs) {
425
+ if (!path.isAbsolute(d)) { unreadable = true; continue; }
426
+ for (const a of ancestorsOf(d, stopAt)) dirs.add(a);
427
+ }
428
+ const claudeDirs = [configDir];
429
+ for (const dir of dirs) {
430
+ const claudeDir = path.join(dir, '.claude');
431
+ if (sameDir(path.resolve(claudeDir), configDir)) continue;
432
+ claudeDirs.push(claudeDir);
433
+ for (const n of ['settings.json', 'settings.local.json']) attempt(() => check(readJson(path.join(claudeDir, n)), {project: true, file: path.join(claudeDir, n)}));
434
+ }
435
+ // skills, agents and commands, in the user's and every project's .claude
436
+ for (const d of claudeDirs) attempt(() => { if (textMentions(d, count)) hit('client hook present', d); });
437
+
438
+ // the flags' settings: a file (absolute) or inline JSON
439
+ for (const v of flags.settings) {
440
+ attempt(() => {
441
+ let s;
442
+ if (v.trim().startsWith('{')) {
443
+ try { s = JSON.parse(v); } catch (err) { throw new Unreadable('--settings'); }
444
+ } else {
445
+ if (!path.isAbsolute(v)) throw new Unreadable(v);
446
+ s = readJson(v);
447
+ if (s == null) throw new Unreadable(v); // a flag naming nothing readable
448
+ }
449
+ check(s, {file: v.trim().startsWith('{') ? null : v});
450
+ });
451
+ }
452
+
453
+ // installed plugins' hooks: <root>/cache/<marketplace>/<plugin>/<version>/
454
+ // (the root is CLAUDE_CODE_PLUGIN_CACHE_DIR, or <config>/plugins), every
455
+ // --plugin-dir and CLAUDE_CODE_PLUGIN_DIRS entry with its children, and
456
+ // CLAUDE_CODE_PLUGIN_SEED_DIR to four levels
457
+ attempt(() => {
458
+ const root = env.CLAUDE_CODE_PLUGIN_CACHE_DIR ? env.CLAUDE_CODE_PLUGIN_CACHE_DIR : path.join(configDir, 'plugins');
459
+ if (!path.isAbsolute(root)) throw new Unreadable(root);
460
+ const plugins = [];
461
+ for (const m of list(path.join(root, 'cache'))) for (const p of list(m)) for (const v of list(p)) plugins.push(v);
462
+ const split = (v) => v.split(path.delimiter === ';' ? /[;,]/ : /[:,]/).filter(Boolean);
463
+ const given = [...flags.pluginDirs];
464
+ if (env.CLAUDE_CODE_PLUGIN_DIRS) given.push(...split(env.CLAUDE_CODE_PLUGIN_DIRS));
465
+ for (const d of given) {
466
+ if (!path.isAbsolute(d)) throw new Unreadable(d);
467
+ let isDir = false;
468
+ try { isDir = fs.statSync(d).isDirectory(); } catch (err) { isDir = false; }
469
+ if (!isDir) throw new Unreadable(d);
470
+ plugins.push(...dirsUnder(d, 1)); // a plugin, or a folder of them
471
+ }
472
+ for (const seed of env.CLAUDE_CODE_PLUGIN_SEED_DIR ? split(env.CLAUDE_CODE_PLUGIN_SEED_DIR) : []) {
473
+ if (!path.isAbsolute(seed)) throw new Unreadable(seed);
474
+ plugins.push(...dirsUnder(seed, 4));
475
+ }
476
+ if (plugins.length > MAX_PLUGINS) throw new Unreadable(root);
477
+ for (const d of plugins) attempt(() => { if (pluginHasHook(d, count)) hit('plugin hook present', d); });
478
+ // the plugin this process is (the plugin route's CLAUDE_PLUGIN_ROOT):
479
+ // known only as one of the plugins just scanned, by its real path, and
480
+ // named by it (no link): one anywhere else says the client loads plugins
481
+ // from a place this scan does not read. Never thrown: the plugins above
482
+ // are judged whatever it is
483
+ if (env.CLAUDE_PLUGIN_ROOT && !pluginRootScanned(env.CLAUDE_PLUGIN_ROOT, plugins, platform)) unreadable = true;
484
+ });
485
+
486
+ // at: where it was first seen, when a file or directory (never inline
487
+ // settings), for the conditions line's why
488
+ for (const why of HITS) {
489
+ if (found.has(why)) return withAt ? {mayElicit: false, why, at: firstAt.has(why) ? firstAt.get(why) : null} : {mayElicit: false, why};
490
+ }
491
+ if (unreadable) return {mayElicit: false, why: UNREADABLE};
492
+ return {mayElicit: true, why: null};
493
+ }
494
+
495
+ // A hit holds for the whole start: once a hook (or a project's plugin) has
496
+ // been seen, no dialog until restart, though it is removed (a hook deleted
497
+ // just before a form does not help). Every check re-scans as well.
498
+ function conditionsLatch() {
499
+ let latched = null;
500
+ return (args) => {
501
+ if (latched != null) return {mayElicit: false, why: latched};
502
+ const r = clientConditions(args);
503
+ if (HITS.includes(r.why)) latched = r.why;
504
+ return r;
505
+ };
506
+ }
507
+
508
+ // The client among start's ancestors: every line read (a wrapper above or
509
+ // below the client cannot hide a flag: each is scanned), when one of them is
510
+ // the client; null when none is, or a command line on the way is empty
511
+ // (unread, as on Windows for an elevated process).
512
+ function clientLines(lines) {
513
+ if (!Array.isArray(lines) || lines.length === 0) return null;
514
+ if (lines.some((argv) => !Array.isArray(argv) || argv.length === 0 || argv.every((a) => a === ''))) return null;
515
+ return lines.some((argv) => argv.some(isClientToken)) ? lines : null;
516
+ }
517
+
518
+ // Windows command lines, split as CommandLineToArgvW does (quotes, and
519
+ // backslashes before a quote); a misread names nothing readable, which is no.
520
+ function splitWindows(s) {
521
+ const out = [];
522
+ let cur = '';
523
+ let quoted = false;
524
+ let any = false;
525
+ for (let i = 0; i < s.length; i++) {
526
+ const c = s[i];
527
+ if (c === '\\') {
528
+ let n = 0;
529
+ while (s[i] === '\\') { n++; i++; }
530
+ if (s[i] === '"') { cur += '\\'.repeat(Math.floor(n / 2)); if (n % 2 === 1) { cur += '"'; } else { quoted = !quoted; } any = true; } else { cur += '\\'.repeat(n); i--; any = true; }
531
+ } else if (c === '"') { quoted = !quoted; any = true; } else if (!quoted && (c === ' ' || c === '\t')) {
532
+ if (any) { out.push(cur); cur = ''; any = false; }
533
+ } else { cur += c; any = true; }
534
+ }
535
+ if (any) out.push(cur);
536
+ return out;
537
+ }
538
+
539
+ const run = (cmd, args, timeout) => new Promise((resolve, reject) => {
540
+ execFile(cmd, args, {encoding: 'utf8', timeout, windowsHide: true, maxBuffer: 4 * 1024 * 1024}, (err, out, errOut) => {
541
+ if (err) { err.stdout = out; err.stderr = errOut; reject(err); } else resolve(out);
542
+ });
543
+ });
544
+
545
+ // The command lines of pid and up to `depth` of its ancestors, nearest
546
+ // first: [[argv...], ...], or null when one cannot be read.
547
+ async function readAncestry(pid, depth = 8, platform = process.platform) {
548
+ return (await readClientContext(pid, depth, platform)).lines;
549
+ }
550
+
551
+ // Whether a Claude Code policy key exists, by reg.exe (WSL): present, or a
552
+ // failure to tell, is true.
553
+ async function wslPolicyPresent() {
554
+ for (const hive of ['HKLM', 'HKCU']) {
555
+ try {
556
+ await run('reg.exe', ['query', `${hive}\\SOFTWARE\\Policies\\ClaudeCode`], 10000);
557
+ return true; // found
558
+ } catch (err) {
559
+ // reg.exe exits 1 and says so when the key is not there
560
+ if (!(err && err.code === 1 && /unable to find/i.test(String(err.stderr || '') + String(err.stdout || '')))) return true;
561
+ }
562
+ }
563
+ return false;
564
+ }
565
+
566
+ // The ancestry, and whether a managed source start cannot read is present
567
+ // (on Windows, and under WSL, a Claude Code policy key: HKLM or HKCU
568
+ // \SOFTWARE\Policies\ClaudeCode; whether Claude Code reads hooks from it is
569
+ // on the re-test's list). Never blocks the event loop (PowerShell takes
570
+ // seconds); start reads it once, and the client's command line does not
571
+ // change while it runs. -> {lines | null, policyPresent}
572
+ async function readClientContext(pid, depth = 8, platform = process.platform, env = process.env) {
573
+ try {
574
+ if (platform === 'win32') {
575
+ const script = [
576
+ "$ErrorActionPreference='Stop'",
577
+ "$k='SOFTWARE\\Policies\\ClaudeCode'",
578
+ "if(([Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($k) -ne $null) -or ([Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($k) -ne $null)){[Console]::Out.WriteLine('POLICY')}else{[Console]::Out.WriteLine('NOPOLICY')}",
579
+ "[void][System.Reflection.Assembly]::LoadWithPartialName('System.Management')",
580
+ `$p=${Number(pid)}`,
581
+ `for($i=0;$i -le ${Number(depth)} -and $p -gt 0;$i++){`,
582
+ "$s=[System.Management.ManagementObjectSearcher]::new(\"SELECT ParentProcessId,CommandLine FROM Win32_Process WHERE ProcessId=$p\")",
583
+ '$o=$null; foreach($x in $s.Get()){$o=$x}',
584
+ 'if($o -eq $null){break}',
585
+ "$c=[string]$o['CommandLine']",
586
+ // an empty command line (unread) is said as '-', never dropped
587
+ "if($c -eq ''){[Console]::Out.WriteLine('-')}else{[Console]::Out.WriteLine([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($c)))}",
588
+ "$p=[int]$o['ParentProcessId']}"
589
+ ].join(';');
590
+ // by its absolute path in the Windows directory, never by name: the
591
+ // search for a program looks in the current directory first
592
+ const out = await run(require('./win-acl').powershellPath(), ['-NoProfile', '-NonInteractive', '-Command', script], 30000);
593
+ const raw = out.split(/\r?\n/).filter((l) => l !== '');
594
+ const policy = raw.shift();
595
+ if (policy !== 'POLICY' && policy !== 'NOPOLICY') return {lines: null, policyPresent: true};
596
+ const lines = raw.map((b) => (b === '-' ? [] : splitWindows(Buffer.from(b, 'base64').toString('utf8'))));
597
+ return {lines: lines.length > 0 ? lines : null, policyPresent: policy === 'POLICY'};
598
+ }
599
+ const lines = [];
600
+ let p = Number(pid);
601
+ for (let i = 0; i <= depth && p > 0; i++) {
602
+ let argv;
603
+ let ppid;
604
+ if (platform === 'linux') {
605
+ argv = fs.readFileSync(`/proc/${p}/cmdline`, 'utf8').split('\0');
606
+ if (argv[argv.length - 1] === '') argv.pop();
607
+ const stat = fs.readFileSync(`/proc/${p}/stat`, 'utf8');
608
+ ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
609
+ } else {
610
+ const out = (await run('ps', ['-o', 'ppid=,args=', '-p', String(p)], 5000)).trim();
611
+ const m = /^(\d+)\s+(.*)$/s.exec(out);
612
+ if (m == null) return {lines: null, policyPresent: false};
613
+ ppid = Number(m[1]);
614
+ argv = m[2].split(/\s+/);
615
+ }
616
+ lines.push(argv);
617
+ if (!Number.isInteger(ppid) || ppid <= 1) break;
618
+ p = ppid;
619
+ }
620
+ const policyPresent = platform === 'linux' && env.WSL_DISTRO_NAME ? await wslPolicyPresent() : false;
621
+ return {lines: lines.length > 0 ? lines : null, policyPresent};
622
+ } catch (err) {
623
+ return {lines: null, policyPresent: true};
624
+ }
625
+ }
626
+
627
+ // start's service: the client's ancestry read once, in the background; a
628
+ // first scan latching a hit for the whole start once it is in; check(client)
629
+ // answers within waitMs (under the runtime's 5 s), unreadable while the
630
+ // ancestry is still being read. ancestry: a promise of the client's lines
631
+ // (clientLines), or of {lines, policyPresent}.
632
+ function conditionsService(args, {ancestry, waitMs = 3000} = {}) {
633
+ if (ancestry === undefined) {
634
+ ancestry = readClientContext(process.ppid, 8, args.platform, args.env).then((c) => ({lines: clientLines(c.lines), policyPresent: c.policyPresent}));
635
+ }
636
+ const latch = conditionsLatch();
637
+ let lines; // undefined while being read
638
+ let policyPresent = false;
639
+ const ready = Promise.resolve(ancestry).then((l) => {
640
+ if (l != null && !Array.isArray(l)) { lines = l.lines; policyPresent = l.policyPresent === true; } else { lines = l; }
641
+ }, () => { lines = null; });
642
+ ready.then(() => latch({...args, managedPresent: policyPresent, client: {name: CLAUDE_CODE, version: '0.0.0'}, parentCommandLines: () => lines}));
643
+ return {
644
+ ready,
645
+ async check(client) {
646
+ if (lines === undefined) {
647
+ await Promise.race([ready, new Promise((r) => { const t = setTimeout(r, waitMs); if (typeof t.unref === 'function') t.unref(); })]);
648
+ }
649
+ if (lines === undefined) return {mayElicit: false, why: UNREADABLE};
650
+ return latch({...args, managedPresent: policyPresent, client, parentCommandLines: () => lines});
651
+ }
652
+ };
653
+ }
654
+
655
+ module.exports = {clientConditions, conditionsLatch, conditionsService, readAncestry, readClientContext, clientLines, splitWindows,
656
+ hasElicitationHook, flagsOf, pluginRootScanned, CLAUDE_CODE, HITS, UNREADABLE, REASONS, SAFE_FLAGS, SCANNED_FLAGS};