@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
package/lib/start.js ADDED
@@ -0,0 +1,721 @@
1
+ 'use strict';
2
+ // ch-local start --stdio (plan Task 11): runs the installed runtime over stdio
3
+ // with every installed pack whose credential is present. The profile is LM1's
4
+ // single-identity one: the local store in the one per-user store directory,
5
+ // the sandbox enforced (audit may be asked for, off never), no auth file, no
6
+ // usage directory and no port. stdout is the client's MCP channel, so start
7
+ // writes only to stderr. What one start writes for its runtime (the remote
8
+ // credentials and the device configs) lives in <home>/run/<host>-<pid>-<random>,
9
+ // so starts from several clients at once never see each other's.
10
+ const crypto = require('node:crypto');
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const {layout} = require('./home');
14
+ const {writeAtomic} = require('./atomic');
15
+ const {ALLOWED_ORIGINS} = require('./allowlist');
16
+ const {ghToken} = require('./github-token');
17
+ const moduleCredentials = require('./module-credentials');
18
+ const heldBack = require('./held-back');
19
+ const {allowedEnv, runtimeEnv} = require('./shim-config');
20
+ const {installedPacks, withdrawnNames, releaseOf, recordRelease, staleLine, installLine, runsFromHome} = require('./packs');
21
+ const {readModulesRecord: readRecord} = require('./module-record');
22
+ const {availability, short} = require('./availability');
23
+ const {readOwnRecord} = require('./own-record');
24
+ const {moduleSeams} = require('./module-seams');
25
+ const {UNRELEASED_LINE} = require('./pins');
26
+ const {chLocal, hintCommand} = require('./command-line');
27
+
28
+ // The pass-through is an allowlist (reviewer, 2026-11-12): only options known
29
+ // safe, each with its accepted values. Anything else is refused by name.
30
+ const PASS_THROUGH = {
31
+ // enforce where the installed runtime can run it (lib/sandbox-support.js)
32
+ '--moduleSandbox': (v, platform, enforceOk) => (enforceOk ? v === 'enforce' || v === 'audit' : v === 'audit')
33
+ };
34
+ const SIGNALS = {SIGINT: 2, SIGHUP: 1, SIGTERM: 15};
35
+ // A runtime older than countinghouse#195 refuses --moduleSandbox enforce on
36
+ // Windows: said here before anything starts, with what to do (where: the
37
+ // home's layout, for the command's launcher form: lib/command-line.js).
38
+ const windowsEnforce = (where) => `--moduleSandbox enforce needs a countinghouse that runs it on Windows (https://github.com/mchen6/countinghouse/issues/195), and the installed one is older: run \`${chLocal(where, 'upgrade')}\`, or use --moduleSandbox audit until then.`;
39
+ // What audit does (the maintainer's decision): countinghouse lets a pack
40
+ // read, and logs it, but refuses its writes outside its own area. Said once
41
+ // whenever the runtime runs under audit.
42
+ // (one notice each, within the runtime's 200-character notice cut at a
43
+ // user's home: the final pass on #134, L2; the runtime's own words for what
44
+ // audit does not stop, L5)
45
+ const AUDIT_LINE = 'under audit, countinghouse logs what a pack reads and refuses its file writes outside its own area; it does not stop a module that starts a process, a thread or native code: enforce refuses those';
46
+ const windowsAudit = (where) => `this countinghouse is older than countinghouse#195: it cannot enforce the sandbox on Windows, so it runs audit; \`${chLocal(where, 'upgrade')}\` installs one that can`;
47
+ // Acceptance runs only (reviewer, 2026-11-12): CH_LOCAL_REMOTE_MAP, a comma
48
+ // list of <allowed origin>=<http://127.0.0.1:port | http://[::1]:port>, under
49
+ // CH_LOCAL_DEV=1, becomes the runtime's --remoteOriginMap: the pack's calls
50
+ // to that origin go to a local stand-in. Never from a client's options. The
51
+ // runtime honours it only with COUNTINGHOUSE_ACCEPTANCE=1 in its environment,
52
+ // which start passes through as it is and never sets. Under a map, only a
53
+ // credential that is an acceptance token (chacc_...) is sent (start, below).
54
+ // -> {problem} or {args, notes}.
55
+ function remoteMap(env) {
56
+ const raw = env.CH_LOCAL_REMOTE_MAP;
57
+ if (raw == null || raw === '') return {args: [], notes: []};
58
+ if (env.CH_LOCAL_DEV !== '1') return {problem: 'CH_LOCAL_REMOTE_MAP needs CH_LOCAL_DEV=1: it is for acceptance runs only'};
59
+ const args = [];
60
+ const notes = [];
61
+ for (const item of raw.split(',')) {
62
+ const m = /^(https:\/\/[^=]+)=(.*)$/.exec(item.trim());
63
+ if (m == null) return {problem: `CH_LOCAL_REMOTE_MAP ${JSON.stringify(item)} must be <origin>=<http://127.0.0.1:port>`};
64
+ if (!Object.prototype.hasOwnProperty.call(ALLOWED_ORIGINS, m[1])) return {problem: `CH_LOCAL_REMOTE_MAP: ${m[1]} is not an origin this launcher allows`};
65
+ if (!/^http:\/\/(127\.0\.0\.1|\[::1\]):\d{1,5}$/.test(m[2])) return {problem: `CH_LOCAL_REMOTE_MAP: the target must be http://127.0.0.1:<port> or http://[::1]:<port>, not ${m[2]}`};
66
+ args.push('--remoteOriginMap', `${m[1]}=${m[2]}`);
67
+ notes.push(`acceptance: ${m[1]} is sent to ${m[2]} (CH_LOCAL_REMOTE_MAP)`);
68
+ }
69
+ return {args, notes};
70
+ }
71
+
72
+ // GitHub's rules: an owner is 1-39 letters, digits or single inner hyphens; a
73
+ // repository name is 1-100 letters, digits, '.', '_' or '-', and not . or ..
74
+ const OWNER = /^(?=.{1,39}$)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/;
75
+ const NAME = /^(?=.{1,100}$)[A-Za-z0-9._-]+$/;
76
+
77
+ // owner/name from a GitHub remote URL (https, git, ssh or scp form), else null.
78
+ function repoFromRemote(url) {
79
+ const s = String(url || '').trim();
80
+ const host = '(?:www\\.)?github\\.com';
81
+ const m = new RegExp(`^(?:(?:https?|git|ssh)://(?:[^@/]+@)?${host}(?::\\d+)?/|[^@/\\s]+@${host}:)([^/\\s]+)/([^/\\s]+?)(?:\\.git)?/?$`, 'i').exec(s);
82
+ if (m == null) return null;
83
+ const [, owner, name] = m;
84
+ if (!OWNER.test(owner) || !NAME.test(name) || name === '.' || name === '..') return null;
85
+ return `${owner}/${name}`;
86
+ }
87
+
88
+ // The url of [remote "origin"] in a git config's text, or null. Section and
89
+ // key names are case-insensitive; values may be quoted; ; and # start comments.
90
+ function originUrl(text) {
91
+ let inOrigin = false;
92
+ for (const raw of String(text).split(/\r?\n/)) {
93
+ const line = raw.trim();
94
+ if (line === '' || line.startsWith('#') || line.startsWith(';')) continue;
95
+ const section = /^\[\s*([A-Za-z0-9.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(line);
96
+ if (section != null) { inOrigin = section[1].toLowerCase() === 'remote' && section[2] === 'origin'; continue; }
97
+ if (!inOrigin) continue;
98
+ const kv = /^([A-Za-z][A-Za-z0-9-]*)\s*=\s*(.*)$/.exec(line);
99
+ if (kv == null || kv[1].toLowerCase() !== 'url') continue;
100
+ let value = kv[2];
101
+ if (value.startsWith('"')) {
102
+ const q = /^"((?:[^"\\]|\\.)*)"/.exec(value);
103
+ value = q == null ? '' : q[1].replace(/\\(.)/g, '$1');
104
+ } else {
105
+ value = value.replace(/\s[;#].*$/, '').trim();
106
+ }
107
+ return value === '' ? null : value;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // The origin URL of the repository holding `cwd`, read from its config file;
113
+ // no git process runs (reviewer, 2026-11-12: a git.exe in an untrusted
114
+ // repository would run with the user's environment). A worktree's .git is a
115
+ // file naming its gitdir, whose commondir names the directory with the config.
116
+ function readOrigin(cwd) {
117
+ if (typeof cwd !== 'string' || cwd === '') return null;
118
+ const read = (file) => {
119
+ try {
120
+ const st = fs.statSync(file);
121
+ return st.isFile() && st.size <= 1024 * 1024 ? fs.readFileSync(file, 'utf8') : null;
122
+ } catch (err) { return null; }
123
+ };
124
+ for (let dir = path.resolve(cwd); ; dir = path.dirname(dir)) {
125
+ const dotGit = path.join(dir, '.git');
126
+ let gitDir = null;
127
+ try {
128
+ const st = fs.statSync(dotGit);
129
+ if (st.isDirectory()) gitDir = dotGit;
130
+ else if (st.isFile()) {
131
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(read(dotGit) || '');
132
+ if (m != null) gitDir = path.resolve(dir, m[1]);
133
+ }
134
+ } catch (err) { /* not here */ }
135
+ if (gitDir != null) {
136
+ const common = (read(path.join(gitDir, 'commondir')) || '').trim();
137
+ const configDir = common !== '' ? path.resolve(gitDir, common) : gitDir;
138
+ return originUrl(read(path.join(configDir, 'config')) || '');
139
+ }
140
+ if (path.dirname(dir) === dir) return null;
141
+ }
142
+ }
143
+
144
+ // -> {problem} or {options}: the pass-through, each option known safe with
145
+ // an accepted value, in `--x v` or `--x=v` form. where: the home's layout, for
146
+ // the command a refusal names.
147
+ function checkPassThrough(passThrough, platform = process.platform, enforceOk = platform !== 'win32', where = null) {
148
+ const options = [];
149
+ for (let i = 0; i < passThrough.length; i++) {
150
+ const a = passThrough[i];
151
+ const eq = a.indexOf('=');
152
+ const name = eq === -1 ? a : a.slice(0, eq);
153
+ const check = Object.prototype.hasOwnProperty.call(PASS_THROUGH, name) ? PASS_THROUGH[name] : null;
154
+ if (check == null) return {problem: `${name} cannot be passed to ch-local start; only ${Object.keys(PASS_THROUGH).join(' and ')} can`};
155
+ const value = eq === -1 ? passThrough[++i] : a.slice(eq + 1);
156
+ if (value === undefined || !check(value, platform, enforceOk)) {
157
+ if (value === 'enforce' && !enforceOk) return {problem: windowsEnforce(where)};
158
+ return {problem: !enforceOk
159
+ ? `--moduleSandbox ${value || '(no value)'} is not allowed; with the installed countinghouse a pack runs under audit on Windows (countinghouse#195)`
160
+ : `--moduleSandbox ${value || '(no value)'} is not allowed; a pack runs under enforce, or audit to diagnose`};
161
+ }
162
+ options.push(...(eq === -1 ? [name, value] : [a]));
163
+ }
164
+ return {options, sandbox: options.includes('--moduleSandbox') || options.some((o) => o.startsWith('--moduleSandbox='))};
165
+ }
166
+
167
+ const {hostTag, HEARTBEAT_MS} = require('./run-liveness');
168
+ const {machineId} = require('./machine');
169
+ const {withLock} = require('./lock');
170
+ const {controlClient, teller} = require('./control');
171
+ const {conditionsService} = require('./client-conditions');
172
+ const {enforceAvailable} = require('./sandbox-support');
173
+ const {watchFiles} = require('./watch');
174
+ const {inPlace} = require('./in-place');
175
+ const {readSettings, valueOf, runtimeValue, withSettingsLock} = require('./settings');
176
+ const {ceilingFor, forbiddenBy, startUnderCeiling} = require('./ceiling');
177
+ const {reportOutsideEdits, outsideEdits} = require('./outside-edits');
178
+
179
+ // Settings the runtime takes as options at start.
180
+ //
181
+ // The two caps are passed always: the stored value, or ch-local's own
182
+ // default when nothing is stored, as the ceiling left them
183
+ // (startUnderCeiling). So the runtime's own default never governs under
184
+ // ch-local, and the two defaults drifting apart cannot leave a ceiling that
185
+ // bounds nothing (countinghouse #283: the runtime at 16 MiB, ch-local at
186
+ // 8 MiB, a ceiling between them).
187
+ function settingArgs(settings) {
188
+ // in the runtime's unit (runtimeValue: --requestTimeout in seconds); the
189
+ // sandbox is decided once, in sandboxArgs
190
+ const arg = (name) => [`--${name}`, String(runtimeValue(name, valueOf(settings, name)))];
191
+ return [...arg('maxOutputBytes'), ...arg('requestTimeout')];
192
+ }
193
+
194
+ // The sandbox option the runtime gets, decided in one place: one passed
195
+ // through wins (checked.sandbox: it is in the pass-through already);
196
+ // otherwise the setting (audit, or enforce by default), except audit where
197
+ // the installed runtime cannot run enforce (Windows before countinghouse#195).
198
+ function sandboxArgs(checked, settings, enforceOk) {
199
+ if (checked.sandbox) return [];
200
+ if (!enforceOk) return ['--moduleSandbox', 'audit'];
201
+ return ['--moduleSandbox', valueOf(settings, 'moduleSandbox') === 'audit' ? 'audit' : 'enforce'];
202
+ }
203
+ // the sandbox the runtime runs, as sandboxArgs and a pass-through decide it:
204
+ // 'enforce' or 'audit' (an own module loads only under enforce: B-own-add)
205
+ function sandboxModeOf(checked, settings, enforceOk) {
206
+ if (!checked.sandbox) return sandboxArgs(checked, settings, enforceOk)[1];
207
+ const o = checked.options;
208
+ return o.some((a, i) => a === '--moduleSandbox=audit' || (a === '--moduleSandbox' && o[i + 1] === 'audit')) ? 'audit' : 'enforce';
209
+ }
210
+
211
+ // Removes this host's run directories whose start has died (a SIGKILL leaves
212
+ // one). Other hosts' (a home on a shared disk) and names start never made stay.
213
+ function sweepRuns(runDir, host, alive) {
214
+ let names = [];
215
+ try { names = fs.readdirSync(runDir); } catch (err) { return; }
216
+ for (const name of names) {
217
+ const m = /^(.+)-(\d+)-[0-9a-f]{8}$/.exec(name);
218
+ if (m != null && m[1] === host && !alive(Number(m[2]))) fs.rmSync(path.join(runDir, name), {recursive: true, force: true});
219
+ }
220
+ }
221
+
222
+
223
+ // what the shared runtime tells ch-local daemon's table (countinghouse #255,
224
+ // #262 and the idle stop)
225
+ // the runtime's explicit refusals of a restore (countinghouse restore.js)
226
+ const RESTORE_REFUSALS = ['CONTROL_BAD_RESTORE', 'CONTROL_RESTORE_DONE'];
227
+ const TABLE_TELLS = ['session-resume', 'session-state', 'session-gone', 'decline', 'idle', 'busy', 'drained'];
228
+
229
+ // a stopped session runtime's SIGTERM, then SIGKILL after this
230
+ const SESSION_KILL_MS = 10000;
231
+
232
+ // The path options a session runtime is given, and its entry: the first one
233
+ // whose real path (its nearest existing ancestor's, for one not made yet)
234
+ // is not under the home's, or null. The one exception (C4c,
235
+ // lib/session-socket.js): --sessionSocket may instead be a named pipe of the
236
+ // daemon's form (Windows has no socket path), or exactly the long-home
237
+ // fallback's socket the daemon picks ($TMPDIR/ch-<uid>/sessions.sock).
238
+ const PATH_OPTIONS = ['--sessionSocket', '--sessionDir', '--storePath', '--modulePath', '--moduleDataPath', '--remoteCredentials', '--deviceConfigPath',
239
+ '--loadModule', '--modulesRoot', '--partDir', '--settingsFile'];
240
+ function realOrAncestor(p) {
241
+ let cur = path.resolve(p);
242
+ const rest = [];
243
+ for (;;) {
244
+ try { return path.join(fs.realpathSync(cur), ...rest.reverse()); } catch (e) { /* not there yet */ }
245
+ const up = path.dirname(cur);
246
+ if (up === cur) return cur;
247
+ rest.push(path.basename(cur));
248
+ cur = up;
249
+ }
250
+ }
251
+ function pathsOutside(args, home, {env = process.env} = {}) {
252
+ const root = realOrAncestor(home);
253
+ const under = (p) => { const r = realOrAncestor(p); return r === root || r.startsWith(root + path.sep); };
254
+ const {isPipeName, fallbackSocket} = require('./session-socket');
255
+ const socketElsewhere = (p) => (process.platform === 'win32' ? isPipeName(p) : p === fallbackSocket({env}));
256
+ if (!under(args[0])) return `entry ${args[0]}`;
257
+ for (let i = 1; i < args.length - 1; i++) {
258
+ if (args[i] === '--sessionSocket' && socketElsewhere(args[i + 1])) continue;
259
+ if (PATH_OPTIONS.includes(args[i]) && !under(args[i + 1])) return `${args[i]} ${args[i + 1]}`;
260
+ }
261
+ return null;
262
+ }
263
+
264
+ // session: {socket, home, signal?, onListening?} runs the shared runtime for
265
+ // ch-local daemon (countinghouse #236): framework.js on --sessionSocket
266
+ // instead of --stdio. Its clients' own inputs (the client checks, the
267
+ // repository) come per session from the native shim, so this start reads
268
+ // none of its own. In this mode (the review of ch-local #32):
269
+ // - the home is session.home, never COUNTINGHOUSE_HOME or ~/.countinghouse;
270
+ // - the runtime's environment is shim.json's allowlist of io.env and, from
271
+ // gh, COUNTINGHOUSE_GITHUB_TOKEN, nothing else;
272
+ // - only SIGINT and SIGTERM are trapped (the daemon ignores SIGHUP), and the
273
+ // runtime runs in its own process group, so a terminal's hang-up never
274
+ // reaches it;
275
+ // - session.signal's abort stops the runtime (SIGTERM), and the start ends
276
+ // with its exit;
277
+ // - the runtime's {type: 'listening', socket} goes to session.onListening;
278
+ // - session.restore() is sent as the first control request, the table's
279
+ // tells go to session.onTold, and session.onControl is handed a sender
280
+ // for the daemon's own requests (C3a).
281
+ // home: the home `--home` named (absolute, real), over COUNTINGHOUSE_HOME
282
+ // ownRuntime: {reason?, why?} when the native shim handed this session over
283
+ // because it can't share the daemon's runtime (bin/ch-local.js)
284
+ async function start({passThrough, session = null, home = null, ownRuntime = null}, io) {
285
+ const fail = (s, code = 1) => { io.stderr.write(`ch-local: ${s}\n`); return code; };
286
+ const say = (s) => io.stderr.write(`ch-local: ${s}\n`);
287
+
288
+ // Before anything is written: a signal now cleans up and exits; once the
289
+ // runtime runs, each signal is forwarded to it once.
290
+ let child = null;
291
+ let runDir = null;
292
+ let stopped = null;
293
+ const forwarded = new Set();
294
+ const untrap = io.trapSignals(...[(signal) => {
295
+ if (child != null) {
296
+ if (!forwarded.has(signal)) { forwarded.add(signal); child.kill(signal); }
297
+ return;
298
+ }
299
+ if (stopped != null) return;
300
+ stopped = 128 + (SIGNALS[signal] || 15);
301
+ if (runDir != null) fs.rmSync(runDir, {recursive: true, force: true});
302
+ io.exit(stopped);
303
+ }, ...(session != null ? [['SIGINT', 'SIGTERM']] : [])]);
304
+ try {
305
+ // one platform for every decision of this start
306
+ const platform = io.platform || process.platform;
307
+ const where = layout(session != null ? {COUNTINGHOUSE_HOME: session.home} : home != null ? {...io.env, COUNTINGHOUSE_HOME: home} : io.env, io.homedir);
308
+ // a home another user could change starts nothing: its app is loaded and
309
+ // every stored key given to it (the reviewer's pre-work high,
310
+ // A-home-check, 3; with --home the command line checked it too)
311
+ {
312
+ const {homeOpenProblem, HOME_OPEN} = require('./home');
313
+ // (on this machine's own filesystem, by its own platform: never one a
314
+ // caller simulates, whose rule would judge the wrong kind of folder)
315
+ const open = homeOpenProblem(where.home, {fileAcl: process.platform === 'win32' && io.winAcl != null ? io.winAcl.fileAcl : null, principalNames: process.platform === 'win32' && io.winAcl != null ? io.winAcl.principalNames : null});
316
+ if (open != null) return fail(`${where.home} ${open.why.replace(/^it /, '')}, ${open.consequence || HOME_OPEN}${open.fix != null ? `; ${open.fix}${open.final ? '' : ', then start again'}` : ''}; nothing was started`, 2);
317
+ }
318
+ // whether the installed runtime runs enforce here (Windows: from countinghouse#195)
319
+ const enforceOk = enforceAvailable(where, platform);
320
+ const checked = checkPassThrough(passThrough, platform, enforceOk, where);
321
+ if (checked.problem != null) return fail(checked.problem, 2);
322
+ const mapped = remoteMap(io.env);
323
+ if (mapped.problem != null) return fail(mapped.problem, 2);
324
+
325
+ // The run directory and its run.json come first, the record read and
326
+ // run.json written under the home's lock, which collection holds: no tree
327
+ // this start reads can be collected before run.json names it (the review
328
+ // of ch-local #13). The lock is waited for; a wait given up on (another
329
+ // host's lock, or one that can't be read, or a holder here that stopped
330
+ // renewing it: lib/lock.js waitRemoteMs) fails the start, which never
331
+ // goes on without the lock (the medium on post-rel packs.lock, 1).
332
+ const host = hostTag(io.hostname);
333
+ runDir = path.join(where.run, `${host}-${io.pid}-${crypto.randomBytes(4).toString('hex')}`);
334
+ const runFile = path.join(runDir, 'run.json');
335
+ // chLocal: this start's own ch-local, so status can name a running client
336
+ // still on another one (#413 section 9.9); null for one not run from the
337
+ // home (a checkout), as recordRelease takes it: never called stale
338
+ // shared, ownSeen, ownAt: what add-module and remove-module wait for
339
+ // (lib/own-applied.js; the applier writes ownSeen)
340
+ let run = {host, machine: machineId(), pid: io.pid, childPid: null, startedAt: Date.now(), loaded: {}, shared: session != null, ownSeen: null, ownAt: null,
341
+ chLocal: io.selfVersion !== undefined ? io.selfVersion : (runsFromHome(where) ? require('../package.json').version : null)};
342
+ const writeRunFile = () => writeAtomic(runFile, JSON.stringify(run) + '\n');
343
+ let record;
344
+ let recordProblem = null;
345
+ let locked = false;
346
+ await withLock(where, io, async () => {
347
+ locked = true;
348
+ try { record = readRecord(where); } catch (err) { recordProblem = err.message; return 1; }
349
+ if (record == null) return 0;
350
+ fs.mkdirSync(runDir, {recursive: true});
351
+ // every installed module version (#413 section 9.8): none of what this
352
+ // start may load is collected meanwhile (lib/gc.js collectStore)
353
+ run.loaded = Object.assign({}, ...installedPacks(where, record, io).map((p) => p.modules));
354
+ writeRunFile();
355
+ return 0;
356
+ }, {wait: true, signal: session != null ? session.signal : null});
357
+ if (session != null && session.signal != null && session.signal.aborted) return fail('stopped before the shared runtime started');
358
+ // (the held line said why)
359
+ if (!locked) return fail('the home\'s lock could not be taken; nothing was started');
360
+ if (recordProblem != null) return fail(recordProblem);
361
+ // nothing installed: no runtime to start, whatever own.json holds (the
362
+ // reviewer's high on #113, 3)
363
+ // (the npx form, before an install: the home in words on Windows -- the
364
+ // closing pass, L3)
365
+ if (record == null) return fail(`no pack is installed; run ${hintCommand(where, 'install --pack <name>', platform)}`);
366
+ const installed = installedPacks(where, record, io);
367
+ // withdrawn packs (#413 section 9.7): one this release does not list, or
368
+ // one the record's withdrawn list names (an upgrade's own pins wrote
369
+ // it); never started, said once the client can be told (below); nothing
370
+ // of them is removed
371
+ // (a home whose every pack was removed starts for its own modules alone:
372
+ // B-own-add, the reviewer's ruling (b); one own.json can't be read for
373
+ // counts as none here, and its line is said below when there are packs)
374
+ const ownNames = (() => { try { const r = readOwnRecord(where); return r != null ? Object.keys(r.modules) : []; } catch (e) { return []; } })();
375
+ if (installed.length === 0 && ownNames.length === 0) return fail(`no pack is installed; run ${hintCommand(where, 'install --pack <name>', platform)}`);
376
+ const gone = withdrawnNames(record, installed, releaseOf(io));
377
+ const withdrawn = installed.filter((p) => gone.has(p.name));
378
+ const packs = installed.filter((p) => !withdrawn.includes(p));
379
+ if (record.unreleased) say(UNRELEASED_LINE);
380
+
381
+ // The runtime's environment, an allowlist either way: a session runtime
382
+ // (the daemon's) gets the daemon's keys (lib/shim-config.js allowedEnv),
383
+ // a runtime of its own those and the locale, the CA bundle and the
384
+ // runtime's own switches (runtimeEnv), never the client's whole
385
+ // environment. Every credential comes from the store, bound to its
386
+ // module, in a slot of its own (#413 section 6.4; L5a:
387
+ // lib/module-credentials.js forStart, below), never from a client's
388
+ // environment (section 6.9; the Reviewer's high review of L5a, 1).
389
+ const env = session != null ? allowedEnv(io.env, platform) : runtimeEnv(io.env, platform);
390
+
391
+ // settings (packs in place, part 2): a pack turned off is not loaded
392
+ // A settings file that is not valid stops the start: its defaults would
393
+ // load a pack the user turned off and loosen a limit the user tightened
394
+ // (the review of ch-local #13).
395
+ // Part 3, section 5, never silent: what start says about the settings and
396
+ // the operator's ceiling (an outside edit, a clamp, a refusal) goes on
397
+ // stderr and, once the runtime is up, to the client as notices (the next
398
+ // result of any tool, and notifications/message): the model relays them,
399
+ // so stderr and the history stay the record it cannot edit.
400
+ const notices = teller(say);
401
+ const tell = notices.tell;
402
+ const settings = readSettings(where);
403
+ if (settings.error != null) return fail(`${settings.error}: not starting; fix it (\`${chLocal(where, 'settings reset')}\` replaces every setting with its default, asking first if that loosens one)`);
404
+ if (settings.warning != null) say(settings.warning);
405
+ // part 3, section 5: a setting changed outside the tools is said and
406
+ // recorded (under the settings lock: a change under way is not one)
407
+ // part 3, section 4: the operator's ceiling binds the values and flags
408
+ // this start passes; one that cannot be trusted refuses a start that
409
+ // loosens. An outside loosening it refuses (a pack turned on, say) is not
410
+ // applied.
411
+ const ceiling = ceilingFor(where, {platform, env: io.env});
412
+ try {
413
+ const edits = withSettingsLock(where, () => reportOutsideEdits(where, readSettings(where), {say: (line) => tell(line, {fit: false}), host, pid: process.pid, refusal: forbiddenBy(ceiling)}));
414
+ for (const e of edits) {
415
+ if (e.refused == null) continue;
416
+ if (valueOf({values: {}}, e.setting) === e.old) delete settings.values[e.setting]; else settings.values[e.setting] = e.old;
417
+ }
418
+ } catch (err) {
419
+ // a lock held (by another writer, or kept fresh on purpose) never
420
+ // turns the checks off: a loosening the history has not recorded is
421
+ // not applied this start, the recorded value is
422
+ const kept = [];
423
+ for (const e of outsideEdits(where, settings)) {
424
+ if (!e.loosened) continue;
425
+ if (valueOf({values: {}}, e.setting) === e.old) delete settings.values[e.setting]; else settings.values[e.setting] = e.old;
426
+ kept.push(e.setting);
427
+ }
428
+ tell(`could not compare the settings with their history (${err.code || err.message})${kept.length > 0 ? `: ${kept.join(', ')} not loosened this start` : ''}`);
429
+ }
430
+ const bounded = startUnderCeiling(settings, ceiling, {
431
+ where,
432
+ forcedAudit: !enforceOk,
433
+ passedAudit: checked.options.some((o, i) => o === '--moduleSandbox=audit' || (o === '--moduleSandbox' && checked.options[i + 1] === 'audit'))
434
+ });
435
+ if (bounded.problem != null) return fail(bounded.problem);
436
+ // (the outcome first, its command in the middle: cut at the end)
437
+ for (const note of bounded.notes) tell(note, {fit: false});
438
+ let auditSaid = false;
439
+ if (!enforceOk && !checked.sandbox && valueOf(settings, 'moduleSandbox') !== 'audit') { tell(windowsAudit(where)); tell(AUDIT_LINE); auditSaid = true; }
440
+ settings.values = bounded.values;
441
+ // What loads, by module (#413 section 5.2; L2a): each available top-level
442
+ // module, once, with the closure it needs; every unavailable one said
443
+ // once, with its reason. On/off, the ceiling and the credential stay
444
+ // today's, behind the seams L2b replaces (by the pack whose scenario the
445
+ // module is: pack.<p>, the ceiling's packs, the release's version 1
446
+ // credentials).
447
+ // each installed module's credential, from the store (section 6.7): its
448
+ // state is availability's rule 5, and a usable one gets its slot
449
+ // the modules whose "sends" line was said (the applier says one loaded later)
450
+ const sendsSaid = new Set();
451
+ const decls = moduleCredentials.declarations(where, record);
452
+ // a key read from GitHub's earlier name, said once a start; never
453
+ // rewritten here (the Reviewer's cut on #98's round 3)
454
+ const read = moduleCredentials.bindings(where, record, {platform, decls});
455
+ moduleCredentials.carriedLines(read, where).forEach((line, i) => tell(line, {about: short(read.carried[i].module)}));
456
+ const creds = await moduleCredentials.forStart(where, record, {env, ghToken: () => ghToken(io, where.home), platform, shared: session != null, acceptanceMap: mapped.args.length > 0, decls, read});
457
+ // #413 section 10: a GitHub token a client's configuration still sets is
458
+ // not moved and not read; said once per start (a session runtime never
459
+ // sees a client's environment)
460
+ const oldToken = session == null && io.env != null ? io.env.COUNTINGHOUSE_GITHUB_TOKEN : null;
461
+ if (typeof oldToken === 'string' && oldToken.trim() !== '') {
462
+ const gh = [...creds.decls].find(([, d]) => d.problem == null && d.origin === moduleCredentials.GH_ORIGIN);
463
+ tell(`COUNTINGHOUSE_GITHUB_TOKEN in this client's environment is no longer read: run \`${chLocal(where, `credentials add ${gh != null ? gh[0].replace(/^@[^/]+\//, '') : '<module>'}`)}\``);
464
+ }
465
+ // a record of another release (a ch-local older than the record: a
466
+ // daemon or binary still running from before an upgrade) is judged by
467
+ // none of this start's pins, as the applier judges it (section 9.8; the
468
+ // high review of L2a, 3)
469
+ // whose record this is: one rule with the applier (lib/packs.js
470
+ // recordRelease); each case said once, the applier never repeating it
471
+ const whose = recordRelease(record, io, where);
472
+ if (whose.state === 'stale') tell(staleLine(whose.installed, whose.how, where, session != null));
473
+ if (whose.state === 'other') tell(installLine(whose.ours, where, record, whose.fromHome));
474
+ // the user's own modules (B-own-add; the own-modules design §2.2): an
475
+ // own.json that can't be read loads none of them, said; the packs load.
476
+ // Each loads only under enforce, decided once for this start (a change
477
+ // of the sandbox applies at the next one).
478
+ let ownRecord = null;
479
+ try { ownRecord = readOwnRecord(where); } catch (err) {
480
+ // (the record by its name: its problem is what must fit)
481
+ tell(err.reason != null ? `your own modules are not loaded: ${err.reason.replace(where.ownRecord, path.basename(where.ownRecord))}; \`${chLocal(where, 'status')}\` shows them` : `your own modules are not loaded this start: ${err.message}`);
482
+ }
483
+ const ownSandboxOk = sandboxModeOf(checked, settings, enforceOk) === 'enforce';
484
+ const av = availability(where, record, {release: releaseOf(io), pins: whose.state !== 'stale', seams: Object.assign(moduleSeams({settings, ceiling, record, where}), {credential: moduleCredentials.credentialSeam(creds.states)}),
485
+ own: {record: ownRecord, sandboxOk: ownSandboxOk}});
486
+ // one turned off is the user's own doing: said here, never told
487
+ for (const [m, u] of av.unavailable) if (u.kind === 'off') say(u.line); else tell(u.line, {about: short(m)});
488
+ for (const [m, u] of av.shadowed) tell(u.line, {about: short(m)});
489
+ // the modules held back, and why, for the runtime's overview: a private
490
+ // file it reads at start, and again on the applier's reread
491
+ // (lib/held-back.js; A-firstrun d1). Written whatever the record; the
492
+ // applier rewrites it after each apply, from what ended up loaded, under
493
+ // another release's record too. If it can't be written, no flag is passed
494
+ // and the overview has no reasons to give.
495
+ const heldText = heldBack.contentOf(where, av.unavailable, platform);
496
+ let heldBackFile = null;
497
+ try { heldBackFile = heldBack.write(runDir, heldText); } catch (e) { say(`the overview will not say which modules are held back this start (${e.code || e.message})`); }
498
+ // the withdrawn modules this start has told about (the applier's own
499
+ // unload never repeats one)
500
+ const withdrawnTold = new Set([...av.unavailable].filter(([, u]) => u.withdrawn).map(([m]) => m));
501
+ let load = av.units;
502
+ // a session the shim handed over: told why it runs its own runtime, in
503
+ // its first result's notice (#236 section 5), never a credential's value
504
+ if (ownRuntime != null) {
505
+ // (token and credential: no longer produced by this ch-local's
506
+ // conditions check, #413 section 6.9; still read from an older shim)
507
+ if (ownRuntime.reason === 'token') tell('this session chooses a GitHub token the shared runtime doesn\'t hold, so it runs its own runtime');
508
+ else if (ownRuntime.reason === 'credential') tell('a pack credential in this session\'s environment isn\'t the shared runtime\'s, so it runs its own runtime');
509
+ else if (ownRuntime.reason === 'conditions-failed') tell(`the client checks could not run${ownRuntime.why ? ` (${ownRuntime.why})` : ''}, so this session runs its own runtime`);
510
+ // a reason the shim passed that this ch-local doesn't know; with none
511
+ // (an older shim, or the startup and failed.json fallbacks, where no
512
+ // shared runtime refused anything) nothing is told
513
+ else if (ownRuntime.reason != null) tell(`this session can't share the runtime${ownRuntime.reason !== 'unknown' ? ` (${ownRuntime.reason})` : ''}, so it runs its own`);
514
+ }
515
+ // (a module whose files are not all placed is not available: its reason
516
+ // was said above, and the healthy ones load)
517
+ if (load.length === 0) tell('no module is loaded this start; only ch-local\'s own tools (settings, the usage report) are served');
518
+
519
+ // the runtime's environment, every inherited COUNTINGHOUSE_CREDENTIAL_*
520
+ // removed and each usable binding's slot added; its --remoteCredentials,
521
+ // version 2: per module, origin and variable, the slot (section 6.4).
522
+ // Under an acceptance run's map only an acceptance token has a slot
523
+ // (forStart): a real key never reaches whatever listens on the mapped port.
524
+ const childEnv = creds.env;
525
+ const chosen = creds.file;
526
+
527
+ const configDir = path.join(runDir, 'config');
528
+ const remoteCredentials = path.join(runDir, 'remote-credentials.json');
529
+ try {
530
+ fs.mkdirSync(configDir, {recursive: true});
531
+ writeAtomic(remoteCredentials, JSON.stringify(chosen, null, 2) + '\n');
532
+ // (no device config: the scenario's defaultRepo is its own setting since
533
+ // #413 rev 3's P1 and P3; --deviceConfigPath names this empty
534
+ // directory, so the runtime reads none from anywhere else)
535
+ sweepRuns(where.run, host, io.alive);
536
+ // what this start's runtime loads, for collection (lib/gc.js): a
537
+ // version a live start names is never removed under it. Every installed
538
+ // version was named under the home's lock above, so none of these can
539
+ // have been collected since
540
+ run = {...run, loaded: Object.assign({}, ...load.map((p) => p.modules)), stopped: {}};
541
+ writeRunFile();
542
+ if (stopped != null) return stopped;
543
+ for (const p of load) if (p.own !== true) say(`loading ${p.short}`);
544
+ const ownLoading = load.filter((p) => p.own === true);
545
+ if (ownLoading.length > 0) say(`own modules: ${ownLoading.map((p) => `${p.short} ${p.version.slice(0, 12)}`).join(', ')}`);
546
+ // the own modules' root, there for one added while this start runs
547
+ // (private to this user -- the copies are the user's own code -- made
548
+ // so, or kept so when an earlier one made it otherwise: C's upgrade
549
+ // test, the reviewer; the medium on B-own-settings, 8)
550
+ fs.mkdirSync(where.own, {recursive: true, mode: 0o700});
551
+ if (platform !== 'win32') require('./own-tree').chmodNoFollow(where.own, 0o700);
552
+ // (only for a module this start loads: a slot given for one turned on
553
+ // later is said when it loads; the Reviewer's high review of L5a, 6)
554
+ const loading = new Set(load.flatMap((p) => Object.keys(p.modules)));
555
+ for (const [m, id] of creds.identities) {
556
+ if (loading.has(m)) sendsSaid.add(m);
557
+ if (loading.has(m)) say(`sends ${id.variable} to ${id.origin} for ${m.replace(/^@[^/]+\//, '')}${id.source === 'gh' ? ' (your gh login\'s token, held in memory)' : ''}`);
558
+ }
559
+ for (const note of mapped.notes) say(note);
560
+ const args = [
561
+ ...(session != null
562
+ // --sessionDir (countinghouse C2): the secret's directory, which a
563
+ // Windows pipe has none of, and the long-home fallback's apart from it
564
+ ? [path.join(where.app, 'node_modules', 'countinghouse', 'framework.js'), '--sessionSocket', session.socket,
565
+ ...(session.sessionDir != null ? ['--sessionDir', session.sessionDir] : [])]
566
+ : [path.join(where.app, 'node_modules', 'countinghouse', 'bin', 'countinghouse-stdio.js')]),
567
+ '--workerThread',
568
+ '--store', 'local',
569
+ '--storePath', where.store,
570
+ ...sandboxArgs(checked, settings, enforceOk),
571
+ '--modulePath', where.modules,
572
+ '--moduleDataPath', where.moduleData,
573
+ '--remoteCredentials', remoteCredentials,
574
+ '--deviceConfigPath', configDir,
575
+ ...load.flatMap((p) => ['--loadModule', p.dir]),
576
+ // each part one of them needs, by its store directory (#413 section
577
+ // 9.8): the runtime looks for a part among these only
578
+ ...[...new Set(load.flatMap((p) => p.packages.filter((m) => m !== p.scenario).map((m) => p.dirs[m])))].flatMap((d) => ['--partDir', d]),
579
+ // the settings the runtime takes at start
580
+ ...settingArgs(settings),
581
+ // packs in place (part 2): the runtime's control channel; a runtime
582
+ // older than the channel ignores the flag, and changes then need a
583
+ // restart (lib/control.js)
584
+ '--controlChannel', 'ipc',
585
+ // where every module the start and the channel load lies (#413
586
+ // section 7.2): the runtime refuses a directory whose real path is
587
+ // outside it, or that has a link leading out
588
+ '--modulesRoot', where.moduleStore,
589
+ // and the user's own modules' copies (B-own-add)
590
+ '--modulesRoot', where.own,
591
+ // the file countinghouse_settings changes, by the protocol in
592
+ // docs/development/settings.md; an older runtime ignores the flag
593
+ '--settingsFile', where.settings,
594
+ // what this start held back (lib/held-back.js); an older runtime
595
+ // ignores the flag
596
+ ...(heldBackFile != null ? ['--heldBackFile', heldBackFile] : []),
597
+ // acceptance runs only: the stand-in's origin map (CH_LOCAL_REMOTE_MAP)
598
+ ...mapped.args,
599
+ ...checked.options
600
+ ];
601
+ // under audit, however it came to be: what audit does, once
602
+ const underAudit = args.some((a, k) => a === '--moduleSandbox=audit' || (a === '--moduleSandbox' && args[k + 1] === 'audit'));
603
+ if (underAudit && !auditSaid) tell(AUDIT_LINE);
604
+ // the client's conditions for a dialog, scanned at this start (a hook
605
+ // seen now holds for the whole start)
606
+ // (in the background: the client's ancestry takes seconds on Windows)
607
+ const conditionArgs = {home: typeof io.homedir === 'function' ? io.homedir() : io.homedir, cwd: io.cwd, env: io.env, platform};
608
+ // a session runtime's conditions are each session's (the shim's
609
+ // `conditions` child); this start has no one client to scan
610
+ const conditions = session != null
611
+ ? {check: async() => ({mayElicit: false, why: 'a shared runtime asks each session'})}
612
+ : conditionsService(conditionArgs, io.clientAncestry !== undefined ? {ancestry: io.clientAncestry} : {});
613
+ // a session runtime (ch-local daemon, from the shim's shim.json), or
614
+ // the shim's own-runtime hand-over (--home): every path it is given
615
+ // must resolve under the home, so a link or a config can't point the
616
+ // runtime elsewhere
617
+ if (session != null || home != null) {
618
+ const outside = pathsOutside(args, where.home, {env: io.env});
619
+ if (outside != null) return fail(`the shared runtime's ${outside} resolves outside the home; nothing was started`);
620
+ }
621
+ if (session != null && session.signal != null && session.signal.aborted) return fail('stopped before the shared runtime started');
622
+ // (a shared runtime's stdout and stderr to the daemon's log: under
623
+ // --sessionSocket MCP is on the session socket, its stdout only its
624
+ // log -- C-daemon-log. A client's own runtime keeps the client's)
625
+ child = io.spawn(io.node, args, {env: childEnv, control: true, ...(session != null ? {detached: true, ...(io.runtimeOutput != null ? {output: io.runtimeOutput} : {})} : {})});
626
+ // stopped: SIGTERM, then SIGKILL after the bound, for a runtime that
627
+ // is hung and ignores SIGTERM
628
+ if (session != null && session.signal != null) {
629
+ session.signal.addEventListener('abort', () => {
630
+ child.kill('SIGTERM');
631
+ const t = setTimeout(() => child.kill('SIGKILL'), Number.isInteger(io.sessionKillMs) ? io.sessionKillMs : SESSION_KILL_MS);
632
+ if (typeof t.unref === 'function') t.unref();
633
+ child.exited.then(() => clearTimeout(t), () => clearTimeout(t));
634
+ }, {once: true});
635
+ }
636
+ // the runtime's pid too: collection keeps this start's trees while
637
+ // either lives; and a heartbeat, for a start on another machine
638
+ if (Number.isInteger(child.pid)) { run = {...run, childPid: child.pid}; writeRunFile(); }
639
+ const heartbeat = setInterval(() => { try { const t = new Date(); fs.utimesSync(runFile, t, t); } catch (err) { /* ending */ } }, HEARTBEAT_MS);
640
+ if (typeof heartbeat.unref === 'function') heartbeat.unref();
641
+ let watcher = null;
642
+ // the in-place applier, closed when this start ends
643
+ let applier = null;
644
+ let credentialsWatcher = null;
645
+ if (typeof child.send === 'function' && typeof child.onMessage === 'function') {
646
+ const loaded = new Map(load.map((p) => [p.name, {version: p.version, scenario: p.scenario, modules: p.modules, ...(p.own === true ? {own: true, added: p.added} : {})}]));
647
+ const control = controlClient(child, {timeoutMs: io.controlTimeoutMs, readyMs: io.controlReadyMs});
648
+ if (session != null && typeof session.onListening === 'function') {
649
+ control.onTold('listening', (m) => session.onListening({type: 'listening', socket: m.socket}));
650
+ }
651
+ // the daemon's table (C3a): its restore is the first request, sent
652
+ // as soon as the channel is ready; the table's tells go to it; and the
653
+ // daemon gets a sender for its own requests (the idle stop)
654
+ // a runtime that ends settles its pending requests at once
655
+ child.exited.then(() => control.close(), () => control.close());
656
+ if (session != null) {
657
+ if (typeof session.onTold === 'function') {
658
+ for (const type of TABLE_TELLS) control.onTold(type, (m) => session.onTold(m));
659
+ }
660
+ if (typeof session.restore === 'function') {
661
+ control.request(session.restore()).then((reply) => {
662
+ if (reply == null || reply.ok !== true) {
663
+ say(`the shared runtime did not take the session table (${reply != null ? reply.code : 'no answer'})`);
664
+ // only the runtime's own refusal: no answer, or a runtime that
665
+ // ended (CONTROL_GONE), says nothing about the table
666
+ if (reply != null && RESTORE_REFUSALS.includes(reply.code) && typeof session.onRestoreRefused === 'function') session.onRestoreRefused();
667
+ }
668
+ });
669
+ }
670
+ if (typeof session.onControl === 'function') session.onControl((msg) => control.request(msg));
671
+ }
672
+ notices.attach(control);
673
+ // may the client be asked to confirm a loosening in a dialog
674
+ // (countinghouse part 3 P2, Task 4)? Scanned now, latching a hook
675
+ // seen for this whole start, and again on every request.
676
+ control.onRequest('may-elicit', async (m) => {
677
+ const client = m.client != null && typeof m.client.name === 'string' ? {name: m.client.name, version: String(m.client.version)} : null;
678
+ return conditions.check(client);
679
+ });
680
+ applier = inPlace({where, io, runDir, shared: session != null, identities: creds.identities, credentialStates: creds.states, credentialSeen: creds.seen, credentialDecls: creds.decls, sendsSaid, control, loaded, say, host, withdrawnTold,
681
+ tell, told: notices.told, settings, runtimeVersions: record.runtime.versions, record, ownSandboxOk, sandboxPassed: checked.sandbox,
682
+ // the held-back file's text start wrote (null: none was written)
683
+ heldBack: heldBackFile != null ? heldText : null});
684
+ // a module the runtime stopped for good (#413 section 7.3)
685
+ control.onTold('module-stopped', (m) => { applier.moduleStopped(m).catch(() => {}); });
686
+ watcher = watchFiles(where.home, ['modules.json', 'settings.json', 'own.json'], () => { applier.apply(); });
687
+ // and the credential store (#413 section 6.4): a removed or changed
688
+ // key unloads its module at once; a new one is said
689
+ credentialsWatcher = watchFiles(path.join(where.home, 'credentials'), ['credentials.json'], () => { applier.apply(); });
690
+ // a change made between reading the home and watching it
691
+ applier.apply();
692
+ }
693
+ // the opt-in automatic upgrade check, at most daily (or weekly), in the
694
+ // background: never in the way of the runtime, and abandoned when start
695
+ // ends (a registry that never answers cannot keep start alive)
696
+ const checking = new AbortController();
697
+ // (its lines are notices: in shared mode start's stderr is the
698
+ // daemon's, which no client reads -- A8; one that comes after this
699
+ // start ended is said on stderr alone, with no client to tell: the
700
+ // medium on A8, 3)
701
+ require('./auto-upgrade').autoCheck({where, io, say: (line) => (checking.signal.aborted ? say(line) : tell(line, {fit: false})), host, signal: checking.signal}).catch(() => {});
702
+ try {
703
+ return await child.exited;
704
+ } finally {
705
+ // (no applier timer outlives this start: the reviewer's high on #106, 1)
706
+ if (applier != null) applier.close();
707
+ clearInterval(heartbeat);
708
+ checking.abort();
709
+ if (watcher != null) watcher.stop();
710
+ if (credentialsWatcher != null) credentialsWatcher.stop();
711
+ }
712
+ } finally {
713
+ fs.rmSync(runDir, {recursive: true, force: true});
714
+ }
715
+ } finally {
716
+ untrap();
717
+ if (runDir != null) fs.rmSync(runDir, {recursive: true, force: true});
718
+ }
719
+ }
720
+
721
+ module.exports = {start, repoFromRemote, originUrl, readOrigin, checkPassThrough};