@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,420 @@
1
+ 'use strict';
2
+ // Copied from countinghouse lib/win-acl.js at master c274f2f3 (2026-11-15),
3
+ // with countinghouse #275's fileAcls and privateProblem's directory option,
4
+ // unchanged but for powershellPath, which is exported here, and
5
+ // makePrivateDirs, prefetch, FILE_ACLS_EACH_SCRIPT and runCount, which are
6
+ // ch-local's own (cold-start part 3); keep the two copies in step.
7
+ // (Apache-2.0, the same author.) For the private-file checks the native shim
8
+ // makes (lib/private-file.js): the
9
+ // owner and DACL of a file by well-known SID, read with the PowerShell in the
10
+ // Windows directory, and privateProblem's rule.
11
+ // Windows access control by well-known SID, read and set with the PowerShell
12
+ // in the Windows directory (no localized names, no icacls text). Shared by
13
+ // the operator's ceiling (lib/settings-ceiling.js) and the identity secret
14
+ // (lib/identity.js), where POSIX has mode bits and Windows has none (every
15
+ // file reports 0666 there).
16
+ //
17
+ // PowerShell is started by its absolute path under the Windows directory,
18
+ // never by name (Windows looks in the current directory first, where an
19
+ // agent could have put a powershell.exe), with its working directory there
20
+ // and a minimal environment: no PSModulePath, no profile; the security
21
+ // module is imported from beside that powershell.exe. Every caller fails
22
+ // closed on a throw.
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const {execFileSync} = require('child_process');
26
+
27
+ const DRIVE_PATH = /^[A-Za-z]:\\[^"<>|?*\r\n]*$/;
28
+ const SYSTEM = 'S-1-5-18';
29
+ const ADMINISTRATORS = 'S-1-5-32-544';
30
+
31
+ // The process's SystemRoot (the user's own environment: spec #169 section 3),
32
+ // which a caller may check against the Windows known folder.
33
+ function windowsDir() {
34
+ const root = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
35
+ if (!DRIVE_PATH.test(root)) throw new Error(`SystemRoot is not a drive path (${String(root).slice(0, 80)})`);
36
+ return root.replace(/\\+$/, '');
37
+ }
38
+
39
+ // input: what the script reads from stdin ([Console]::In), never a variable
40
+ // or an argument (a secret is never in another process's environment or
41
+ // command line). Throws; e.code ETIMEDOUT when it took over 10 s.
42
+ // PowerShell in the Windows directory, by its absolute path
43
+ const powershellPath = () => path.win32.join(windowsDir(), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
44
+
45
+ // How many synchronous PowerShell runs this process has made (cold-start
46
+ // part 3's pin: the daemon's first start counts them, on Windows).
47
+ let runs = 0;
48
+ const runCount = () => runs;
49
+ function runPowershell(script, extraEnv = {}, input = '') {
50
+ const root = windowsDir();
51
+ runs++;
52
+ const system32 = path.win32.join(root, 'System32');
53
+ return execFileSync(powershellPath(),
54
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
55
+ {cwd: system32, env: Object.assign({SystemRoot: root, windir: root}, extraEnv), input: input, timeout: 10000, encoding: 'utf8', windowsHide: true});
56
+ }
57
+
58
+ // runPowershell without blocking: for a script whose answer comes from this
59
+ // same process (the daemon's pipe probe, when a test serves the pipe in
60
+ // process), which a synchronous child would wait on for ever. The same
61
+ // arguments, environment and 10 s bound. -> Promise of stdout; rejects on a
62
+ // non-zero exit, the bound or a failed start.
63
+ function runPowershellAsync(script, extraEnv = {}, input = '') {
64
+ const {spawn} = require('child_process');
65
+ const root = windowsDir();
66
+ const system32 = path.win32.join(root, 'System32');
67
+ return new Promise((resolve, reject) => {
68
+ let out = '';
69
+ let settled = false;
70
+ const done = (err) => { if (settled) return; settled = true; clearTimeout(timer); if (err != null) reject(err); else resolve(out); };
71
+ let child;
72
+ try {
73
+ child = spawn(powershellPath(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
74
+ {cwd: system32, env: Object.assign({SystemRoot: root, windir: root}, extraEnv), windowsHide: true, stdio: ['pipe', 'pipe', 'ignore']});
75
+ } catch (e) {
76
+ return done(e);
77
+ }
78
+ const timer = setTimeout(() => { try { child.kill(); } catch (e) { /* gone */ } done(new Error('powershell did not answer within 10 s')); }, 10000);
79
+ child.stdout.setEncoding('utf8');
80
+ child.stdout.on('data', (d) => { out += d; });
81
+ child.on('error', done);
82
+ child.on('close', (code) => done(code === 0 ? null : new Error(`powershell exited ${code}`)));
83
+ child.stdin.on('error', () => { /* it ended first: its exit says why */ });
84
+ child.stdin.end(input);
85
+ return undefined;
86
+ });
87
+ }
88
+
89
+ // Pure .NET, and no cmdlet from a module (Get-Acl, ConvertTo-Json,
90
+ // Join-Path, New-Object ...): calling one makes PowerShell look commands up,
91
+ // which without the caller's PSModuleAnalysisCachePath rebuilds its module
92
+ // analysis cache, some 20 s a call on the CI runner, and would load code
93
+ // from whatever module path it has. test/stdio/17 and test/auth/51 check
94
+ // none is named. The JSON is built by hand: a SID, a rights number and
95
+ // Allow or Deny hold no quote.
96
+ const PRELUDE = [
97
+ "$ErrorActionPreference = 'Stop'",
98
+ '$sid = [System.Security.Principal.SecurityIdentifier]',
99
+ '$inheritOnly = [System.Security.AccessControl.PropagationFlags]::InheritOnly'
100
+ ];
101
+ // A $p's ACL as JSON: {"owner", "rules": [{sid, rights, type, inheritOnly}]}
102
+ // (inherited rules included: they are evaluated like any other).
103
+ const ACL_FN = [
104
+ 'function A($p) {',
105
+ ' if ([System.IO.Directory]::Exists($p)) { $a = [System.IO.Directory]::GetAccessControl($p) } else { $a = [System.IO.File]::GetAccessControl($p) }',
106
+ ' $r = @()',
107
+ ' foreach ($x in $a.GetAccessRules($true, $true, $sid)) {',
108
+ ' $io = (($x.PropagationFlags -band $inheritOnly) -ne 0)',
109
+ " $r += ('{\"sid\":\"' + $x.IdentityReference.Value + '\",\"rights\":' + [int64]$x.FileSystemRights + ',\"type\":\"' + [string]$x.AccessControlType + '\",\"inheritOnly\":' + ([string]$io).ToLower() + '}')",
110
+ ' }',
111
+ ' $o = $a.GetOwner($sid)',
112
+ " $ov = ''",
113
+ ' if ($o -ne $null) { $ov = $o.Value }',
114
+ // Only plain allow (A) and deny (D) ACEs are understood: any other type
115
+ // (OA, XA, ZA, XU, the object and callback types) is not, or not wholly,
116
+ // among GetAccessRules' rules. Seen in the SDDL, given as a flag (the SDDL
117
+ // itself, which may quote, is not).
118
+ " $sddl = $a.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)",
119
+ ' $other = $false',
120
+ " foreach ($t in [regex]::Matches($sddl, '\\(([A-Z]+);')) { if ($t.Groups[1].Value -ne 'A' -and $t.Groups[1].Value -ne 'D') { $other = $true } }",
121
+ " '{\"owner\":\"' + $ov + '\",\"otherAces\":' + ([string]$other).ToLower() + ',\"rules\":[' + ($r -join ',') + ']}'",
122
+ '}'
123
+ ];
124
+
125
+ // file -> {user: the current user's SID, owner, rules}; throws on any failure.
126
+ const FILE_ACL_SCRIPT = PRELUDE.concat(ACL_FN, [
127
+ '$u = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
128
+ "(A $env:CH_ACL_FILE).Replace('{\"owner\"', '{\"user\":\"' + $u + '\",\"owner\"')"
129
+ ]).join('\n');
130
+ function fileAcl(file) {
131
+ // absolute: PowerShell's working directory is System32
132
+ return JSON.parse(runPowershell(FILE_ACL_SCRIPT, {CH_ACL_FILE: path.resolve(file)}));
133
+ }
134
+
135
+ // Several paths' ACLs in one PowerShell run (each run costs 1 to 10 s on a
136
+ // CI runner): files -> [{user, owner, otherAces, rules}], in order. The paths
137
+ // go in one variable, a newline between each (DRIVE_PATH has none, nor does
138
+ // path.resolve give one). Throws on any failure. (As countinghouse's, C2.)
139
+ const FILE_ACLS_SCRIPT = PRELUDE.concat(ACL_FN, [
140
+ '$u = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
141
+ '$out = @()',
142
+ "foreach ($f in ($env:CH_ACL_FILES -split \"`n\")) { $out += (A $f).Replace('{\"owner\"', '{\"user\":\"' + $u + '\",\"owner\"') }",
143
+ "'[' + ($out -join ',') + ']'"
144
+ ]).join('\n');
145
+ const pathList = (files) => {
146
+ const list = files.map((f) => path.resolve(f));
147
+ if (list.length === 0 || list.some((f) => /[\r\n]/.test(f))) throw new Error('one or more paths, none with a line break');
148
+ return list;
149
+ };
150
+ function fileAcls(files) {
151
+ const list = pathList(files);
152
+ const acls = JSON.parse(runPowershell(FILE_ACLS_SCRIPT, {CH_ACL_FILES: list.join('\n')}));
153
+ if (!Array.isArray(acls) || acls.length !== list.length) throw new Error('fileAcls: not one ACL per path');
154
+ return acls;
155
+ }
156
+
157
+ // Several paths' ACLs in one run, each read in a try of its own: a path whose
158
+ // read fails answers {"failed": true} in its place, never hiding another's.
159
+ const FILE_ACLS_EACH_SCRIPT = PRELUDE.concat(ACL_FN, [
160
+ '$u = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
161
+ '$out = @()',
162
+ "foreach ($f in ($env:CH_ACL_FILES -split \"`n\")) { try { $out += (A $f).Replace('{\"owner\"', '{\"user\":\"' + $u + '\",\"owner\"') } catch { $out += '{\"failed\":true}' } }",
163
+ "'[' + ($out -join ',') + ']'"
164
+ ]).join('\n');
165
+
166
+ // The ACLs of `paths` read in one PowerShell run, answered one path at a time
167
+ // as fileAcl answers (cold-start part 3: a private read asks its folder's and
168
+ // its file's, a run each). -> fileAcl(p).
169
+ // - Each path is lstat'd first, and only a plain file or directory is sent:
170
+ // no ACL is read through a link found at that lstat (the same gap between
171
+ // an lstat and the read as today's checks, whose own lstat still runs
172
+ // first and refuses a link). A link, or a path that isn't there, is
173
+ // answered by the single read, with today's answer, and so is a path under
174
+ // a listed folder that was left out, a path listed before a folder that
175
+ // holds it, and a path that differs only by case from one listed earlier.
176
+ // - A path whose read failed in the run (or a run that failed, or answered
177
+ // in another shape) is answered by the single read, so its error is
178
+ // exactly today's, and every other path keeps its own. A run that timed
179
+ // out is not followed by more: every sent path answers that timeout, so a
180
+ // refusal comes no later than today's first single read, with its code.
181
+ // A reader serves the one read it was made for and is dropped with it, so a
182
+ // later read reads fresh.
183
+ // run, lstat: a test's; single: the caller's own reader (else fileAcl's export).
184
+ function prefetch(paths, {run = runPowershell, lstat = (p) => fs.lstatSync(p), single = (p) => module.exports.fileAcl(p)} = {}) {
185
+ const known = new Map();
186
+ const plain = [];
187
+ const left = [];
188
+ const under = (r, d) => r.toLowerCase().startsWith(`${d.toLowerCase().replace(/[\\/]+$/, '')}${path.sep}`);
189
+ const all = paths.map((p) => path.resolve(p));
190
+ for (let i = 0; i < all.length; i++) {
191
+ const r = all[i];
192
+ if (plain.includes(r) || left.includes(r)) continue;
193
+ // (a path under a listed folder that was left out, a link or missing, is
194
+ // left out too: its lstat would go through that link; and so is one
195
+ // whose folder is listed after it, or one an earlier listed path spells
196
+ // with other case: a folder is judged before what it holds)
197
+ if (left.some((d) => under(r, d))) { left.push(r); continue; }
198
+ if (all.some((d, j) => (j > i && under(r, d)) || (j < i && d !== r && d.toLowerCase() === r.toLowerCase()))) { left.push(r); continue; }
199
+ let st = null;
200
+ try { st = lstat(r); } catch (e) { st = null; }
201
+ if (st == null || st.isSymbolicLink() || !(st.isFile() || st.isDirectory())) { left.push(r); continue; }
202
+ plain.push(r);
203
+ }
204
+ let timedOut = null;
205
+ if (plain.length > 0) {
206
+ let out = null;
207
+ try { out = JSON.parse(run(FILE_ACLS_EACH_SCRIPT, {CH_ACL_FILES: pathList(plain).join('\n')})); } catch (e) { out = null; if (e != null && e.code === 'ETIMEDOUT') timedOut = e; }
208
+ if (Array.isArray(out) && out.length === plain.length) {
209
+ plain.forEach((p, i) => { if (out[i] != null && typeof out[i] === 'object' && out[i].failed !== true) known.set(p, out[i]); });
210
+ }
211
+ }
212
+ return (p) => {
213
+ const r = path.resolve(p);
214
+ if (known.has(r)) return known.get(r);
215
+ if (timedOut != null && plain.includes(r)) throw timedOut;
216
+ return single(p);
217
+ };
218
+ }
219
+
220
+ // ch-local's own directories on Windows (the daemon's run directory, C4c):
221
+ // each of `dirs`, in order, created if missing and given a protected DACL
222
+ // (nothing inherited): full control for the current user and SYSTEM, to the
223
+ // directory and everything made in it; then the ACLs of `read`, as
224
+ // fileAcls, in the same run. Only the DACL is written, so no privilege to
225
+ // set an owner is needed. Throws on any failure.
226
+ const PRIVATE_DIRS_SCRIPT = PRELUDE.concat(ACL_FN, [
227
+ '$full = [System.Security.AccessControl.FileSystemRights]::FullControl',
228
+ '$allow = [System.Security.AccessControl.AccessControlType]::Allow',
229
+ "$inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'",
230
+ '$none = [System.Security.AccessControl.PropagationFlags]::None',
231
+ '$me = [System.Security.Principal.WindowsIdentity]::GetCurrent().User',
232
+ `$system = [System.Security.Principal.SecurityIdentifier]::new('${SYSTEM}')`,
233
+ "foreach ($d in ($env:CH_ACL_DIRS -split \"`n\")) {",
234
+ ' $a = [System.Security.AccessControl.DirectorySecurity]::new()',
235
+ ' $a.SetAccessRuleProtection($true, $false)',
236
+ ' $a.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($me, $full, $inherit, $none, $allow))',
237
+ ' $a.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($system, $full, $inherit, $none, $allow))',
238
+ // (never a missing parent: CreateDirectory makes them, so a home removed
239
+ // meanwhile would be made again -- the reviewer's high on #140, L7)
240
+ ' if ([System.IO.Directory]::Exists($d)) { [System.IO.Directory]::SetAccessControl($d, $a) } elseif (-not [System.IO.Directory]::Exists([System.IO.Path]::GetDirectoryName($d))) { throw ("the folder above " + $d + " is not there") } else { [void][System.IO.Directory]::CreateDirectory($d, $a) }',
241
+ '}',
242
+ '$u = $me.Value',
243
+ '$out = @()',
244
+ "foreach ($f in ($env:CH_ACL_FILES -split \"`n\")) { $out += (A $f).Replace('{\"owner\"', '{\"user\":\"' + $u + '\",\"owner\"') }",
245
+ "'[' + ($out -join ',') + ']'"
246
+ ]).join('\n');
247
+ // -> the ACLs of `read`, read after `dirs` were made private
248
+ function makePrivateDirs(dirs, read) {
249
+ const d = pathList(dirs);
250
+ const r = pathList(read);
251
+ const acls = JSON.parse(runPowershell(PRIVATE_DIRS_SCRIPT, {CH_ACL_DIRS: d.join('\n'), CH_ACL_FILES: r.join('\n')}));
252
+ if (!Array.isArray(acls) || acls.length !== r.length) throw new Error('makePrivateDirs: not one ACL per path');
253
+ return acls;
254
+ }
255
+
256
+ // Gives file a protected DACL (nothing inherited): full control for the
257
+ // current user and SYSTEM, no one else. Only the DACL is written (a fresh
258
+ // FileSecurity), so no privilege to set an owner is needed. Throws on any
259
+ // failure.
260
+ // Creates file (which must not exist) with data from stdin, its DACL set in
261
+ // the same call that creates it: protected (nothing inherited), full control
262
+ // for the current user and SYSTEM, no one else. There is no instant at which
263
+ // it exists with the directory's inherited DACL, and FileShare.None lets no
264
+ // other handle open while it is written; CreateNew fails on a name that
265
+ // exists (one planted ahead, a link). Throws.
266
+ const CREATE_SCRIPT = [
267
+ "$ErrorActionPreference = 'Stop'",
268
+ '$a = [System.Security.AccessControl.FileSecurity]::new()',
269
+ '$a.SetAccessRuleProtection($true, $false)',
270
+ '$full = [System.Security.AccessControl.FileSystemRights]::FullControl',
271
+ '$allow = [System.Security.AccessControl.AccessControlType]::Allow',
272
+ '$u = [System.Security.Principal.WindowsIdentity]::GetCurrent().User',
273
+ '$a.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($u, $full, $allow))',
274
+ `$a.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new([System.Security.Principal.SecurityIdentifier]::new('${SYSTEM}'), $full, $allow))`,
275
+ // (the data as base64 of its bytes: console text would be read in the
276
+ // console's code page, and ASCII.GetBytes made every non-ASCII character
277
+ // '?' -- A12)
278
+ '$bytes = [System.Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())',
279
+ '$fs = [System.IO.FileStream]::new($env:CH_ACL_FILE, [System.IO.FileMode]::CreateNew, [System.Security.AccessControl.FileSystemRights]::Write, [System.IO.FileShare]::None, 4096, [System.IO.FileOptions]::None, $a)',
280
+ 'try { $fs.Write($bytes, 0, $bytes.Length); $fs.Flush() } finally { $fs.Dispose() }'
281
+ ].join('\n');
282
+ // data (a string, as UTF-8, or bytes: a Buffer or any view of an
283
+ // ArrayBuffer) -> what createPrivate's PowerShell reads on stdin: base64 of
284
+ // its bytes. Anything else is refused, never written as its String().
285
+ function createInput(data) {
286
+ if (typeof data === 'string') return Buffer.from(data, 'utf8').toString('base64');
287
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('base64');
288
+ throw new TypeError('createPrivate: the data is not a string or bytes');
289
+ }
290
+ function createPrivate(file, data) {
291
+ runPowershell(CREATE_SCRIPT, {CH_ACL_FILE: path.resolve(file)}, createInput(data));
292
+ }
293
+
294
+ // Rights a rule may grant someone other than the file's people without
295
+ // letting them read or change it: Synchronize, ReadPermissions,
296
+ // ReadAttributes.
297
+ const HARMLESS = (0x100000 | 0x20000 | 0x80) >>> 0;
298
+ // CREATOR OWNER only (never CREATOR GROUP, S-1-3-1)
299
+ const CREATORS = new Set(['S-1-3-0']);
300
+
301
+ // A secret's ACL (fileAcl) -> a problem, or null. Owned by the current user,
302
+ // Administrators or SYSTEM; no allow rule grants anyone else more than
303
+ // HARMLESS; anything unrecognised fails closed. directory: the ACL is a
304
+ // directory's, whose inherit-only allow rules are not skipped: they flow into
305
+ // the files made there, so one granting anyone else more than HARMLESS fails.
306
+ // CREATOR OWNER's inherit-only rule is admitted: it grants nothing by
307
+ // itself, only to whoever makes a child there, which no one else can under a
308
+ // private DACL, and Windows profiles carry it. CREATOR GROUP's is not: it
309
+ // becomes a grant to the creator's primary group (None, every local user;
310
+ // or Domain Users).
311
+ function privateProblem(what, acl, {directory = false} = {}) {
312
+ if (acl == null || typeof(acl) !== 'object' || typeof(acl.owner) !== 'string' || typeof(acl.user) !== 'string') return `${what}'s ACL could not be read`;
313
+ if (acl.otherAces !== false) return `${what} has an access rule other than a plain allow or deny, or its rules could not all be read`;
314
+ const own = new Set([acl.user, SYSTEM, ADMINISTRATORS]);
315
+ if (!own.has(acl.owner)) return `${what} is owned by ${acl.owner}, not this user, Administrators or SYSTEM`;
316
+ const rules = Array.isArray(acl.rules) ? acl.rules : (acl.rules != null ? [acl.rules] : []);
317
+ for (const r of rules) {
318
+ if (r == null || typeof(r.sid) !== 'string' || typeof(r.type) !== 'string' || !Number.isFinite(Number(r.rights))) return `${what} has an access rule that could not be read`;
319
+ if (r.type === 'Deny') continue;
320
+ if (r.inheritOnly === true) {
321
+ if (!directory || CREATORS.has(r.sid)) continue;
322
+ if (r.type === 'Allow' && !own.has(r.sid) && ((Number(r.rights) >>> 0) & ~HARMLESS) !== 0) return `${what} has an inherit-only rule for ${r.sid}, which the files made in it would take`;
323
+ continue;
324
+ }
325
+ if (r.type !== 'Allow') return `${what} has an access rule of type ${r.type}`;
326
+ if (!own.has(r.sid) && ((Number(r.rights) >>> 0) & ~HARMLESS) !== 0) return `${what} is accessible by ${r.sid}`;
327
+ }
328
+ return null;
329
+ }
330
+
331
+ // The rights that change a file or folder (or what is in it): write and append data, write extended attributes, delete a child,
332
+ // write attributes, delete, change permissions, take ownership; generic write and generic all. Any other right beyond HARMLESS is
333
+ // a read (read data, read extended attributes, execute).
334
+ const CHANGE_RIGHTS = (0x2 | 0x4 | 0x10 | 0x40 | 0x100 | 0x10000 | 0x40000 | 0x80000 | 0x40000000 | 0x10000000) >>> 0;
335
+ // The other accounts privateProblem would name (allow rules, not inherit-only, granting someone not the user, SYSTEM or
336
+ // Administrators more than HARMLESS), in its order: [{sid, name (names[sid], as principalNames resolves it; '' if not), change}]
337
+ function openPrincipals(acl, names = {}) {
338
+ if (acl == null || typeof(acl) !== 'object' || typeof(acl.user) !== 'string') return [];
339
+ const own = new Set([acl.user, SYSTEM, ADMINISTRATORS]);
340
+ const rules = Array.isArray(acl.rules) ? acl.rules : (acl.rules != null ? [acl.rules] : []);
341
+ const out = [];
342
+ for (const r of rules) {
343
+ if (r == null || typeof(r.sid) !== 'string' || r.type !== 'Allow' || r.inheritOnly === true || own.has(r.sid)) continue;
344
+ const rights = (Number(r.rights) >>> 0);
345
+ if ((rights & ~HARMLESS) === 0) continue;
346
+ const prev = out.find((p) => p.sid === r.sid);
347
+ if (prev != null) { prev.change = prev.change || (rights & CHANGE_RIGHTS) !== 0; continue; }
348
+ out.push({sid: r.sid, name: (names != null && typeof(names[r.sid]) === 'string') ? names[r.sid] : '', change: (rights & CHANGE_RIGHTS) !== 0});
349
+ }
350
+ return out;
351
+ }
352
+
353
+ // SIDs -> {names: {sid: its name as Windows resolves it ('' when it can't: a capability or workspace SID)}, machine: this machine's
354
+ // name as Windows gives it ([Environment]::MachineName, never the environment's COMPUTERNAME, which a session the shim or Codex
355
+ // starts lacks), localAppData: the user's local application data folder, the known folder (never the environment's)}, in one
356
+ // PowerShell run. For a refusal's words only, so it runs only when one names other accounts, never on the way
357
+ // to a private one (a lookup can reach a domain controller). Every rule is judged by its SID; a SID that is not plainly one is not
358
+ // asked. Each string is written as JSON in ASCII alone (\u escapes), so no console code page changes a localized name. Throws on
359
+ // any failure: the caller then says the SIDs.
360
+ const NAMES_SCRIPT = PRELUDE.concat([
361
+ // (the known folder on its own: a failure there leaves it '', never the names with it)
362
+ "function L() { try { return E ([Environment]::GetFolderPath('LocalApplicationData')) } catch { return '\"\"' } }",
363
+ "function E($t) { $e = ''; foreach ($c in $t.ToCharArray()) { $i = [int]$c; if ($i -lt 32 -or $i -gt 126 -or $i -eq 34 -or $i -eq 92) { $e += '\\u' + $i.ToString('x4') } else { $e += $c } }; return '\"' + $e + '\"' }",
364
+ '$out = @()',
365
+ "foreach ($s in ($env:CH_SIDS -split \"`n\")) {",
366
+ " try { $n = $sid::new($s).Translate([System.Security.Principal.NTAccount]).Value } catch { $n = '' }",
367
+ ' $out += (E $n)',
368
+ '}',
369
+ "'{\"machine\":' + (E ([Environment]::MachineName)) + ',\"localAppData\":' + (L) + ',\"names\":[' + ($out -join ',') + ']}'"
370
+ ]).join('\n');
371
+ function principalNames(sids) {
372
+ const asked = sids.filter((s) => typeof(s) === 'string' && SID_TEXT.test(s));
373
+ if (asked.length === 0) return {names: {}, machine: null, localAppData: null};
374
+ const got = JSON.parse(runPowershell(NAMES_SCRIPT, {CH_SIDS: asked.join('\n')}));
375
+ if (got == null || !Array.isArray(got.names) || got.names.length !== asked.length) throw new Error('principalNames: not one name per SID');
376
+ const names = {};
377
+ asked.forEach((s, i) => { names[s] = typeof(got.names[i]) === 'string' ? got.names[i] : ''; });
378
+ const given = (v) => (typeof(v) === 'string' && v !== '') ? v : null;
379
+ return {names, machine: given(got.machine), localAppData: given(got.localAppData)};
380
+ }
381
+
382
+ // Whether anyone but this user, SYSTEM and Administrators holds a right that changes it, or what is made in it: an allow rule,
383
+ // inherit-only ones included (what was made in it took that right), CREATOR OWNER's aside (it grants only to whoever makes a child).
384
+ // A folder someone else could change may already have been changed, so it is moved aside, not repaired (the reviewer's ruling on
385
+ // the Windows home, as for POSIX's group or world write).
386
+ function foreignChange(acl) {
387
+ if (acl == null || typeof(acl) !== 'object' || typeof(acl.user) !== 'string') return false;
388
+ const own = new Set([acl.user, SYSTEM, ADMINISTRATORS]);
389
+ const rules = Array.isArray(acl.rules) ? acl.rules : (acl.rules != null ? [acl.rules] : []);
390
+ return rules.some((r) => r != null && r.type === 'Allow' && typeof(r.sid) === 'string' && !own.has(r.sid) && !CREATORS.has(r.sid) && ((Number(r.rights) >>> 0) & CHANGE_RIGHTS) !== 0);
391
+ }
392
+
393
+ // The lines that make file private as privateProblem wants it, for Windows PowerShell (each one, on a line of its own): nothing
394
+ // inherited, this user and SYSTEM, each other SID a rule names removed, and the user made the owner. By SID (no names: they are
395
+ // localized, and a user name is never printed). A SID is removed with .NET's PurgeAccessRules, one SID to a line: icacls /remove
396
+ // leaves a SID that names no account (a Codex sandbox capability), and one call with several /remove switches processes nothing,
397
+ // both saying no error (seen on the owner's machine); Get-Acl/Set-Acl need SeSecurityPrivilege (Set-Acl writes the SACL), which a standard user
398
+ // lacks. The Windows legs run the printed lines as printed (test/home-windows-acl.test.js). Single quotes: nothing in a path is
399
+ // expanded. A SID that is not plainly one: no lines.
400
+ // directory: the grants inherit to what is made in it ((OI)(CI)), or
401
+ // /inheritance:r would leave its own files reachable by no one (the
402
+ // reviewer's Fable high on #126, F13)
403
+ const SID_TEXT = /^S-1-[0-9]+(-[0-9]+)+$/;
404
+ // (PowerShell takes U+2018-U+201B as single quotes too: each doubled, as an ASCII one is)
405
+ const psQuote = (s) => `'${String(s).replace(/['\u2018-\u201b]/g, '$&$&')}'`;
406
+ function fixHint(file, acl, {directory = false} = {}) {
407
+ const user = acl != null && typeof(acl.user) === 'string' ? acl.user : null;
408
+ if (user == null || !SID_TEXT.test(user)) return null;
409
+ const rules = Array.isArray(acl.rules) ? acl.rules : (acl.rules != null ? [acl.rules] : []);
410
+ const others = [...new Set(rules.map((r) => r && r.sid).filter((s) => typeof(s) === 'string' && s !== user && s !== SYSTEM))];
411
+ if (others.some((s) => !SID_TEXT.test(s))) return null;
412
+ const f = directory ? '(OI)(CI)F' : 'F';
413
+ const p = psQuote(file);
414
+ // (each grant in single quotes: in PowerShell an unquoted (OI) is a command to run)
415
+ return [`icacls ${p} /inheritance:r /grant:r '*${user}:${f}' '*${SYSTEM}:${f}'`,
416
+ ...others.map((s) => ` $i = Get-Item -LiteralPath ${p} -Force; $a = $i.GetAccessControl('Access'); $a.PurgeAccessRules([System.Security.Principal.SecurityIdentifier]'${s}'); $i.SetAccessControl($a)`),
417
+ ` icacls ${p} /setowner *${user}`].join('\n');
418
+ }
419
+
420
+ module.exports = {windowsDir, powershellPath, runPowershell, runPowershellAsync, runCount, fileAcl, fileAcls, prefetch, FILE_ACLS_EACH_SCRIPT, makePrivateDirs, createPrivate, createInput, privateProblem, openPrincipals, principalNames, foreignChange, fixHint, PRELUDE, ACL_FN, FILE_ACL_SCRIPT, FILE_ACLS_SCRIPT, PRIVATE_DIRS_SCRIPT, NAMES_SCRIPT, CREATE_SCRIPT, SYSTEM, ADMINISTRATORS, DRIVE_PATH};
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: ci-failure-triage
3
+ description: Use when a CI run (GitHub Actions) failed and the user wants to know why. Calls the ci_failure_triage tool of the ch-packs plugin.
4
+ ---
5
+
6
+ # CI failure triage
7
+
8
+ when a CI run failed, call `ci_failure_triage` first and show its receipt line verbatim.
9
+
10
+ Then answer from what the tool returned: the failing step, its error lines, whether the failure is new, flaky or recurring where it says so (with several failed jobs, each job's own), and the authors of the commits the failure occurred on, when it names them. Do not read the raw logs yourself unless the user asks; the receipt says how much of them the tool read.
11
+
12
+ If the `ci_failure_triage` tool is not available, it is often one of these:
13
+ - countinghouse is not installed, or the ci-failure-triage pack is not;
14
+ - the `ch-packs` plugin is not installed, or its `countinghouse` MCP server is not connected (reconnect it in `/mcp`, or restart Claude Code after an install);
15
+ - a module the tool needs has no credential: a module without its credential does not load, so its tool is not listed;
16
+ - a module the tool needs is turned off;
17
+ - or another reason `countinghouse_overview` names.
18
+
19
+ If `countinghouse_overview` is available, follow the countinghouse-setup skill's section 5 with it: it names what is not ready and the command for it, and that skill says how to treat what it returns. Otherwise follow the countinghouse-setup skill from its section 1, which checks whether countinghouse is installed. Either way, run nothing and turn nothing on without the user's yes.
20
+
21
+ The tool reads GitHub through ch-access-github's credential, a read-only token or the user's `gh` login. Never ask the user to paste a token into the conversation. If the credential is missing, find the countinghouse home `<home>` and check its characters as the countinghouse-setup skill's section 1 says (stop if the check fails), then ask the user to run, in their own terminal, `node "<home>/bin/ch-local.js" credentials add ch-access-github`. Never the bare `ch-local`: installing does not put it on their PATH. Never run that command yourself: it reads the key in the user's terminal.
@@ -0,0 +1,177 @@
1
+ ---
2
+ name: countinghouse-module
3
+ description: "Use when writing a new countinghouse module, or when a user asks for a tool to be hosted on a countinghouse runtime. Covers decomposing a requirement into services and actions, the module file layout, and checking it. On ch-local you never load a module yourself: the user adds it with add-module in their own terminal."
4
+ ---
5
+ <!-- Copied from countinghouse 2412d071dfa31cd5f644f294b538f137509bfb3e, .claude/skills/countinghouse-module/SKILL.md; its doc references point at that commit. Re-copied with each release's countinghouse (docs/development/release-checklist.md); never edited here. -->
6
+
7
+
8
+ # Writing a countinghouse module
9
+
10
+ A countinghouse module is a directory the runtime loads and exposes as one or
11
+ more MCP tools. Your job is to turn a user's requirement into that directory,
12
+ with the user approving the design before code exists.
13
+
14
+ ## Decide what it may return, before what it does
15
+
16
+ The output schema is the guarantee. A tool whose output schema is
17
+ `{type: 'object'}` promises nothing; a tool whose output schema has fields for
18
+ findings and counts and no field that can hold a file cannot leak a file, no
19
+ matter what its handler does or what a model asks it to do.
20
+
21
+ So the first question is not "what does this tool do" but **"what is this tool
22
+ allowed to return?"** Ask the user. If they say "summarize our logs", ask
23
+ whether the summary may quote raw log lines. Their answer is a schema
24
+ constraint, and encoding it is most of the value they came for.
25
+
26
+ ## Decomposing a requirement
27
+
28
+ - **One action is one schema-typed operation.** If describing it needs the word
29
+ "and", consider two actions.
30
+ - **A service groups related actions** on one device. Most modules need exactly
31
+ one service; reach for a second only when the two groups would sensibly be
32
+ used independently.
33
+ - **A chain belongs in a composite action**, not in the model. If the user's
34
+ request is "read X, then check Y, then report" and the intermediate data is
35
+ large or sensitive, that is one action calling others via `ctx.serviceClient`
36
+ — not three tools the model has to join. See `https://github.com/mchen6/countinghouse/blob/2412d071dfa31cd5f644f294b538f137509bfb3e/docs/composite-tools.md`.
37
+ - **Name for a reader who has never seen it.** The action `description` is what
38
+ an LLM reads to decide whether to call it, and an action with no description
39
+ is skipped entirely when `tools/list` is built.
40
+
41
+ ## If it must ask the user: ask first, act after
42
+
43
+ An action may declare questions (`api.json`'s `questions`) and ask one with
44
+ `ctx.ask(name, values)`. The handler does not wait: with no answer it ends
45
+ (`ASK_PENDING`), and the client's retry runs it again from the top. So put
46
+ every `ctx.ask` **before** anything the handler cannot do twice:
47
+
48
+ - every `ctx.call` before the ask **runs again** on the retry, with
49
+ whatever it costs or changes;
50
+ - a message sent, a record written or a payment made before the ask
51
+ **happens twice**, and has happened once even if the user declines.
52
+
53
+ Never catch `ASK_PENDING` (from your own ask, or a part's through
54
+ `ctx.call`): let it pass. Catch `ASK_UNAVAILABLE` to fall back when there is
55
+ no one to ask. Keep a question's values the same on every run, and never
56
+ treat an answer as proof of a person. Validate cannot check any of this;
57
+ say it to the user when you show the split.
58
+
59
+ ## Show the split before writing files
60
+
61
+ Present the proposed device, services, actions and — most importantly — what
62
+ each action may return. Wait for the user. This is where a wrong assumption is
63
+ cheap; after four files exist it is not.
64
+
65
+ Then call `countinghouse_validate_plan` to check names, duplicates, missing
66
+ descriptions and collisions with tools already on the runtime.
67
+
68
+ ## The layout
69
+
70
+ ```
71
+ my-module/
72
+ ├── package.json # name and version
73
+ ├── api.json # device, services, actions, schema pointers
74
+ ├── schema.json # JSON Schema 2020-12 documents
75
+ └── handlers/
76
+ └── greetService/ # service SHORT name (after ":serviceID:")
77
+ └── hello.js # one file per action
78
+ ```
79
+
80
+ That is the only format: no `index.js`, no `device.js`, no `"main"` in
81
+ `package.json`. A main entry without `handlers/` is refused
82
+ (`MODULE_LAYOUT_UNSUPPORTED`); shared code goes in a plain file the handlers
83
+ require.
84
+
85
+ A handler is `async (input, ctx)`; `input` is already validated.
86
+
87
+ ```js
88
+ module.exports = async (input, ctx) => ({output: {text: `hello ${input.name}`}});
89
+ ```
90
+
91
+ To fail a call, return the module's own error code (never one of the
92
+ runtime's):
93
+
94
+ ```js
95
+ module.exports = async (input, ctx) => {
96
+ if (input.name.trim() === '') return ctx.error('INPUT_REJECTED', 'name must not be blank');
97
+ return {output: {text: `hello ${input.name}`}};
98
+ };
99
+ ```
100
+
101
+ Full reference: `https://github.com/mchen6/countinghouse/blob/2412d071dfa31cd5f644f294b538f137509bfb3e/docs/module-development.md`.
102
+
103
+ ## The loop
104
+
105
+ 1. `countinghouse_validate_plan` — before any file exists.
106
+ 2. Write `package.json`, `api.json`, `schema.json`, `handlers/`.
107
+ 3. `countinghouse_validate_module` — repeat until `ok: true`. It returns
108
+ *every* problem, each naming the stage and the fix; do not fix them one per
109
+ run.
110
+ 4. `countinghouse_load_module` — note the `toolNames` it returns. If
111
+ `discoveryComplete` is `false`, `toolNames` may be incomplete; the call is
112
+ worth retrying.
113
+ 5. `countinghouse_call_tool` with one of those names, and real arguments.
114
+ 6. Show the user the call and its output.
115
+
116
+ Without a running server, the installed `countinghouse-validate` is the same
117
+ check from a shell (exit 0 clean, 1 problems, 2 unusable path): in a project
118
+ that has countinghouse, `npx --no-install countinghouse-validate ./my-module`;
119
+ with ch-local, `node "<home>/app/node_modules/countinghouse/bin/countinghouse-validate.js" ./my-module`.
120
+ Never a bare `npx countinghouse-validate`: without a local copy it fetches
121
+ whatever npm package has that name.
122
+
123
+ On a hosted runtime, the authoring tools need the runtime started with
124
+ `--authoringTools` and an admin key. If they are missing from `tools/list`,
125
+ that is why (under ch-local, see below). Keep the
126
+ default worker mode: a module whose handler file crashes or calls
127
+ `process.exit()` while being required by `countinghouse_load_module` is a
128
+ reported failure in worker mode, but takes the whole runtime down under
129
+ `--no-workerThread`.
130
+
131
+ ## Under ch-local
132
+
133
+ You are under ch-local, the user's own install, when `tools/list` has
134
+ `countinghouse_validate_plan`, `countinghouse_validate_module` and
135
+ `countinghouse_load_module` but no `countinghouse_call_tool`. There the loop
136
+ ends differently:
137
+
138
+ - Write the module in a folder the user chooses, outside the ch-local home
139
+ (`~/.countinghouse`, or `$COUNTINGHOUSE_HOME`). A folder inside it, one
140
+ holding it, or one reached through a link is refused
141
+ (`OWN_MODULE_PATH_REFUSED`).
142
+ - Its `package.json` declares `"countinghouse": {"role": "scenario"}`:
143
+ only a scenario's tools are listed here.
144
+ - `countinghouse_validate_plan` works as above. `countinghouse_validate_module`
145
+ checks the files without running any of the module's code. A problem with
146
+ the folder itself (a link, a special file, too large) is reported first,
147
+ alone: fix it and validate again before the other checks run.
148
+ - `countinghouse_load_module` (with the folder's absolute path) loads
149
+ nothing. It answers `OWN_MODULE_NEEDS_TERMINAL`, which is expected, not a
150
+ failure: its message holds the command the user runs in their own
151
+ terminal. Give the user that command exactly as the answer has it; do not
152
+ rebuild it. Never run it yourself, and never answer its question: the user
153
+ confirms what is added. Step 4's `toolNames` and retry advice do not apply.
154
+ - Once the user has added it, its tools are in `tools/list` like a pack's:
155
+ call them directly. `countinghouse_call_tool` does not exist here, and
156
+ calling it is answered like any unknown tool.
157
+ - Never suggest `--authoringTools` or an admin key: they are for a hosted
158
+ runtime.
159
+ - After any change to the module's code, the user runs `add-module` again
160
+ and confirms again.
161
+
162
+ ## When it does not appear in tools/list
163
+
164
+ `https://github.com/mchen6/countinghouse/blob/2412d071dfa31cd5f644f294b538f137509bfb3e/docs/module-development.md` has the full checklist. The five that account for
165
+ almost everything:
166
+
167
+ 1. `MODULE_LAYOUT_UNSUPPORTED` — a main entry (`"main"` or `index.js`) and no
168
+ `handlers/`: the retired format; the error names the file.
169
+ 2. `DEVICE_SPEC_VALIDATION_FAIL` — `api.json` fails the meta-schema; the error
170
+ names the instance path.
171
+ 3. `MODULE_NO_DEVICE_ONLINE` — the device assembled from `api.json` failed;
172
+ the message quotes the earlier error.
173
+ 4. `LOAD_MODULE_FAIL` — a handler file threw while being required.
174
+ 5. Loaded but absent — an action with no `description`, or whose input or
175
+ output schema holds a hidden character, is skipped; under `--stdio` or the
176
+ shared runtime only a module with `role: "scenario"` is listed (a part
177
+ never is); and `tools/list` is filtered by what the caller may use.