@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,153 @@
1
+ 'use strict';
2
+ // What the home has installed, described as the release pins describe a
3
+ // release (#413 rev 3 sections 9.3 and 9.6; L4): the baseline a new
4
+ // release's additions are judged against. It is the home's own record, not
5
+ // the bundled pins as such: a module is described only when it is verifiably
6
+ // what the running release pinned (the Reviewer's high on L4, 3):
7
+ // - the record has it at the running release's pin version, and
8
+ // - the store's marker for that version names the pin's integrity;
9
+ // then the running release's description of those bytes is its description.
10
+ // Anything else (a module the version table keeps off its pin, a held
11
+ // pack's, a marker that can't be read or names other bytes) is null:
12
+ // unknown, which holds an automatic upgrade back. The store's files are
13
+ // never read as a description: they are not verified to be the pinned bytes.
14
+ //
15
+ // What runs is start's own rule (packs.withdrawnNames against the running
16
+ // release: a pack it does not list, or one the record has withdrawn, is not
17
+ // running; the Reviewer's high on #101, round 2). A pack not running is
18
+ // {modules: [], withdrawn: true}, and a module no running pack lists is not
19
+ // in `modules`, so a release that serves it again adds them (the
20
+ // Reviewer's high on L4, 4). A module is verified by the store holding it
21
+ // whole at the pin (module-store wholeAt: its directory and its marker).
22
+ //
23
+ // -> {packs: {<pack>: {modules: [package], withdrawn?: true}}, modules:
24
+ // {<package>: description | null}}, pins-shaped for lib/release-pins.js
25
+ // additions(). running: the bundled release (lib/allowlist ALLOWLIST:
26
+ // {packs, pins, modules}; its packs decide what runs), the same data
27
+ // findUpgrade judges the new release against.
28
+ const fs = require('node:fs');
29
+ const path = require('node:path');
30
+ const {own} = require('./module-record');
31
+ const {wholeAt} = require('./module-store');
32
+ const {withdrawnNames} = require('./packs');
33
+ const {compareVersions} = require('./semver-order');
34
+
35
+ // alsoWithdrawnBy: another release whose withdrawn packs are not running
36
+ // either (homeDescription: the running ch-local's own, beside the home's;
37
+ // a pack either withdraws is left out, so a release serving it again holds:
38
+ // the medium on L4 baseline, 1)
39
+ function installedDescription(where, record, running, {alsoWithdrawnBy = null} = {}) {
40
+ const all = Object.entries((record && record.packs) || {});
41
+ const named = all.map(([name]) => ({name}));
42
+ const out = withdrawnNames(record, named, running);
43
+ if (alsoWithdrawnBy != null) for (const n of withdrawnNames(record, named, alsoWithdrawnBy)) out.add(n);
44
+ const packs = {};
45
+ const runs = new Set();
46
+ for (const [name, p] of all) {
47
+ const mods = Object.keys((p && p.modules) || {}).sort();
48
+ if (out.has(name)) { packs[name] = {modules: [], withdrawn: true}; continue; }
49
+ packs[name] = {modules: mods};
50
+ for (const m of mods) runs.add(m);
51
+ }
52
+ const pins = (running && running.pins) || {};
53
+ const descs = (running && running.modules) || {};
54
+ const verified = (m, version) => {
55
+ // (a pin with no integrity verifies nothing: the medium on #101 round 2, 5)
56
+ if (!own(pins, m) || !own(descs, m) || pins[m].version !== version || typeof pins[m].integrity !== 'string') return false;
57
+ try { return wholeAt(where, m, pins[m]); } catch (err) { return false; }
58
+ };
59
+ const modules = {};
60
+ for (const [m, e] of Object.entries((record && record.modules) || {}).sort(([a], [b]) => (a < b ? -1 : 1))) {
61
+ if (!runs.has(m)) continue;
62
+ modules[m] = e != null && typeof e.version === 'string' && verified(m, e.version) ? descs[m] : null;
63
+ }
64
+ return {packs, modules};
65
+ }
66
+
67
+ // The record's own release's pins ({packs, modules, pins}), the baseline's
68
+ // (post-rel L4 baseline, ruled 11-20 on #101): a ch-local whose own bundled
69
+ // release is another (a client process whose home was upgraded or rolled
70
+ // back under it, a checkout or a global install) judges what the home holds
71
+ // by the pins it was installed from, not by its own, so it isn't held with
72
+ // every module unknown.
73
+ // The record's version is its runtime's ch-local (runtime.versions, as
74
+ // packs.recordRelease reads it; every install records it); a release it
75
+ // records must say the same. Then, in order:
76
+ // - the home's app, the ch-local its launcher runs (packs.homeSelfDir; no
77
+ // wider a trust than running it): its package.json ch-local at that
78
+ // version, and its lib/release-pins.json (own-file readBoundedFile: a
79
+ // regular file, not a link, at most release-pins MAX_BYTES), parsed by
80
+ // parseReleasePins. Read even when the bundled release has that version:
81
+ // a checkout or global install of the same version may carry other pins
82
+ // (the medium on L4 baseline, 3);
83
+ // - with no such app, the bundled release when it has that version (the
84
+ // pins main judged by, a test's home with no app);
85
+ // - anything else (no recorded ch-local, another version, a problem in
86
+ // the file): null.
87
+ // -> {packs, modules, pins}, or null (homeDescription then holds every
88
+ // module unknown)
89
+ const SELF = '@countinghouse/ch-local';
90
+ const shapeOf = (d) => ({packs: d.packs, modules: d.modules, pins: d.pins});
91
+ // (the package.json and the pins are two reads, not tied to one app
92
+ // generation: an install or rollback landing between them can pair one
93
+ // release's version with another's pins. What that can describe is still
94
+ // bounded by the store: a module is described only when the store holds it
95
+ // whole at that pin's integrity, so no bytes the pins don't name are ever
96
+ // taken for known; the reviewer's high on #103, 4)
97
+ function appPins(where, version) {
98
+ const {readBoundedFile} = require('./own-file');
99
+ const dir = require('./packs').homeSelfDir(where);
100
+ const pkgFile = path.join(dir, 'package.json');
101
+ // Only a home with no app at all (<home>/app itself missing) is "no app";
102
+ // an app there whose ch-local is refused or missing (package.json a link,
103
+ // a directory, a FIFO, over the bound, gone mid-install; the app or a
104
+ // directory under it a dangling link) is an app whose pins are unknown,
105
+ // never a reason to take the bundled pins (the reviewer's high on #103,
106
+ // 1; the medium on it, 3 and 4)
107
+ try { fs.lstatSync(where.app); } catch (e) { if (e.code === 'ENOENT') return {found: false}; return {found: true, pins: null}; }
108
+ const pkgBytes = readBoundedFile(pkgFile, {max: 64 * 1024});
109
+ if (pkgBytes == null) return {found: true, pins: null};
110
+ const pkg = JSON.parse(pkgBytes.toString('utf8'));
111
+ if (pkg == null || pkg.name !== SELF || pkg.version !== version) return {found: true, pins: null};
112
+ const {parseReleasePins, MAX_BYTES} = require('./release-pins');
113
+ const bytes = readBoundedFile(path.join(dir, 'lib', 'release-pins.json'), {max: MAX_BYTES});
114
+ if (bytes == null) return {found: true, pins: null};
115
+ const parsed = parseReleasePins(bytes);
116
+ return {found: true, pins: parsed.problem != null ? null : shapeOf(parsed.pins)};
117
+ }
118
+ function ownReleasePins(where, record, bundled) {
119
+ const versions = record != null && record.runtime != null && record.runtime.versions != null ? record.runtime.versions : {};
120
+ const version = typeof versions[SELF] === 'string' ? versions[SELF] : null;
121
+ if (version == null) return null;
122
+ // (a release recorded with no version is valid: compared only when it is
123
+ // a string, as recordRelease does; the reviewer's high on #103, 5)
124
+ if (record.release != null && typeof record.release.version === 'string' && record.release.version !== version) return null;
125
+ let app;
126
+ try { app = appPins(where, version); } catch (err) { return null; }
127
+ if (app.found) return app.pins;
128
+ return bundled != null && bundled.release != null && bundled.release.version === version ? shapeOf(bundled) : null;
129
+ }
130
+
131
+ // What the home holds, described by its own release's pins: the baseline
132
+ // an upgrade's additions are judged against. A pack withdrawn by the home's
133
+ // release is not running; nor is one the running release withdrew, which a
134
+ // release does by no longer listing it, so a running release older than the
135
+ // home's counts for nothing: it doesn't list a newer pack because it never
136
+ // knew it (the reviewer's high on #103, 2); one whose version can't be
137
+ // compared counts (fail closed). With the
138
+ // home's pins unknown, every module the record runs is unknown (null), so
139
+ // an automatic upgrade is held, as it was (fail closed).
140
+ function homeDescription(where, record, bundled) {
141
+ const pins = ownReleasePins(where, record, bundled);
142
+ if (pins != null) {
143
+ const homeVersion = record.runtime.versions[SELF];
144
+ const ran = bundled != null && bundled.release != null && typeof bundled.release.version === 'string' ? bundled.release.version : null;
145
+ // (a running version not known, or not comparable, counts: fail closed;
146
+ // the medium on #103's round 1, 1)
147
+ const c = ran != null ? compareVersions(ran, homeVersion) : null;
148
+ return installedDescription(where, record, pins, {alsoWithdrawnBy: c === -1 ? null : bundled});
149
+ }
150
+ return installedDescription(where, record, {...bundled, pins: {}, modules: {}});
151
+ }
152
+
153
+ module.exports = {installedDescription, ownReleasePins, homeDescription};
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+ // A tarball's integrity as a pin records it: sha512, base64 (npm's form).
3
+ const crypto = require('node:crypto');
4
+
5
+ const integrityOf = (buf) => 'sha512-' + crypto.createHash('sha512').update(buf).digest('base64');
6
+
7
+ module.exports = {integrityOf};
package/lib/lock.js ADDED
@@ -0,0 +1,456 @@
1
+ 'use strict';
2
+ // The home's lock (reviewer, 2026-11-12): install, add-pack, remove-pack and
3
+ // uninstall change packs.json and app/node_modules, so only one runs at a time.
4
+ // <home>/packs.lock is created exclusively and holds {pid, host, at}. A live
5
+ // holder, or one on another host, stops the command, naming it.
6
+ //
7
+ // A holder on this host whose PID is dead (a crash) is cleared, but only by
8
+ // one ch-local at a time: clearing takes <home>/packs.lock.break exclusively,
9
+ // then reads the lock again and removes it only if it is still that dead
10
+ // holder's. So a second ch-local that read the same dead holder earlier
11
+ // cannot remove the lock the first has just taken.
12
+ //
13
+ // "This host" is the host name plus, on Linux, the PID namespace: two
14
+ // containers sharing a host name do not see each other's PIDs, so neither
15
+ // takes the other's live lock for dead. With `started` (below), a holder
16
+ // whose PID was reused is gone, and the boot id tells this machine from
17
+ // another of the same name.
18
+ //
19
+ // The lock is never what creates the home: with no home there is nothing
20
+ // installed to guard.
21
+ //
22
+ // Packs in place (part 2; the review of ch-local #13): start takes the lock
23
+ // for one short section, reading the record and writing its run.json, which
24
+ // collection (held under this lock) reads; it waits for an install for as
25
+ // long as one takes, saying so every 10 s, and never tells anyone to remove
26
+ // the lock. A lock is created whole (its content written to a temporary file
27
+ // and linked into place), so it is never seen empty; an empty or unreadable
28
+ // one is never taken for stale. While held, its mtime is refreshed every
29
+ // HEARTBEAT_MS: a lock on any host whose heartbeat is STALE_MS old is a
30
+ // holder that is gone, and is cleared as a dead one is.
31
+ //
32
+ // Options a lock turns on (the stored credentials' lock, post-rel
33
+ // cred-race; packs.lock too since post-rel packs.lock protocol, with
34
+ // trustStarted and waitRemoteMs besides):
35
+ // - started: the holder records its process's start time, this boot's id and
36
+ // this machine's id where they can be read (Linux), and a holder on this host whose
37
+ // PID is alive with another start time is a reused PID: gone. Elsewhere
38
+ // both are null and the heartbeat covers a reused PID. A zombie or dead
39
+ // process (/proc state Z, X) is never taken for alive (#104's high, 1).
40
+ // - ageOtherHosts: false: a holder on another host is never taken for gone
41
+ // by its heartbeat's age (another host's clock can be skewed); it is
42
+ // named, with the file to remove if nothing runs there. By the ids a
43
+ // holder recorded (placeOf; #104's high, 2, and the medium on it): the
44
+ // same boot id, whatever the host name or PID namespace (a container on
45
+ // a shared home), is this machine and its clock, aged by its heartbeat;
46
+ // a different boot id with this machine id and host name, renewed last
47
+ // before this kernel booted, is this machine before a reboot, gone; any other is another machine (a host name alone
48
+ // never decides: two machines can share one). With no boot id on either
49
+ // side, the host string decides, as before.
50
+ // - waitMs: wait at most that long for a holder, then say it is held. Its
51
+ // heartbeat's age never cuts the wait short (the reviewer's high on
52
+ // #102's round 1, 2 and 3): on this host an old heartbeat already makes
53
+ // the holder gone (cleared; a stopped holder's lock with it, the limit
54
+ // stated above, its write then refused by held), and a gone one whose
55
+ // clearing another waiter (or a young .break) holds up is waited for; on
56
+ // another host its mtime is that host's clock, which ageOtherHosts: false
57
+ // distrusts, so an abandoned lock there is waited out to the cap, then
58
+ // named with the file to remove. An unreadable lock is waited out too.
59
+ // - trustStarted (with started): a holder on this host whose PID is alive
60
+ // with the start time it recorded is exactly that holder, so it is never
61
+ // taken for gone by its heartbeat's age: an install whose synchronous
62
+ // work (extracting, hashing) blocks its heartbeat past STALE_MS is never
63
+ // stolen (packs.lock; the reviewer 11-20), and start waits for it as long
64
+ // as it takes, unless /proc says it is stopped (state T: it won't finish
65
+ // by itself; said with how to resume or end it). One that has stopped
66
+ // renewing but isn't stopped (busy, or hung) is still waited for, said
67
+ // with how to end it if it is hung. Where the start time can't be read it
68
+ // changes nothing.
69
+ // - waitRemoteMs (with wait: true): a lock whose holder this host can't
70
+ // judge (another host's, one that can't be read or has no pid) or an exact
71
+ // holder here that is stopped is waited for while the lock changes, as
72
+ // seen by this host's own clock (a new holder, or its mtime renewed), and
73
+ // given up on once it has not changed for that long; then one more try,
74
+ // and said held with the last look (start fails, never going on
75
+ // unlocked). (the medium on post-rel packs.lock, 2-4; #104's high, 3-5)
76
+ // A limit: trustStarted protects a holder only from waiters that turn it on;
77
+ // an older ch-local (the defaults) still takes an hour-old heartbeat for
78
+ // gone. Mixed versions during an upgrade can still steal a blocked install.
79
+ // - missing: with no `dir`, its answer, never fn run unlocked.
80
+ // - doing: what the holder is doing, recorded for the held message.
81
+ // - heldMessage({holder, who, file, removable, stopped, quiet}): that line,
82
+ // not the default.
83
+ // fn(release, held): held.check() throws (code LOCK_LOST) once the lock is
84
+ // no longer this holder's (cleared as stale, another holder in it), so a
85
+ // write made under it can be refused just before it lands. A limit: it is
86
+ // a check, then the write; a holder stopped in between (past STALE_MS, its
87
+ // lock taken meanwhile) still lands. A file lock in Node's core can't close
88
+ // that; it needs a holder stopped for minutes at that one instruction.
89
+ // A bounded wait (waitMs) says it is waiting at once, not after
90
+ // PROGRESS_MS, so a short wait is never silent.
91
+ const fs = require('node:fs');
92
+ const os = require('node:os');
93
+ const path = require('node:path');
94
+
95
+ function lockHost() {
96
+ let ns = '';
97
+ if (process.platform === 'linux') {
98
+ try { ns = `#${fs.readlinkSync('/proc/self/ns/pid').replace(/^pid:/, 'pid:')}`; } catch (err) { ns = ''; }
99
+ }
100
+ return `${os.hostname()}${ns}`;
101
+ }
102
+
103
+ // a process's state letter (R running, S sleeping, T stopped, Z zombie, X
104
+ // dead, ...) and start time (clock ticks since boot, as a string), from one
105
+ // read of /proc/<pid>/stat, so both describe the same moment (the medium on
106
+ // #104's round 1, 7); nulls where it can't be read
107
+ function processStat(pid) {
108
+ if (process.platform !== 'linux' || !Number.isInteger(pid) || pid <= 0) return {state: null, started: null};
109
+ try {
110
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
111
+ // the fields after the command, which is in parentheses and may hold any
112
+ // character: the state first, field 22 (starttime) the 20th
113
+ const rest = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
114
+ return {state: rest[0] || null, started: /^\d+$/.test(rest[19] || '') ? rest[19] : null};
115
+ } catch (err) { return {state: null, started: null}; }
116
+ }
117
+ const processStarted = (pid) => processStat(pid).started;
118
+ const processState = (pid) => processStat(pid).state;
119
+ // this boot of this machine's kernel (Linux): random per boot, the same in
120
+ // every container on it. null elsewhere.
121
+ let BOOT_ID;
122
+ function bootId() {
123
+ if (BOOT_ID !== undefined) return BOOT_ID;
124
+ try { BOOT_ID = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() || null; } catch (err) { BOOT_ID = null; }
125
+ return BOOT_ID;
126
+ }
127
+ // this installation's id (/etc/machine-id: kept across reboots), or null
128
+ let MACHINE_ID;
129
+ function machineId() {
130
+ if (MACHINE_ID !== undefined) return MACHINE_ID;
131
+ try { MACHINE_ID = fs.readFileSync('/etc/machine-id', 'utf8').trim() || null; } catch (err) { MACHINE_ID = null; }
132
+ return MACHINE_ID;
133
+ }
134
+ // when this kernel booted (ms since the epoch: /proc/stat's btime), or null
135
+ let BOOT_TIME_MS;
136
+ function bootTimeMs() {
137
+ if (BOOT_TIME_MS !== undefined) return BOOT_TIME_MS;
138
+ try {
139
+ const m = /^btime (\d+)$/m.exec(fs.readFileSync('/proc/stat', 'utf8'));
140
+ BOOT_TIME_MS = m != null ? Number(m[1]) * 1000 : null;
141
+ } catch (err) { BOOT_TIME_MS = null; }
142
+ return BOOT_TIME_MS;
143
+ }
144
+ const hostNameOf = (h) => String(h).split('#')[0];
145
+ // Where a holder is (#104's high, 2; the medium on its round 1, 1, 2, 5),
146
+ // from the ids it recorded (`started`) and this side's:
147
+ // - 'here': this PID namespace of this boot (its PIDs are ours to judge);
148
+ // - 'machine': the same boot id, so this kernel, whatever its host name or
149
+ // PID namespace (a container on a shared home): its clock is ours, so its
150
+ // heartbeat's age counts, but its PIDs can't be read;
151
+ // - 'rebooted': another boot id, with this machine id and host name, and a
152
+ // lock last renewed before this kernel booted: this machine before a
153
+ // reboot, so the holder is gone. A host name alone is never enough (two
154
+ // machines can share one: the medium, 1), nor a machine id with it (a
155
+ // cloned VM keeps both, and a live clone renews its lock after our boot:
156
+ // the reviewer's delta read of 87b28d4);
157
+ // - 'remote': anything else, never aged here.
158
+ // With no boot id on either side, as before: the host string decides.
159
+ // `mtimeMs`: the lock's last renewal (null: never 'rebooted').
160
+ function placeOf(holder, host, mtimeMs = null) {
161
+ const boot = bootId();
162
+ const theirs = typeof holder.boot === 'string' ? holder.boot : null;
163
+ if (boot == null || theirs == null) return holder.host === host ? 'here' : 'remote';
164
+ if (theirs === boot) return holder.host === host ? 'here' : 'machine';
165
+ const mid = machineId();
166
+ const booted = bootTimeMs();
167
+ const before = booted != null && Number.isFinite(mtimeMs) && mtimeMs < booted;
168
+ return before && mid != null && holder.machine === mid && hostNameOf(holder.host) === os.hostname() ? 'rebooted' : 'remote';
169
+ }
170
+ // where a holder is, as a person reads it (the high's 7; the medium, 9): the
171
+ // same machine in another PID namespace (either side may be the container);
172
+ // another machine by its host name, said as such when it is this one's
173
+ function hostLabel(holder) {
174
+ const name = hostNameOf(holder.host);
175
+ if (placeOf(holder, lockHost()) === 'machine') return 'another PID namespace on this machine (a container, or the host)';
176
+ return name === os.hostname() ? `another machine named ${name}` : name;
177
+ }
178
+ // what to do about a lock this host can't judge: remove it if nothing runs
179
+ // where it was taken (one shared line: packs.lock's, credentials.lock's)
180
+ function removeHint(file, holder) {
181
+ return `, or remove ${file} if nothing is running ${holder == null ? 'there' : `on ${hostLabel(holder)}`}`;
182
+ }
183
+
184
+ // a zombie (Z) or dead (X) process answers kill(pid, 0) but holds nothing
185
+ // (#104's high, 1)
186
+ const deadState = (state) => state === 'Z' || state === 'X';
187
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; } };
188
+ const readHolder = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (err) { return null; } };
189
+ const sameHolder = (a, b) => a != null && b != null && a.pid === b.pid && a.host === b.host && a.at === b.at;
190
+ const BREAK_STALE_MS = 10000;
191
+ const HEARTBEAT_MS = 15000;
192
+ const STALE_MS = 2 * 60 * 1000;
193
+ const PROGRESS_MS = 10000;
194
+
195
+ // On Windows a lock file another process is deleting (delete pending: a
196
+ // handle still open on it, as a holder's release meets a reader) refuses a
197
+ // new link or an exclusive create onto its name with EPERM (or EACCES) until
198
+ // that handle closes. Taking the lock then counts as busy, and is tried again
199
+ // on the wait's own clock for at most PENDING_WAIT_MS; a genuine permission
200
+ // error answers EPERM too, so the tries end at that deadline with the error
201
+ // itself (its code and the lock's path), never as a held lock and never
202
+ // forever (as countinghouse's json-file.js does). Elsewhere EPERM is an error
203
+ // at once, as before.
204
+ const PENDING_WAIT_MS = 10000;
205
+ const pendingRefusal = (err, platform) => platform === 'win32' && err != null && (err.code === 'EPERM' || err.code === 'EACCES');
206
+
207
+ // The lock created whole -> true; false when another holds it; or {pending:
208
+ // err} when its name is being deleted (Windows; pendingRefusal).
209
+ function create(file, mine, platform = process.platform) {
210
+ const tmp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
211
+ fs.writeFileSync(tmp, JSON.stringify(mine) + '\n');
212
+ try {
213
+ fs.linkSync(tmp, file);
214
+ return true;
215
+ } catch (err) {
216
+ if (err.code === 'EEXIST') return false;
217
+ // (the lock named, never the temporary file the link came from, which
218
+ // Node's error names in its path)
219
+ if (pendingRefusal(err, platform)) return {pending: Object.assign(new Error(`${err.code}: the lock ${file} could not be taken`), {code: err.code, path: file})};
220
+ throw err;
221
+ } finally {
222
+ fs.rmSync(tmp, {force: true});
223
+ }
224
+ }
225
+ // The lock created whole -> true, or false when another holds it; anything
226
+ // else thrown, a delete-pending refusal included (pendingRefusal tells it),
227
+ // for a caller with its own loop (lib/settings.js withSettingsLock).
228
+ function createWhole(file, mine, platform = process.platform) {
229
+ const made = create(file, mine, platform);
230
+ if (made === true || made === false) return made;
231
+ throw made.pending;
232
+ }
233
+ const heartbeatAge = (file) => { try { return Date.now() - fs.statSync(file).mtimeMs; } catch (err) { return 0; } };
234
+
235
+ // Clears `file` if it is still `dead`'s: true when it was cleared, false when
236
+ // it wasn't, or {pending: err} when the breaker's name is being deleted
237
+ // (Windows: pendingRefusal; busy under the same deadline as the lock's own).
238
+ function clearStale(file, dead, platform = process.platform) {
239
+ const breaker = `${file}.break`;
240
+ try {
241
+ fs.writeFileSync(breaker, String(process.pid), {flag: 'wx'});
242
+ } catch (err) {
243
+ if (pendingRefusal(err, platform)) return {pending: Object.assign(new Error(`${err.code}: the lock's breaker ${breaker} could not be made`), {code: err.code, path: breaker})};
244
+ if (err.code !== 'EEXIST') throw err;
245
+ // A breaker left by a crash in the few lines below.
246
+ try { if (Date.now() - fs.statSync(breaker).mtimeMs > BREAK_STALE_MS) fs.rmSync(breaker, {force: true}); } catch (e) { /* gone */ }
247
+ return false;
248
+ }
249
+ try {
250
+ if (!sameHolder(readHolder(file), dead)) return false;
251
+ fs.rmSync(file, {force: true});
252
+ return true;
253
+ } finally {
254
+ fs.rmSync(breaker, {force: true});
255
+ }
256
+ }
257
+
258
+ // fn: an async function -> its exit code; or 1 when the lock is held.
259
+ // wait: true waits for the holder for as long as it takes, saying so every
260
+ // PROGRESS_MS (start: an install's npm ci can run for minutes).
261
+ // packs.lock on credentials.lock's options (post-rel packs.lock protocol,
262
+ // the reviewer 11-20): a reused PID is gone (started); another host's lock
263
+ // is never taken for gone by age (ageOtherHosts: false), waited for at most
264
+ // STALE_MS by start (waitRemoteMs; io.lockWaitMs, the tests'), then said
265
+ // with the file to remove; a live local holder with its recorded start time
266
+ // is never taken for gone by age (trustStarted: a long install isn't
267
+ // stolen). The hint to remove the file is said only where nothing here can
268
+ // tell whether its holder runs: another host's, or an unreadable lock.
269
+ // missing: what to do when the home isn't there (withLockFile's), else fn
270
+ // runs unlocked
271
+ async function withLock(where, io, fn, {wait = false, signal = null, missing = null} = {}) {
272
+ const file = path.join(where.home, 'packs.lock');
273
+ return withLockFile(file, where.home, io, fn, {wait, signal, missing,
274
+ started: true, ageOtherHosts: false, trustStarted: true,
275
+ waitRemoteMs: io != null && Number.isInteger(io.lockWaitMs) ? io.lockWaitMs : STALE_MS,
276
+ heldMessage: ({holder, who, removable, stopped, quiet}) => (stopped
277
+ ? `ch-local: another ch-local (${who}) holds this home's lock and is stopped (Ctrl-Z): resume it (fg, or kill -CONT ${holder.pid}) to let it finish, or end it (kill -9 ${holder.pid}), and try again`
278
+ : quiet
279
+ ? `ch-local: another ch-local (${who}) is changing this home but has not renewed its lock for over ${Math.round(STALE_MS / 60000)} minutes; try again when it is done, or if it is hung, end it (kill ${holder.pid}) and try again`
280
+ : `ch-local: another ch-local (${who}) is changing this home; try again when it is done${removable ? removeHint(file, holder) : ''}`)});
281
+ }
282
+
283
+ // The same protocol for any lock file: `dir` must exist (with none there is
284
+ // nothing to guard, and fn runs unlocked). fn(release) may release the lock
285
+ // before it ends (ch-local daemon: once its runtime listens, while the
286
+ // runtime runs on); the release at the end is then skipped.
287
+ // what: how the waiting line names the holder's work.
288
+ // signal: an abort ends a wait, with 1 and fn never run
289
+ async function withLockFile(file, dir, io, fn, {wait = false, what = 'to finish changing this home', signal = null,
290
+ started = false, ageOtherHosts = true, trustStarted = false, waitRemoteMs = null, waitMs = null, missing = null, doing = null, heldMessage = null} = {}) {
291
+ const where = {home: dir};
292
+ const host = lockHost();
293
+ const mine = {pid: process.pid, host, at: new Date().toISOString()};
294
+ if (started) {
295
+ mine.started = processStarted(process.pid);
296
+ mine.boot = bootId();
297
+ mine.machine = machineId();
298
+ }
299
+ if (doing != null) mine.doing = doing;
300
+ const unlocked = () => (typeof missing === 'function' ? missing() : fn(() => {}, null));
301
+ // the clock the waits are measured on, and how a wait sleeps: a test may
302
+ // give its own (io.lockNow, io.lockSleep), as it gives io.lockWaitMs, so a
303
+ // wait is decided by what it observes, never by a timer's luck
304
+ const now = typeof io.lockNow === 'function' ? io.lockNow : Date.now;
305
+ const sleep = typeof io.lockSleep === 'function' ? io.lockSleep : (ms) => new Promise((r) => setTimeout(r, ms));
306
+ // (the platform whose refusals are read: a test may give one, io.lockPlatform)
307
+ const platform = typeof io.lockPlatform === 'string' ? io.lockPlatform : process.platform;
308
+ const since = now();
309
+ // a name being deleted (Windows): since when, on this clock, and the next step
310
+ let pendingSince = null;
311
+ let pendingStep = 25;
312
+ // the lock this waiter is watching, and when (its own clock) it last saw
313
+ // the lock change: a new holder, or its mtime moved
314
+ let watched = null;
315
+ let lastSaid = waitMs != null ? -Infinity : now();
316
+ // the last look, for the line said when the wait gives up (#104's high, 5)
317
+ let look = null;
318
+ for (let attempt = 0; ; attempt++) {
319
+ try {
320
+ if (!fs.existsSync(where.home)) return unlocked();
321
+ // (a name being deleted, the lock's or its breaker's: busy, tried again,
322
+ // backing off, until the deadline; then the refusal itself, never a held
323
+ // lock; said nothing meanwhile, as a wait of at most PENDING_WAIT_MS)
324
+ const pending = async (refusal) => {
325
+ if (signal != null && signal.aborted) return 1;
326
+ if (pendingSince == null) pendingSince = now();
327
+ if (now() - pendingSince >= PENDING_WAIT_MS) throw refusal;
328
+ await sleep(pendingStep);
329
+ pendingStep = Math.min(pendingStep * 2, 1000);
330
+ return null;
331
+ };
332
+ const made = create(file, mine, platform);
333
+ if (made === true) break;
334
+ if (made !== false) {
335
+ if (await pending(made.pending) === 1) return 1;
336
+ continue;
337
+ }
338
+ const holder = readHolder(file);
339
+ // a holder with no usable pid is one this host can't judge: as an
340
+ // unreadable lock (#104's high, 4)
341
+ const pidOk = holder != null && Number.isInteger(holder.pid) && holder.pid > 0;
342
+ // empty or unreadable: being written by an older ch-local, never stale
343
+ let mtime = null;
344
+ try { mtime = fs.statSync(file).mtimeMs; } catch (e) { mtime = null; }
345
+ const place = pidOk ? (started ? placeOf(holder, host, mtime) : (holder.host === host ? 'here' : 'remote')) : null;
346
+ const here = place === 'here';
347
+ const sameMachine = place === 'machine';
348
+ // (one read of /proc per look: the medium on post-rel packs.lock, 7,
349
+ // and on #104's round 1, 7; a zombie or dead process holds nothing:
350
+ // #104's high, 1)
351
+ const stat = here ? processStat(holder.pid) : null;
352
+ const aliveNow = here ? alive(holder.pid) && !deadState(stat.state) : null;
353
+ const recorded = holder != null && typeof holder.started === 'string' ? holder.started : null;
354
+ const reused = started && here && recorded != null && stat.started != null && stat.started !== recorded;
355
+ // (exactly the holder that recorded it: alive, the same start time)
356
+ const exact = trustStarted && started && here && recorded != null && aliveNow === true && stat.started === recorded;
357
+ // stopped (T): an exact holder that will not finish by itself
358
+ const stopped = exact && (stat.state === 'T' || stat.state === 't');
359
+ const age = heartbeatAge(file);
360
+ // not renewing: an exact holder busy or hung (never cleared; said with
361
+ // what to do: the medium on #104's round 1, 4)
362
+ const quiet = exact && !stopped && age > STALE_MS;
363
+ // (the same machine in another PID namespace: aged by heartbeat, as
364
+ // the reviewer's #104 high, 2, asks; its PIDs can't be read from here,
365
+ // so a long install there is not protected as one here is: the limit)
366
+ const aged = (ageOtherHosts || here || sameMachine) && !exact && age > STALE_MS;
367
+ const gone = pidOk && ((here && aliveNow === false) || reused || place === 'rebooted' || aged);
368
+ if (gone) {
369
+ const cleared = clearStale(file, holder, platform);
370
+ if (cleared === true) continue;
371
+ if (cleared !== false) {
372
+ if (await pending(cleared.pending) === 1) return 1;
373
+ continue;
374
+ }
375
+ }
376
+ // (neither name pending this look: the pending wait starts afresh)
377
+ pendingSince = null;
378
+ pendingStep = 25;
379
+ const bounded = waitMs != null && now() - since < waitMs;
380
+ // an exact holder here is waited for as long as it takes (start can be
381
+ // interrupted), unless it is stopped; one this host can't judge
382
+ // (another host, unreadable, no pid) is watched, and given up on once
383
+ // it hasn't changed for waitRemoteMs by this host's clock
384
+ const judgeable = (here && !stopped) || sameMachine;
385
+ // (two unreadable reads are the same lock: sameHolder is false for
386
+ // nulls, which reset the watch each look and never gave up)
387
+ const sameAsWatched = watched != null && ((watched.holder == null && holder == null) || sameHolder(watched.holder, holder));
388
+ if (!sameAsWatched || watched.mtime !== mtime) watched = {holder, mtime, since: now()};
389
+ const watchDone = wait && waitRemoteMs != null && !judgeable && now() - watched.since >= waitRemoteMs;
390
+ const who = !pidOk ? `an unreadable lock ${file}` : `pid ${holder.pid}${here ? '' : ` on ${hostLabel(holder)}`}`;
391
+ look = {holder: pidOk ? holder : null, who, removable: !here && !sameMachine, stopped, quiet};
392
+ if ((wait && !watchDone) || bounded) {
393
+ if (signal != null && signal.aborted) return 1;
394
+ if (now() - lastSaid >= (io.lockProgressMs || PROGRESS_MS)) {
395
+ lastSaid = now();
396
+ // (a stopped or quiet holder said as such while waited for: the
397
+ // medium on #104's round 1, 4 and 6)
398
+ const why = stopped ? `; it is stopped (Ctrl-Z): resume it (fg, or kill -CONT ${holder.pid})`
399
+ : quiet ? `; it has not renewed its lock for over ${Math.round(STALE_MS / 60000)} minutes: if it is hung, end it (kill ${holder.pid})` : '';
400
+ io.stderr.write(`ch-local: waiting for another ch-local (${holder == null ? 'starting' : who}) ${what}${why}\n`);
401
+ }
402
+ await sleep(200);
403
+ continue;
404
+ }
405
+ // (given up after a wait: one more try, then the last look's line;
406
+ // the medium on #104's round 1, 8: never twice in a row unwaited)
407
+ if (wait || waitMs != null) {
408
+ const last = create(file, mine, platform);
409
+ if (last === true) break;
410
+ // (its name being deleted as this waiter gives up: the lock is about
411
+ // to be free, so the pending wait, never the held line)
412
+ if (last !== false) {
413
+ if (await pending(last.pending) === 1) return 1;
414
+ continue;
415
+ }
416
+ }
417
+ } catch (err) {
418
+ if (err.code === 'ENOENT') return unlocked();
419
+ throw err;
420
+ }
421
+ {
422
+ const {holder, who, removable, stopped, quiet} = look != null ? look : {holder: null, who: `an unreadable lock ${file}`, removable: true, stopped: false, quiet: false};
423
+ if (typeof heldMessage === 'function') {
424
+ io.stderr.write(`${heldMessage({holder, who, file, removable, stopped, quiet})}\n`);
425
+ return 1;
426
+ }
427
+ io.stderr.write(`ch-local: another ch-local (${who}) is changing this home; try again when it is done, or remove ${file} if nothing is running\n`);
428
+ return 1;
429
+ }
430
+ }
431
+ // the heartbeat: a lock whose holder lives keeps a fresh mtime
432
+ const beat = setInterval(() => { try { const t = new Date(); fs.utimesSync(file, t, t); } catch (err) { /* released */ } }, HEARTBEAT_MS);
433
+ if (typeof beat.unref === 'function') beat.unref();
434
+ let released = false;
435
+ const release = () => {
436
+ if (released) return;
437
+ released = true;
438
+ clearInterval(beat);
439
+ if (sameHolder(readHolder(file), mine)) fs.rmSync(file, {force: true});
440
+ };
441
+ // (frozen: a holder can't swap its check for one that always passes;
442
+ // the medium on #102 round 1, 4)
443
+ const held = Object.freeze({
444
+ file,
445
+ check() {
446
+ if (released || !sameHolder(readHolder(file), mine)) throw Object.assign(new Error(`${file} is no longer this ch-local's lock`), {code: 'LOCK_LOST'});
447
+ },
448
+ });
449
+ try {
450
+ return await fn(release, held);
451
+ } finally {
452
+ release();
453
+ }
454
+ }
455
+
456
+ module.exports = {withLock, withLockFile, lockHost, processStarted, processState, bootId, machineId, bootTimeMs, placeOf, removeHint, hostLabel, createWhole, pendingRefusal, STALE_MS, HEARTBEAT_MS};