@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,99 @@
1
+ 'use strict';
2
+ // A release's packages from npm (docs/development/auto-upgrade.md, "The trust
3
+ // chain", steps 2-7), for install with no --from and for upgrades.
4
+ // - Each package but ch-local is fetched at its pinned version and must match
5
+ // its pin (lib/npm-fetch.js), then pass its provenance against the pin's
6
+ // identity (lib/provenance.js).
7
+ // - ch-local itself can't be pinned by its own release: it is fetched at the
8
+ // release's version, and its provenance, against release-pins.json's self
9
+ // identity and the tag v<version>, is its only anchor. The digest so
10
+ // verified becomes its pin, held in memory.
11
+ // - Nothing is written until every package has passed. Then each checked
12
+ // tarball goes into `dir` under its release name, for install's
13
+ // loadTarballs, which re-reads each one against these pins.
14
+ // - The runtime lockfile is copied with ch-local's entry filled in from that
15
+ // digest (the lockfile is inside ch-local's tarball, so it can't carry it).
16
+ // The copy is held to lib/lockfile-rules.js, the rules --unreleased-pins
17
+ // uses too, with the verified tarballs (the review of #42).
18
+ // Each failure is an Error with a code, and `package` naming the one at fault.
19
+ const {integrityOf} = require('./integrity');
20
+ const fs = require('node:fs');
21
+ const path = require('node:path');
22
+ const npmFetch = require('./npm-fetch');
23
+ const provenance = require('./provenance');
24
+ const {tarballName} = require('./unpack');
25
+ const {lockfileProblem} = require('./lockfile-rules');
26
+
27
+ const SELF = '@countinghouse/ch-local';
28
+ // the runtime's packages, whose verified tarballs cover what they bundle
29
+ const RUNTIME = [SELF, 'countinghouse'];
30
+ const STRICT = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/;
31
+
32
+ const failure = (code, message, pkg = null) => Object.assign(new Error(message), {code}, pkg != null ? {package: pkg} : {});
33
+
34
+ // the runtime lockfile, with ch-local's entry's integrity -> a copy, held to
35
+ // lib/lockfile-rules.js against the pins and the verified tarballs; null
36
+ // stays null (no release has made one yet)
37
+ function fillLockfile(lockfile, selfIntegrity, {pins, tarballs = null}) {
38
+ if (lockfile == null) return null;
39
+ const copy = JSON.parse(JSON.stringify(lockfile));
40
+ const selfKey = `node_modules/${SELF}`;
41
+ if (copy.packages == null || copy.packages[selfKey] == null) throw failure('LOCKFILE_INTEGRITY', `the runtime lockfile has no entry for ${SELF}`);
42
+ copy.packages[selfKey].integrity = selfIntegrity;
43
+ const why = lockfileProblem(copy, {runtime: RUNTIME, pins, tarballs});
44
+ if (why != null) throw failure('LOCKFILE_INTEGRITY', why);
45
+ return copy;
46
+ }
47
+
48
+ // {data (parsed release pins), version (ch-local's), names, dir, io,
49
+ // registry?, trust?} -> {pins (with ch-local's), lockfile, published: {name: Date}}
50
+ // registry and trust: only a test's own code passes them.
51
+ // verifiedSelf: an upgrade's ch-local, already fetched and checked by its
52
+ // provenance (lib/npm-upgrade.js), {version, bytes, integrity, publishedAt,
53
+ // identity: the INSTALLED release's self}: installed as given, never fetched
54
+ // again, so the bytes its pins were read from are the bytes installed.
55
+ async function fetchRelease({data, version, names, dir, io, registry = npmFetch.REGISTRY, trust = null, verifiedSelf = null}) {
56
+ if (names.includes(SELF) && (typeof version !== 'string' || !STRICT.test(version))) {
57
+ throw failure('NOT_STRICT', `${SELF}'s version ${JSON.stringify(version)} is not strict MAJOR.MINOR.PATCH`, SELF);
58
+ }
59
+ for (const name of names) {
60
+ if (name !== SELF && data.pins[name] == null) throw failure('NOT_PINNED', `no pin names ${name} in this release`, name);
61
+ }
62
+ const pins = Object.assign({}, data.pins);
63
+ const fetched = {};
64
+ const published = {};
65
+ for (const name of names) {
66
+ const own = name === SELF;
67
+ const at = own ? version : data.pins[name].version;
68
+ if (own && verifiedSelf != null) {
69
+ if (verifiedSelf.version !== version) throw failure('SELF_MISMATCH', `the verified ${SELF} is ${verifiedSelf.version}, not ${version}`, SELF);
70
+ const got = integrityOf(verifiedSelf.bytes);
71
+ if (got !== verifiedSelf.integrity) throw failure('INTEGRITY_MISMATCH', `the verified ${SELF}'s bytes are not its integrity`, SELF);
72
+ fetched[name] = verifiedSelf.bytes;
73
+ pins[name] = Object.assign({version, integrity: verifiedSelf.integrity}, verifiedSelf.identity, {tag: `v${version}`});
74
+ published[name] = verifiedSelf.publishedAt;
75
+ continue;
76
+ }
77
+ try {
78
+ // ch-local: no pin to hold its fetch to; its provenance decides
79
+ const {bytes, integrity} = await npmFetch.fetchTarball(name, at, io, {registry, pin: own ? null : data.pins[name]});
80
+ const pin = own ? Object.assign({version: at, integrity}, data.self, {tag: `v${at}`}) : data.pins[name];
81
+ const attestations = await npmFetch.attestations(name, at, io, {registry});
82
+ const times = provenance.verifyRelease({name, version: at, pin, attestations, trust});
83
+ fetched[name] = bytes;
84
+ pins[name] = pin;
85
+ published[name] = times.publishedAt;
86
+ } catch (e) {
87
+ throw Object.assign(e, {package: name});
88
+ }
89
+ }
90
+ // the runtime's lockfile, when the runtime is among them (a pack alone
91
+ // needs none), checked before anything is written
92
+ const lockfile = names.includes(SELF) ? fillLockfile(data.runtime.lockfile, pins[SELF].integrity, {pins, tarballs: fetched}) : null;
93
+ // all passed: only now is anything written
94
+ fs.mkdirSync(dir, {recursive: true});
95
+ for (const name of names) fs.writeFileSync(path.join(dir, tarballName(name, pins[name].version)), fetched[name], {flag: 'wx'});
96
+ return {pins, lockfile, published};
97
+ }
98
+
99
+ module.exports = {fetchRelease, fillLockfile, SELF};
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+ // Whether there is a newer ch-local to upgrade to, and what it pins
3
+ // (docs/development/auto-upgrade.md, "The trust chain", steps 1-5):
4
+ // 1. the registry's `latest` @countinghouse/ch-local, considered only if it
5
+ // is strict MAJOR.MINOR.PATCH and newer by precedence than the installed
6
+ // one. Another major is {kind: 'major'}, fetched no further, unless
7
+ // allowMajor (ch-local upgrade, the Reviewer's ruling on #48): then it is
8
+ // checked exactly as any other (provenance, pins, identity changes and
9
+ // additions) and returned as available with major: true. The automatic
10
+ // upgrade never passes it;
11
+ // 2-3. its tarball, fetched with no pin to hold it to, checked by its
12
+ // provenance against the INSTALLED release's own identity (self) and the
13
+ // tag v<version>;
14
+ // 4. its digest, so verified, is its pin, held in memory;
15
+ // 5. its lib/release-pins.json, read from those verified bytes in memory
16
+ // (lib/tar.js readMember: nothing written, nothing of it run), parsed as
17
+ // this release's own is; what it adds that needs the user's yes
18
+ // (additions), and its identity changes, which block an automatic
19
+ // upgrade (identityChanges), are listed.
20
+ // A 0.x minor (0.1 -> 0.2) or a 0.0.x patch is `breaking`: under semver
21
+ // either may break, so the automatic upgrade treats it as a major (the
22
+ // Reviewer's ruling on #48); ch-local upgrade shows it so and asks.
23
+ // The registry and trust are only ever a test's own arguments.
24
+ const npmFetch = require('./npm-fetch');
25
+ const provenance = require('./provenance');
26
+ const {readMembers} = require('./tar');
27
+ const {parseReleasePins, additions, identityChanges} = require('./release-pins');
28
+
29
+ const SELF = '@countinghouse/ch-local';
30
+ const STRICT = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/;
31
+
32
+ const failure = (code, message) => Object.assign(new Error(message), {code});
33
+ const parts = (v) => v.split('.').map(Number);
34
+
35
+ // a newer than b, both strict MAJOR.MINOR.PATCH; anything else is never newer
36
+ function newer(a, b) {
37
+ if (typeof a !== 'string' || typeof b !== 'string' || !STRICT.test(a) || !STRICT.test(b)) return false;
38
+ const [x, y] = [parts(a), parts(b)];
39
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
40
+ return false;
41
+ }
42
+
43
+ // a release's parsed pins and version -> the allow object install takes.
44
+ // found and installedSelf: an upgrade's verified ch-local (findUpgrade's
45
+ // bytes, integrity and publish time) and the INSTALLED release's self, so
46
+ // install installs those same bytes (lib/npm-release.js verifiedSelf).
47
+ function releaseAllow(data, version, {found = null, installedSelf = null} = {}) {
48
+ // (every key install reads, the shim's section too: an upgrade from npm
49
+ // places this platform's native shim, by its pin)
50
+ const allow = {release: {version, security: data.release.security}, self: data.self, shim: data.shim, runtime: data.runtime, packs: data.packs, modules: data.modules, pins: data.pins};
51
+ if (found != null) {
52
+ allow.verifiedSelf = {version, bytes: found.bytes, integrity: found.integrity, publishedAt: found.publishedAt, identity: installedSelf};
53
+ }
54
+ return allow;
55
+ }
56
+
57
+ // {data (the installed release's parsed pins), installed (its version),
58
+ // packs (the installed packs' names), io, registry?, trust?} ->
59
+ // {kind: 'up-to-date'} | {kind: 'major', to} |
60
+ // {kind: 'available', to, data, additions, adds, integrity, publishedAt, builtAt}
61
+ // remembered(version): a version an automatic upgrade already refused under
62
+ // this root, not fetched or checked again -> {kind: 'remembered', to}
63
+ // now: what the home has installed, pins-shaped (lib/installed-description.js:
64
+ // the record, each module described from the store), the baseline additions
65
+ // are judged against (#413 rev 3 section 9.3; L4); identity stays the pins'
66
+ async function findUpgrade({data, now = data, installed, packs, io, registry = npmFetch.REGISTRY, trust = null, remembered = () => false, allowMajor = false}) {
67
+ const doc = await npmFetch.packument(SELF, io, {registry});
68
+ const latest = doc != null && doc['dist-tags'] != null ? doc['dist-tags'].latest : null;
69
+ if (!newer(latest, installed)) return {kind: 'up-to-date'};
70
+ const major = parts(latest)[0] !== parts(installed)[0];
71
+ if (major && allowMajor !== true) return {kind: 'major', to: latest};
72
+ if (remembered(latest)) return {kind: 'remembered', to: latest};
73
+ try {
74
+ return Object.assign(await check(data, latest, packs, io, registry, trust, installed, now), {major});
75
+ } catch (e) {
76
+ // which version failed, for the announcement and the history record
77
+ throw Object.assign(e, {package: SELF, version: latest});
78
+ }
79
+ }
80
+
81
+ // a 0.x minor or a 0.0.x patch change, from installed to latest
82
+ function breaking(latest, installed) {
83
+ const [x, y] = [parts(latest), parts(installed)];
84
+ if (x[0] !== 0 || y[0] !== 0) return false;
85
+ return x[1] !== y[1] || (x[1] === 0 && x[2] !== y[2]);
86
+ }
87
+
88
+ // the Claude Code plugin's manifest in a ch-local package, and its version:
89
+ // a plain x.y.z, or null (none, unreadable, or anything else)
90
+ const PLUGIN_MANIFEST = 'clients/claude-code/.claude-plugin/plugin.json';
91
+ function pluginVersionOf(read) {
92
+ try {
93
+ const text = read();
94
+ if (text == null) return null;
95
+ const v = JSON.parse(String(text)).version;
96
+ return typeof v === 'string' && /^\d+\.\d+\.\d+$/.test(v) ? v : null;
97
+ } catch (e) { return null; }
98
+ }
99
+
100
+ // ch-local's own tarball -> its pins and its Claude Code plugin's manifest
101
+ // (Buffers, or undefined), in one pass. It bundles its @sigstore libraries
102
+ // under node_modules/ (package.json bundleDependencies), so it is read as
103
+ // lib/lockfile-rules.js reads a runtime tarball (the final pass's ch-local
104
+ // part, A1); a pack's tarballs are still read strictly. Throws.
105
+ function readOwnTarball(bytes) {
106
+ return readMembers(bytes, ['lib/release-pins.json', PLUGIN_MANIFEST], {}, {bundled: true});
107
+ }
108
+
109
+ async function check(data, latest, packs, io, registry, trust, installed, now = data) {
110
+ const {bytes, integrity} = await npmFetch.fetchTarball(SELF, latest, io, {registry, pin: null});
111
+ const attestations = await npmFetch.attestations(SELF, latest, io, {registry});
112
+ const times = provenance.verifyRelease({name: SELF, version: latest, attestations, trust,
113
+ pin: Object.assign({version: latest, integrity}, data.self, {tag: `v${latest}`})});
114
+ let member;
115
+ let pluginText = null;
116
+ try {
117
+ // (its pins and its Claude Code plugin's manifest, in one pass)
118
+ const read = readOwnTarball(bytes);
119
+ member = read['lib/release-pins.json'];
120
+ pluginText = read[PLUGIN_MANIFEST];
121
+ } catch (e) {
122
+ throw failure('RELEASE_PINS', `${SELF}@${latest}'s tarball could not be read (${e.message})`);
123
+ }
124
+ if (member == null) throw failure('RELEASE_PINS', `${SELF}@${latest} carries no lib/release-pins.json`);
125
+ const parsed = parseReleasePins(member);
126
+ // its Claude Code plugin's version (clients/claude-code/.claude-plugin/
127
+ // plugin.json in the same verified bytes; absent or unreadable: null), for
128
+ // upgrade's plugin step (A-own-skill's easy upgrades)
129
+ const plugin = pluginVersionOf(() => pluginText);
130
+ // (a later format is marked: the callers, which know the home, name the
131
+ // way out; the medium on the upgrade fix, A1)
132
+ if (parsed.problem != null) throw Object.assign(failure('RELEASE_PINS', parsed.problem), {later: parsed.later === true});
133
+ // identity changes (self's, a pin's) block an automatic upgrade; a manual
134
+ // one shows them and asks (the review of #42)
135
+ const identity = identityChanges(data, parsed.pins, packs);
136
+ // additions: the items (lib/release-pins.js: kind, key, packs, module,
137
+ // line, ...); adds: their lines, as upgrade and the automatic upgrade show
138
+ // them (C's L4 shows the items in its preview)
139
+ // (now may be a function: the home's description, read only here, once a
140
+ // release is found: the medium on L4, 8)
141
+ const adds = additions(typeof now === 'function' ? now() : now, parsed.pins, packs);
142
+ return {kind: 'available', to: latest, plugin, breaking: breaking(latest, installed), data: parsed.pins, additions: adds, adds: adds.map((x) => x.line), identity: identity.blocking, named: identity.named, integrity, bytes,
143
+ publishedAt: times.publishedAt, builtAt: times.builtAt};
144
+ }
145
+
146
+ module.exports = {readOwnTarball, findUpgrade, releaseAllow, newer, breaking, SELF, pluginVersionOf, PLUGIN_MANIFEST};
package/lib/npm.js ADDED
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ // npm as `node npm-cli.js`: no shell on any system (Windows will not spawn
3
+ // npm.cmd without one).
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ // -> npm-cli.js beside the node that runs this ch-local: npm_execpath (npm
8
+ // running us), beside node.exe (Windows), <prefix>/lib/node_modules (the
9
+ // official builds, nvm), Homebrew's <prefix>/libexec/lib/node_modules, or the
10
+ // package <bin>/npm's link leads into. None there: the npx way out, said.
11
+ // (homeEnv: the environment whose home the hint names -- the io's)
12
+ function npmCli({execPath = process.execPath, env = process.env, homeEnv = env} = {}) {
13
+ const fromNpm = env.npm_execpath;
14
+ if (fromNpm && /npm-cli\.js$/.test(fromNpm) && fs.existsSync(fromNpm)) return fromNpm;
15
+ const bin = path.dirname(execPath);
16
+ const cliIn = (pkg) => path.join(pkg, 'bin', 'npm-cli.js');
17
+ for (const candidate of [path.join(bin, 'node_modules', 'npm'), path.join(bin, '..', 'lib', 'node_modules', 'npm'), path.join(bin, '..', 'libexec', 'lib', 'node_modules', 'npm')].map(cliIn)) {
18
+ if (fs.existsSync(candidate)) return candidate;
19
+ }
20
+ // (<bin>/npm a link into npm's package: its bin/npm, beside npm-cli.js)
21
+ let linked = null;
22
+ try { linked = fs.realpathSync.native(path.join(bin, 'npm')); } catch (e) { linked = null; }
23
+ if (linked != null) {
24
+ const candidate = path.join(path.dirname(linked), 'npm-cli.js');
25
+ if (fs.existsSync(candidate)) return candidate;
26
+ }
27
+ // (this release, on this home: npx runs it with npm_execpath set)
28
+ const {homePrefix, homeNote, NPX} = require('./command-line');
29
+ // (a home that can't be read is said in words: the command never acts on
30
+ // the default home instead)
31
+ let where = null;
32
+ try { where = require('./home').layout(homeEnv); } catch (e) { where = null; }
33
+ const note = where == null ? ' (with COUNTINGHOUSE_HOME set to the full path of its home)' : homeNote(where);
34
+ throw new Error(`npm was not found beside ${execPath}; run the same ch-local command through npx instead: \`${homePrefix(where)}${NPX}@${require('../package.json').version} …\`${note}`);
35
+ }
36
+
37
+ // One npm command in `cwd` -> {status, stdout, stderr}.
38
+ // (the hint names the home the io acts on)
39
+ const npm = (io, args, cwd) => io.exec(io.node, [npmCli(io.env != null ? {homeEnv: io.env} : {}), ...args], {cwd});
40
+
41
+ module.exports = {npm, npmCli};
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+ // Settings changed outside the tools (countinghouse part 3, section 5): each
3
+ // start compares settings.json with the last value <home>/history.jsonl
4
+ // recorded for each setting; a difference is reported, on stderr and in the
5
+ // history ("changed outside ch-local"), so the record holds what the model
6
+ // cannot edit. Reporting only: the file is the user's.
7
+ //
8
+ // The history, replayed: a change ({setting, new}, no change label) sets
9
+ // the value; a reset ({setting: '*', change: 'reset'}) clears every one;
10
+ // "not made" (a write that failed after its line) undoes the change before
11
+ // it, except a session's own change failing (a session, and no every-session
12
+ // scope), which never touched the file and undoes nothing; a session's change kept for all sessions (countinghouse's settings
13
+ // tool: {new, change: 'all sessions'}) sets the value as a change does, and
14
+ // "all sessions: not made" undoes it; a request not confirmed ({asked}) and
15
+ // any other labelled line (part 3's this-start changes, a session's own
16
+ // value, a change for all sessions until the runtime restarts) set nothing.
17
+ // A report sets the value it saw, so it is reported once.
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const {valueOf, entryOf, loosens, shown, historyValue, cutPoints} = require('./settings');
21
+ const crypto = require('node:crypto');
22
+
23
+ // a module's setting (module.<package>.<setting>): kept by ch-local, the
24
+ // runtime's to apply (#413 sections 4.2 and 4.3)
25
+ const isModule = (name) => name.startsWith('module.');
26
+ // a value recorded cut (over 64 characters: its line holds the SHA-256 of
27
+ // the whole): compared by that hash
28
+ const CUT = Symbol('cut');
29
+ const sameValue = (recorded, now) => (recorded != null && recorded[CUT] != null
30
+ ? now !== undefined && crypto.createHash('sha256').update(JSON.stringify(now)).digest('hex') === recorded[CUT]
31
+ : JSON.stringify(recorded) === JSON.stringify(now));
32
+ const {appendHistory} = require('./history');
33
+
34
+ const OUTSIDE = 'changed outside ch-local';
35
+ // the settings tool's change for all sessions, kept in the file, and the
36
+ // line it adds when the file could not be written after it
37
+ const ALL_SESSIONS = 'all sessions';
38
+ const ALL_SESSIONS_NOT_MADE = 'all sessions: not made';
39
+ // The scope the runtime's settings tool gives a line of a change it writes for every session (countinghouse
40
+ // lib/settings-tool.js everySession): its failed write's 'not made' carries it too, and undoes that change. A 'not made'
41
+ // with a session and no such scope is that session's own change failing, which never touched settings.json. Both
42
+ // shapes are pinned in countinghouse: test/validation/30-settings-tool-module-settings.js (the every-session one) and
43
+ // test/sessions/09-tightenings.js (a session's own, no scope).
44
+ const EVERY_SESSION = 'every session';
45
+ // an outside loosening the operator's ceiling refuses: said and recorded,
46
+ // not applied; it sets no value, so each start says it again
47
+ const REFUSED = 'changed outside ch-local, refused by the ceiling';
48
+
49
+ // -> Map(setting -> the value last recorded)
50
+ function recordedValues(where) {
51
+ let text = '';
52
+ try { text = fs.readFileSync(path.join(where.home, 'history.jsonl'), 'utf8'); } catch (err) { text = ''; }
53
+ const recorded = new Map();
54
+ const before = new Map(); // setting -> {had, value} before its last change
55
+ let beforeReset = null; // what the last reset cleared, until a 'not made' says it wasn't
56
+ for (const line of text.split('\n')) {
57
+ let e;
58
+ try { e = JSON.parse(line); } catch (err) { continue; }
59
+ if (e == null || typeof e !== 'object' || typeof e.setting !== 'string') continue;
60
+ // a bare reset: every setting of ch-local's own back to its default; a
61
+ // module's values are kept by it, so theirs stand (section 4.3)
62
+ if (e.setting === '*' && e.change === 'reset') {
63
+ beforeReset = {recorded: new Map(recorded), before: new Map(before)};
64
+ for (const k of [...recorded.keys()]) if (!isModule(k)) { recorded.delete(k); before.delete(k); }
65
+ continue;
66
+ }
67
+ // a reset whose write failed: the values before it stand
68
+ if (e.setting === '*' && e.change === 'not made') {
69
+ if (beforeReset != null) {
70
+ for (const [k, v] of beforeReset.recorded) recorded.set(k, v);
71
+ for (const [k, v] of beforeReset.before) before.set(k, v);
72
+ beforeReset = null;
73
+ }
74
+ continue;
75
+ }
76
+ if (e.asked !== undefined) continue;
77
+ // (a session's own change that failed: nothing of the stored values to undo, as its success, 'this session', is
78
+ // not recorded either)
79
+ if (e.change === 'not made' && e.session != null && e.scope !== EVERY_SESSION) continue;
80
+ if (e.change === 'not made' || e.change === ALL_SESSIONS_NOT_MADE) {
81
+ const b = before.get(e.setting);
82
+ if (b != null) { if (b.had) recorded.set(e.setting, b.value); else recorded.delete(e.setting); before.delete(e.setting); }
83
+ continue;
84
+ }
85
+ // one setting's value removed (a module's setting reset, a leftover
86
+ // pack.* removed with its module turned on, or moved to enabled.* by
87
+ // the migration): back to no value
88
+ if (!Object.prototype.hasOwnProperty.call(e, 'new') && typeof e.change === 'string' && (e.change === 'reset' || e.change.startsWith('removed with ') || e.change.startsWith('moved to '))) {
89
+ before.set(e.setting, {had: recorded.has(e.setting), value: recorded.get(e.setting)});
90
+ recorded.delete(e.setting);
91
+ continue;
92
+ }
93
+ if (!Object.prototype.hasOwnProperty.call(e, 'new')) continue;
94
+ if (e.change !== undefined && e.change !== OUTSIDE && e.change !== ALL_SESSIONS) continue;
95
+ before.set(e.setting, {had: recorded.has(e.setting), value: recorded.get(e.setting)});
96
+ recorded.set(e.setting, typeof e.newSha256 === 'string' ? {[CUT]: e.newSha256} : e.new);
97
+ }
98
+ return recorded;
99
+ }
100
+
101
+ // settings: readSettings(where) -> [{setting, old, new, loosened}]
102
+ function outsideEdits(where, settings) {
103
+ const recorded = recordedValues(where);
104
+ const kept = settings.kept || {};
105
+ const names = new Set([...recorded.keys(), ...Object.keys(settings.values), ...Object.keys(kept).filter(isModule)]);
106
+ const out = [];
107
+ for (const name of names) {
108
+ if (isModule(name)) {
109
+ // a module's setting: compared as stored (no value is no value), a cut
110
+ // one by its hash; the runtime checks it at its next read, so no
111
+ // loosening and no ceiling here
112
+ const was = recorded.has(name) ? recorded.get(name) : undefined;
113
+ const now = Object.prototype.hasOwnProperty.call(kept, name) ? kept[name] : undefined;
114
+ if (sameValue(was, now)) continue;
115
+ out.push({setting: name, old: was != null && was[CUT] != null ? '(a long value)' : was, new: now, loosened: false, module: true});
116
+ continue;
117
+ }
118
+ if (entryOf(name) == null) continue;
119
+ const was = recorded.has(name) ? recorded.get(name) : valueOf({values: {}}, name);
120
+ const now = valueOf(settings, name);
121
+ if (JSON.stringify(was) === JSON.stringify(now)) continue;
122
+ out.push({setting: name, old: was, new: now, loosened: loosens(name, was, now)});
123
+ }
124
+ return out;
125
+ }
126
+
127
+ // Reports each (say) and records it. refusal(setting, value) -> null, or
128
+ // the ceiling's refusal of a loosening ({message}): that edit is marked
129
+ // refused, for the caller to leave unapplied. A settings file that cannot
130
+ // be read is no report. -> the edits.
131
+ // A refused edit sets no value, so it is found again: said and recorded once
132
+ // per process (one start), again at the next start.
133
+ const refusedSaid = new Set();
134
+ function reportOutsideEdits(where, settings, {say, host = null, pid = null, refusal = () => null} = {}) {
135
+ if (settings.error != null) return [];
136
+ const edits = outsideEdits(where, settings);
137
+ for (const e of edits) {
138
+ const refused = e.loosened ? refusal(e.setting, e.new) : null;
139
+ if (refused != null) e.refused = refused;
140
+ const key = `${where.home}\0${e.setting}\0${JSON.stringify(e.new)}`;
141
+ if (refused != null && refusedSaid.has(key)) continue;
142
+ if (refused != null) refusedSaid.add(key);
143
+ // (a module's value said as stored, cut past 64 characters; recorded cut,
144
+ // with its hash, as any module value)
145
+ const said = (v) => { if (!e.module) return shown(e.setting, v); if (v === undefined) return '(not set)'; const cut = cutPoints(v); return cut != null ? `${cut}…` : String(v); };
146
+ say(`${e.setting} was changed outside ch-local: ${said(e.old)} -> ${said(e.new)}${e.loosened ? ' (this loosens a guarding setting)' : ''}` +
147
+ // (the ceiling's refusal without its setting and value again: within the
148
+ // runtime's notice cut -- the final pass on #134)
149
+ (refused != null ? `; not applied: ${refused.code === 'SETTING_FORBIDDEN_BY_CEILING' ? 'its operator\'s ceiling forbids it' : refused.message.replace(/; nothing was changed$/, '')}` : ''));
150
+ const values = e.module
151
+ ? {...(e.old === undefined ? {} : historyValue('old', e.old)), ...(e.new === undefined ? {} : historyValue('new', e.new))}
152
+ : {old: e.old, new: e.new};
153
+ if (e.module && e.new === undefined) {
154
+ appendHistory(where, {by: 'start', setting: e.setting, ...values, change: 'removed with an outside edit'}, {host, pid});
155
+ continue;
156
+ }
157
+ appendHistory(where, {by: 'start', setting: e.setting, ...values, change: refused != null ? REFUSED : OUTSIDE, ...(e.loosened ? {loosened: true} : {})}, {host, pid});
158
+ }
159
+ return edits;
160
+ }
161
+
162
+ module.exports = {outsideEdits, reportOutsideEdits, recordedValues, OUTSIDE, REFUSED, resetForTests: () => refusedSaid.clear()};
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+ // How a change to the user's own modules ended in the runtimes that run now
3
+ // (R-add-module-says-early): add-module and remove-module print their line
4
+ // once every live start has applied the change, and say the worst of how it
5
+ // ended. Read from each start's run.json (lib/in-place.js writes it):
6
+ // ownSeen: {<name>: {addedAt, state, code?, kind?}} own.json as the applier
7
+ // last applied it, whole: written after the loads and unloads were
8
+ // answered. state: loaded; kept (availability keeps it out, kind says
9
+ // why, and so does status); refused (the runtime refused the load, with
10
+ // its code); waits (wanted, and may be loading: one of the start's own
11
+ // plan, or a load not answered); restart (wanted, and not loaded in place:
12
+ // its next restart loads it; again: added again at the code it has loaded,
13
+ // which is what it still runs). addedAt is the entry's own, so the same code
14
+ // added again is told from before. null until a first apply ends; absent
15
+ // from an older ch-local's start, which tells nothing.
16
+ // ownAt: {at, ino} the own.json that was, so a removal is told from the
17
+ // own.json before it, which may hold the same names (stampOf).
18
+ // loaded: what that runtime holds; shared: whether it is the shared one.
19
+ // run.json is a file: every field is checked before it is used, and a code is
20
+ // printed only in the runtime's own form.
21
+ const fs = require('node:fs');
22
+ const {liveRuns} = require('./gc');
23
+ const {hostTag} = require('./run-liveness');
24
+
25
+ const WAIT_MS = 40000; // the control request's 30 s, the watcher's 2 s, a margin
26
+ const POLL_MS = 200;
27
+ const SAY_MS = 2000;
28
+ const WAITING = `Waiting for the running runtime to apply it (up to ${WAIT_MS / 1000} s)…`;
29
+ const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
30
+ const TREE = /^[0-9a-f]{64}$/;
31
+ const RUN_DIR = /^(.+)-([0-9]{1,10})-[0-9a-f]{8}$/; // start's: host, pid
32
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
33
+ const own = (o, k) => (isObject(o) && Object.prototype.hasOwnProperty.call(o, k) ? o[k] : undefined);
34
+ const codeOf = (x) => (typeof x === 'string' && CODE.test(x) ? x : null);
35
+
36
+ // worst first: what several runtimes together are said to have done
37
+ const ADD_ORDER = ['refused', 'kept', 'restart', 'late', 'loaded'];
38
+ const REMOVE_ORDER = ['still', 'late', 'removed'];
39
+
40
+ // own.json as it is now: {at, ino}, strings (bigints as JSON has them), zeros
41
+ // with none; null when it can't be told
42
+ function stampOf(where) {
43
+ // (a few times, with a pause: Windows refuses one while the file is being replaced)
44
+ for (let i = 0; i < 5; i++) {
45
+ if (i > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
46
+ try {
47
+ const st = fs.statSync(where.ownRecord, {bigint: true});
48
+ return {at: String(st.mtimeNs), ino: String(st.ino)};
49
+ } catch (err) {
50
+ if (err.code === 'ENOENT') return {at: '0', ino: '0'};
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+ const DIGITS = /^[0-9]{1,30}$/;
56
+ const isStamp = (s) => isObject(s) && typeof s.at === 'string' && typeof s.ino === 'string' && DIGITS.test(s.at) && DIGITS.test(s.ino);
57
+ // whether seen is the own.json of `mine`, or a later one
58
+ const sinceThen = (seen, mine) => isStamp(seen) && isStamp(mine) && (BigInt(seen.at) > BigInt(mine.at) || (seen.at === mine.at && seen.ino === mine.ino));
59
+
60
+ // one start's run.json -> {state (of the order), code?}, or null: not yet
61
+ function addOutcome(run, {name, tree, addedAt}) {
62
+ if (!Object.prototype.hasOwnProperty.call(run, 'ownSeen')) return {state: 'late'};
63
+ const e = own(run.ownSeen, name);
64
+ if (!isObject(e) || e.addedAt !== addedAt) return null;
65
+ if (e.state === 'loaded') return [].concat(own(run.loaded, name)).includes(tree) ? {state: 'loaded'} : null;
66
+ if (e.state === 'refused' && codeOf(e.code) != null) return {state: 'refused', code: e.code};
67
+ if (e.state === 'kept') return {state: 'kept'};
68
+ if (e.state === 'restart') return {state: 'restart', shared: run.shared === true};
69
+ return e.state === 'refused' || e.state === 'waits' ? {state: 'late'} : null;
70
+ }
71
+ // (an own module's version in loaded is its tree; a pack's module of the same
72
+ // name is not the one removed)
73
+ function removeOutcome(run, {name, stamp, tree, addedAt}) {
74
+ if (!Object.prototype.hasOwnProperty.call(run, 'ownSeen')) return {state: 'late'};
75
+ if (!isObject(run.ownSeen) || !sinceThen(run.ownAt, stamp)) return null;
76
+ const still = {state: 'still', shared: run.shared === true};
77
+ const loaded = [].concat(own(run.loaded, name));
78
+ const e = own(run.ownSeen, name);
79
+ if (e === undefined) return loaded.some((v) => TREE.test(String(v))) ? still : {state: 'removed'};
80
+ // (the entry removed itself: an own.json before this, whatever its time says)
81
+ if (isObject(e) && e.addedAt === addedAt) return null;
82
+ // (added again since: overtaken, but the removed code may still be served;
83
+ // not where what was added again is that code, of the start's own plan, or
84
+ // loaded before it was added again)
85
+ return isObject(e) && e.state !== 'loaded' && e.state !== 'waits' && e.again !== true && loaded.includes(tree) ? still : {state: 'removed'};
86
+ }
87
+
88
+ // Waits for the starts live on this machine now, by their processes: one whose
89
+ // process ends drops out; one whose process goes on (the daemon's, between a
90
+ // runtime and the next) is judged as it starts again; a process that starts
91
+ // meanwhile reads the new own.json, and is not waited for, unless all the
92
+ // others have ended (a daemon's hand-over). A run that can't
93
+ // be read is a live start's while its process lives, else nothing.
94
+ // io.appliedWaitMs, appliedPollMs, appliedSayMs: a test's.
95
+ // -> {state: 'none'} (no runtime runs) or the worst outcome
96
+ async function applied(where, io, outcomeOf, order, change) {
97
+ if (typeof io.alive !== 'function') throw new Error('applied: io.alive is required');
98
+ const ms = (v, or) => (Number.isInteger(v) && v >= 0 ? v : or);
99
+ const bound = ms(io.appliedWaitMs, WAIT_MS);
100
+ const sayAfter = ms(io.appliedSayMs, SAY_MS);
101
+ const began = performance.now();
102
+ const here = hostTag(io.hostname);
103
+ const pidOf = (r) => (Number.isInteger(r.pid) ? r.pid : r.childPid);
104
+ let waitedFor = null;
105
+ let said = false;
106
+ for (;;) {
107
+ let runs = null;
108
+ const unread = new Set();
109
+ try {
110
+ runs = liveRuns(where, {alive: io.alive, hostname: io.hostname, sameMachine: true, unreadable: (n) => {
111
+ const m = RUN_DIR.exec(n);
112
+ if (m != null && m[1] === here && io.alive(Number(m[2]))) unread.add(Number(m[2]));
113
+ }});
114
+ } catch (err) { runs = null; } // (the run directory can't be listed: read again)
115
+ const past = performance.now() - began >= bound;
116
+ if (runs == null && past) return {state: 'late'};
117
+ if (runs != null) {
118
+ if (waitedFor == null) waitedFor = new Set([...runs.map(pidOf), ...unread]);
119
+ const judged = () => {
120
+ const out = [];
121
+ for (const pid of waitedFor) {
122
+ const its = runs.filter((r) => pidOf(r) === pid);
123
+ if (its.length === 0 && !io.alive(pid)) continue;
124
+ for (const o of its.length > 0 ? its.map((r) => outcomeOf(r, change)) : [null]) out.push(o || (past ? {state: 'late'} : null));
125
+ }
126
+ return out;
127
+ };
128
+ let outcomes = judged();
129
+ // (none of them left, but others run: the daemon handed over)
130
+ const others = [...runs.map(pidOf), ...unread];
131
+ if (outcomes.length === 0 && others.length > 0) {
132
+ waitedFor = new Set(others);
133
+ outcomes = judged();
134
+ }
135
+ if (outcomes.length === 0) return {state: 'none'};
136
+ if (!outcomes.includes(null)) return outcomes.sort((a, b) => order.indexOf(a.state) - order.indexOf(b.state) || Number(b.shared === true) - Number(a.shared === true))[0];
137
+ }
138
+ if (!said && performance.now() - began >= sayAfter) {
139
+ said = true;
140
+ io.stdout.write(`${WAITING}\n`);
141
+ }
142
+ await new Promise((r) => setTimeout(r, ms(io.appliedPollMs, POLL_MS)));
143
+ }
144
+ }
145
+ const addApplied = (where, io, change) => applied(where, io, addOutcome, ADD_ORDER, change);
146
+ const removeApplied = (where, io, change) => applied(where, io, removeOutcome, REMOVE_ORDER, change);
147
+
148
+ // what status says of this entry (its addedAt) from a live start's run.json,
149
+ // as add-module's line: the code its runtime refused it with; that the start
150
+ // keeps it out for its own sandbox (the rest of what keeps one out, status
151
+ // reads itself); or that only the runtime's restart takes it up
152
+ // (earlier: other code of it is what that runtime still has)
153
+ // -> {code} | {sandbox: true} | {restart: true, shared, earlier?} | null
154
+ function notLoadedIn(run, name, entry) {
155
+ const o = own(run.ownSeen, name);
156
+ if (!isObject(o) || o.addedAt !== entry.addedAt) return null;
157
+ if (o.state === 'refused' && codeOf(o.code) != null) return {code: o.code};
158
+ if (o.state === 'kept' && o.kind === 'sandbox') return {sandbox: true};
159
+ // (loaded meanwhile: loaded is written at once, ownSeen when the apply ends)
160
+ return o.state === 'restart' && (o.again === true || ![].concat(own(run.loaded, name)).includes(entry.tree)) ? {restart: true, shared: run.shared === true,
161
+ ...([].concat(own(run.loaded, name)).some((v) => TREE.test(String(v)) && v !== entry.tree) ? {earlier: true} : {})} : null;
162
+ }
163
+ // (several runs: a refusal first, then the sandbox, then a restart, the shared
164
+ // runtime's first; a restart only of a run in `here`, this machine's: another
165
+ // machine's isn't this one's to restart)
166
+ const NOT_LOADED_ORDER = (x) => (x.code != null ? 0 : x.sandbox === true ? 1 : x.shared === true ? 2 : 3);
167
+ const notLoadedOf = (runs, here, name, entry) => [...runs.map((r) => notLoadedIn(r, name, entry)).filter((x) => x != null && x.restart !== true),
168
+ ...here.map((r) => notLoadedIn(r, name, entry)).filter((x) => x != null)].sort((a, b) => NOT_LOADED_ORDER(a) - NOT_LOADED_ORDER(b))[0] || null;
169
+ // whether one of these runs (this machine's) has this entry's code loaded, not
170
+ // stopped: its copy is checked at a start and at an apply, so one that changed
171
+ // since is on there meanwhile (a worker that starts again reads it as it is:
172
+ // R6, lib/own-tree.js)
173
+ const servedBy = (here, name, entry) => here.some((r) => [].concat(own(r.loaded, name)).includes(entry.tree) && own(r.stopped, name) === undefined);
174
+
175
+ module.exports = {addApplied, removeApplied, notLoadedOf, servedBy, stampOf, WAIT_MS};