@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,1036 @@
1
+ 'use strict';
2
+ // A running start applies a home's pack changes to its runtime (packs in
3
+ // place, part 2, plan Task B3): a pack added is loaded, one removed unloaded,
4
+ // one at another tree (an upgrade, a rollback, a changed part) reloaded; one
5
+ // at a time, in order, each with its notice, which the runtime shows once
6
+ // (countinghouse's notices). Every applied or failed change is appended to
7
+ // <home>/history.jsonl. What is loaded is kept in the run directory's
8
+ // run.json, which collection reads (lib/gc.js).
9
+ // From the module store (#413 L1a-2): each request is the runtime's module
10
+ // form, naming the pack's scenario by its package name and each module's
11
+ // store directory: load {name, dirs}, reload {names: [scenario], dirs},
12
+ // unload {name}. (The pack form is gone: countinghouse M6.)
13
+ // By module (#413 sections 5.2 and 9.8; L2a): what loads is each available
14
+ // top-level module (lib/availability.js), once, whichever packs record it;
15
+ // `loaded` is keyed by its package name. On/off, the ceiling and the
16
+ // credentials are by module (lib/module-seams.js, lib/module-credentials.js:
17
+ // L2b). A record of another release (an upgrade
18
+ // or a release rollback while this start runs) is judged by none of this
19
+ // start's pins: it keeps what it loaded, unloads what the record withdrew
20
+ // or moved back, and loads and reloads nothing.
21
+ const fs = require('node:fs');
22
+ const path = require('node:path');
23
+ const {readModulesRecord: readRecord} = require('./module-record');
24
+ const {removeHint, releaseOf, recordRelease, staleLine, installLine, entryOf, holds} = require('./packs');
25
+ const {availability, short} = require('./availability');
26
+ const {readOwnRecord} = require('./own-record');
27
+ const {chLocal} = require('./command-line');
28
+ const {compareVersions} = require('./semver-order');
29
+ const {moduleSeams} = require('./module-seams');
30
+ const moduleCredentials = require('./module-credentials');
31
+ const heldBack = require('./held-back');
32
+ const {writeAtomic} = require('./atomic');
33
+ const {readSettings, valueOf, runtimeValue, withSettingsLock, loosens, shown} = require('./settings');
34
+ const {ceilingFor, ceilingRefusal, startUnderCeiling, forbiddenBy} = require('./ceiling');
35
+ const {reportOutsideEdits} = require('./outside-edits');
36
+
37
+ // The settings a running runtime takes at once (countinghouse_settings'
38
+ // "now" ones); the rest apply at the next start.
39
+ const LIVE = ['maxOutputBytes', 'requestTimeout'];
40
+
41
+ const {appendHistory} = require('./history');
42
+ const {enforceAvailable} = require('./sandbox-support');
43
+ const {teller} = require('./control');
44
+ const {copyState} = require('./own-tree');
45
+ // whether two packs' module versions are the same: no reload between them
46
+ const sameModules = (a, b) => {
47
+ const x = Object.entries(a || {}).sort(([m], [n]) => (m < n ? -1 : 1));
48
+ const y = Object.entries(b || {}).sort(([m], [n]) => (m < n ? -1 : 1));
49
+ return JSON.stringify(x) === JSON.stringify(y);
50
+ };
51
+ // Under a home upgraded or rolled back under this process (#413 section
52
+ // 9.8), the unloads no pins decide: a
53
+ // module removed from the record (or a callee of it no longer installed:
54
+ // the medium review of the high round, 1), no longer a pack's top-level
55
+ // module, turned off, refused by the ceiling, or without its credential;
56
+ // a caller goes with a callee unloaded for one of these.
57
+ // (an own module's reasons too: no pins decide them -- B-own-add)
58
+ const NO_PINS = ['removed', 'not installed', 'not top-level', 'off', 'ceiling', 'credential', 'changed', 'gone', 'sandbox', 'collision'];
59
+ // a unit's version as a notice says it: an own module's by its code's hash
60
+ const shownVersion = (p) => (p.own === true ? `(own, ${String(p.version).slice(0, 12)})` : p.version);
61
+ // the own module (its version a tree hash) in two closures whose code
62
+ // differs, or null
63
+ const TREE_VERSION = /^[0-9a-f]{64}$/;
64
+ // the own module of this closure whose entry was added again since `was` was
65
+ // loaded, its code the same, or null: what runs is loaded again all the same
66
+ // (its copy may have changed since, and a worker that started again run that)
67
+ const addedAgain = (was, p) => {
68
+ for (const [m, at] of Object.entries(p.added || {})) {
69
+ if (was.added != null && Object.prototype.hasOwnProperty.call(was.added, m) && was.added[m] !== at && was.modules != null && was.modules[m] === p.modules[m]) return m;
70
+ }
71
+ return null;
72
+ };
73
+ const ownCodeChanged = (a, b) => {
74
+ for (const m of Object.keys(b || {})) {
75
+ // (either side a tree: a callee moved between own and a pack too)
76
+ if (a != null && Object.prototype.hasOwnProperty.call(a, m) && a[m] !== b[m] && (TREE_VERSION.test(String(b[m])) || TREE_VERSION.test(String(a[m])))) return m;
77
+ }
78
+ return null;
79
+ };
80
+ // the loaded-map entry of a unit
81
+ // a runtime's code as the held-back file and a notice may carry it
82
+ const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
83
+ const entryFor = (p) => ({version: p.version, scenario: p.name, modules: p.modules, ...(p.own === true ? {own: true, added: p.added} : {})});
84
+
85
+ // state: {where, io, runDir, control, loaded: Map name ->
86
+ // {key, version, scenario}, say, host}. -> {apply() -> Promise}
87
+ // The runtime knows a pack by its scenario's package name (countinghouse
88
+ // #205), so every load, reload and unload names that; a removed pack's is
89
+ // kept in `loaded`, since packs.json no longer has it. The history and the
90
+ // notices name the pack.
91
+ // the runtime's cut of a notice (countinghouse lib/notices.js NOTICE_MAX)
92
+ const NOTICE_MAX = 200;
93
+
94
+ function inPlace(state) {
95
+ const {where, io, runDir, control, loaded, say: sayAlways, host} = state;
96
+ // set by close(): nothing more is applied, said, told or recorded (an
97
+ // apply or a module-stopped already under way included: the medium on
98
+ // #106's round 1, 2)
99
+ let closed = false;
100
+ const say = (text) => { if (!closed) sayAlways(text); };
101
+ // the withdrawn modules this start has told the sessions about (start's
102
+ // notices and the unloads here): never told twice
103
+ const withdrawnTold = state.withdrawnTold instanceof Set ? state.withdrawnTold : new Set();
104
+ // never silent (part 3, section 5): start's teller (lib/control.js), which
105
+ // said what start found; on its own, said and told here
106
+ const tellAlways = state.tell || (() => { const t = teller(say); t.attach(control); return t.tell; })();
107
+ const tell = (text, o) => { if (!closed) tellAlways(text, o); };
108
+ // (in shared mode a client's restart attaches to the same runtime, which
109
+ // runs until 10 minutes after its last session: what applies "at the next
110
+ // start" applies when it restarts, which `ch-local restart` asks for, the
111
+ // sessions resuming -- A5)
112
+ const shared = state.shared === true;
113
+ const restartLine = () => require('./command-line').chLocal(where, 'restart');
114
+ // (no "(your sessions resume)": a notice is cut at 200 characters, and
115
+ // the restart command says it -- the reviewer's high on #147, M3)
116
+ const restartTo = (what, now = false) => (shared ? `run \`${restartLine()}\` ${now ? 'now ' : ''}to ${what}` : `restart your client ${now ? 'now ' : ''}to ${what}`);
117
+ const restartBare = () => (shared ? `run \`${restartLine()}\`` : 'restart your client');
118
+ const nextStart = () => (shared ? `when the shared runtime restarts (\`${restartLine()}\`)` : 'at the next start');
119
+ const earlierLine = () => (shared ? `run \`${restartLine()}\` now` : 'restart your client now');
120
+ // (a loosening's notice hands the model no command: applying it stays the
121
+ // user's own act -- the reviewer's high on #147, M5)
122
+ const loosenedLater = () => (shared ? 'when the shared runtime restarts' : 'at the next start');
123
+ // (in shared mode, start's stderr is the daemon's, which no client reads:
124
+ // a line the user must act on goes out as a notice; per-session, said as
125
+ // before -- L2)
126
+ // (once: a line already told is said again, never told again -- the
127
+ // reviewer's high on #147, N3)
128
+ // (keyed by what it is about, with the text last told: a condition that
129
+ // resolves forgets its key, so it is told again if it comes back -- the
130
+ // medium on #147's last round, 3)
131
+ const toldToAct = new Map();
132
+ const sayToAct = (text, key = text, about = null) => { if (shared && toldToAct.get(key) !== text) { toldToAct.set(key, text); tell(text, {about}); } else say(text); };
133
+ const resolvedToAct = (key) => toldToAct.delete(key);
134
+ // (in shared mode a notice is cut at 200 characters: the command, at the
135
+ // end, kept whole, the explanation before it cut -- M3)
136
+ // (measured in code points, as the cut; a tail that leaves no room for an
137
+ // explanation goes alone -- the medium on #147's last round, 8)
138
+ const codePoints = (x) => [...x].length;
139
+ const fitShared = (head, tail) => {
140
+ if (!shared || codePoints(head) + codePoints(tail) <= NOTICE_MAX) return `${head}${tail}`;
141
+ const room = NOTICE_MAX - codePoints(tail);
142
+ return room >= 20 ? `${require('./command-line').terminalText(head, room)}${tail}` : tail.replace(/^[;:,]\s*/, '');
143
+ };
144
+ // (a change not applied in place may carry a loosening -- a pack turned
145
+ // on, a setting loosened -- so in shared mode it names no command: the
146
+ // model is never handed the restart that applies a loosening; business's
147
+ // condition on #147. Per-session, as before)
148
+ const notApplied = () => (shared ? 'it applies when the shared runtime restarts' : restartTo('apply it'));
149
+ const loosenedText = (name, was, now, later) => `${name} loosened from ${shown(name, was)} to ${shown(name, now)}${later ? `, ${loosenedLater()}${typeof(later) === 'string' ? ` (${later})` : ''}` : ''}`;
150
+ // the settings the runtime was started with (start's own reading), so a
151
+ // change made before the watcher began is still applied
152
+ let applied = state.settings != null ? state.settings : readSettings(where);
153
+ // the runtime this start spawned: a pack change against another runtime
154
+ // version waits for the next start (the review of ch-local #13)
155
+ const runtimeAtSpawn = JSON.stringify(state.runtimeVersions || null);
156
+ let runtimeSaid = false;
157
+ let settingsSaid = null;
158
+ let ceilingSaid = null;
159
+ // what was told already, start's included: told once
160
+ const notesSaid = state.told || new Set();
161
+ const history = (entry) => { if (!closed) appendHistory(where, {by: 'start', ...entry}, {host, pid: io.pid}); };
162
+ // the modules the runtime stopped for good in this start (module-stopped,
163
+ // #413 section 7.3): module -> {code, version}, run.json's stopped, which
164
+ // status shows. Never loaded again in this start unless the module's
165
+ // active version changes; a fresh start begins with none, so each is tried
166
+ // again then (the Reviewer on L2a: a transient crash never keeps it out).
167
+ const stopped = new Map();
168
+ // the record the last apply read, a stop's baseline when it cannot be read
169
+ let lastRecord = state.record != null ? state.record : null;
170
+ // the closure the runtime was last asked to run, by top-level module
171
+ // (start's plan, then each load and reload as it is sent): a stop is
172
+ // recorded at that, so a module that crashes on a reload is never let
173
+ // back in at the version it crashed on (the high review of L2a, 4)
174
+ const askedAdded = new Map(); // and the own entries' addedAt it was asked with
175
+ const asked = new Map([...loaded].map(([n, v]) => [n, v.modules || null]));
176
+ // a request that never reached the runtime (refused busy, or not sent):
177
+ // it was never asked to run the new closure, so what was asked before
178
+ // stands. No answer, or a runtime gone, may follow a request it took and
179
+ // runs: the new closure stands then, as after any other refusal (the
180
+ // high review of L2a's medium round, 1)
181
+ const NEVER_REACHED = ['CONTROL_BUSY', 'CONTROL_SEND_FAILED'];
182
+ // a load the runtime refused: by a code of its own, never the channel's
183
+ // (CONTROL_*: not answered, not taken now, or a passing condition)
184
+ const refusedBy = (reply) => (reply.ok !== true && CODE.test(String(reply.code)) && !String(reply.code).startsWith('CONTROL_') ? reply.code : null);
185
+ // (a load not answered may yet be done)
186
+ const unanswered = (reply) => reply.ok !== true && ['CONTROL_NO_ANSWER', 'CONTROL_GONE'].includes(reply.code);
187
+ // own modules whose load was not answered -> the code it was of: until one of
188
+ // it is answered, what became of it is not known
189
+ const loadUnanswered = new Map();
190
+ // own modules whose load this apply sent and the runtime refused -> code
191
+ const loadRefused = new Map();
192
+ // run.json's ownSeen and ownAt (lib/own-applied.js): own.json as last
193
+ // applied, whole, and which it was
194
+ let ownSeen = null;
195
+ let ownAt = null;
196
+ // the units of the start's own plan: the runtime does not say when it has
197
+ // loaded them, and may yet refuse one, until a request of one is answered
198
+ const planned = new Set(loaded.keys());
199
+ const askOr = (name, reply, before) => {
200
+ if (reply.ok === true || !NEVER_REACHED.includes(reply.code)) return;
201
+ if (before === undefined) asked.delete(name); else asked.set(name, before);
202
+ };
203
+
204
+ // run.json's loaded: every module version this runtime holds
205
+ // ({module: version}), which collection keeps (lib/gc.js collectStore)
206
+ const RUN_TRIES = 50;
207
+ let runTries = 0;
208
+ let runRetry = null;
209
+ const writeRun = () => {
210
+ // a module two loaded packs hold at different versions keeps both (the
211
+ // medium review of L1a-2, 5): run.json's value is then a list
212
+ const versions = {};
213
+ for (const v of loaded.values()) {
214
+ for (const [m, ver] of Object.entries(v.modules || {})) {
215
+ const had = versions[m];
216
+ if (had == null) versions[m] = ver;
217
+ else if (![].concat(had).includes(ver)) versions[m] = [].concat(had, ver);
218
+ }
219
+ }
220
+ try {
221
+ const file = path.join(runDir, 'run.json');
222
+ const run = JSON.parse(fs.readFileSync(file, 'utf8'));
223
+ const why = Object.fromEntries([...stopped].map(([m, s]) => [m, s.code]));
224
+ // (an own module the runtime refused at its start: status says so)
225
+ const refused = Object.fromEntries([...stopped].filter(([, s]) => s.refused === true).map(([m, s]) => [m, {code: s.code, tree: s.tree}]));
226
+ writeAtomic(file, JSON.stringify({...run, loaded: versions, stopped: why, refused, ownSeen, ownAt}) + '\n');
227
+ runTries = 0;
228
+ } catch (err) {
229
+ // (the run directory is gone: start is ending)
230
+ if (closed || err.code === 'ENOENT' || runRetry != null || runTries >= RUN_TRIES) return;
231
+ // (Windows refuses a rename over a file another process is reading)
232
+ runTries += 1;
233
+ runRetry = setTimeout(() => { runRetry = null; writeRun(); }, 100);
234
+ if (typeof runRetry.unref === 'function') runRetry.unref();
235
+ }
236
+ };
237
+ // the slots this runtime was started with, by module (lib/module-
238
+ // credentials.js forStart: {variable, origin, source, digest, slot}); a
239
+ // load or reload carries, for each module of its closure that has one, its
240
+ // allowance naming that slot (#413 section 7.3, M4's credentials field), and
241
+ // only a slot that still matches the store (applyStates decided the
242
+ // module available)
243
+ const identities = state.identities instanceof Map ? state.identities : new Map();
244
+ const allowanceOf = (modules) => {
245
+ const out = {};
246
+ for (const m of modules) {
247
+ const id = identities.get(m);
248
+ if (id != null) out[m] = {[id.origin]: {[id.variable]: id.slot}};
249
+ }
250
+ return out;
251
+ };
252
+ // where a key goes is said once per module: start said it for what it
253
+ // loaded; one loaded later is said here, when its key first goes with a
254
+ // load or reload (the medium on the high round, 5)
255
+ const sendsSaid = state.sendsSaid instanceof Set ? state.sendsSaid : new Set();
256
+ const withAllowance = (msg, modules) => {
257
+ const a = allowanceOf(modules);
258
+ return Object.keys(a).length > 0 ? {...msg, credentials: a} : msg;
259
+ };
260
+ // said, and marked said, only once the runtime took the load or reload
261
+ // (the Reviewer's round 3, 5: as an unload's notice)
262
+ const sayWhereKeysGo = (msg) => {
263
+ for (const m of Object.keys(msg.credentials || {})) {
264
+ if (sendsSaid.has(m)) continue;
265
+ sendsSaid.add(m);
266
+ const id = identities.get(m);
267
+ say(`sends ${id.variable} to ${id.origin} for ${short(m)}${id.source === 'gh' ? ' (your gh login\'s token, held in memory)' : ''}`);
268
+ }
269
+ };
270
+ // one reload for several packs: every scenario named, every module's
271
+ // directory given, one notice for all; each pack's history line as a
272
+ // send's would be. The runtime switches them all or none. -> whether it did.
273
+ const sendReload = async (list) => {
274
+ const dirs = Object.assign({}, ...list.map(({p}) => p.dirs));
275
+ const notice = list.map((r) => r.notice).join('; ');
276
+ const before = new Map(list.map(({p}) => [p.name, asked.get(p.name)]));
277
+ for (const {p} of list) asked.set(p.name, p.modules);
278
+ const reloadMsg = withAllowance({type: 'reload', names: list.map(({p}) => p.name), dirs, notice: require('./command-line').fitHeld(notice, list.length === 1 ? short(list[0].p.name) : null)}, Object.keys(dirs));
279
+ const reply = await control.request(reloadMsg);
280
+ for (const {p} of list) askOr(p.name, reply, before.get(p.name));
281
+ if (reply.ok === true) {
282
+ sayWhereKeysGo(reloadMsg);
283
+ resolvedToAct('reload');
284
+ for (const {p, how, notice: own} of list) {
285
+ // wanted again: a later refused unload of it is told again (3), and
286
+ // an earlier "restart now" is resolved (the medium on round 3, 5)
287
+ if (stuck.delete(p.name)) tell(`module ${short(p.name)} is served again as it should be; the earlier "${earlierLine()}" no longer applies`, {about: short(p.name)});
288
+ loaded.set(p.name, entryFor(p));
289
+ planned.delete(p.name);
290
+ history({module: p.name, change: how, notice: own});
291
+ }
292
+ writeRun();
293
+ say(notice);
294
+ return true;
295
+ }
296
+ for (const {p, how, notice: own} of list) history({module: p.name, change: how, notice: own, problem: `${reply.code || 'failed'}: ${reply.message || ''}`.slice(0, 300)});
297
+ sayToAct(fitShared(notice, `: not applied in place (${reply.code || 'failed'}); ${notApplied()}`), 'reload');
298
+ return false;
299
+ };
300
+ // notice: its text, or {text, head} where the text ends in a command: a
301
+ // failure line is then built on the head, never cutting the command (the
302
+ // medium on #147's last round, 2); in shared mode a text's own is what comes
303
+ // before its command, where the two don't fit together or it is the restart
304
+ const send = async (change, p, msg, given) => {
305
+ // (as the runtime tells it: within its notice cut, the command whole; the
306
+ // history and stderr have it whole)
307
+ const notice = typeof given === 'string' ? given : given.text;
308
+ const before = asked.get(p.name);
309
+ const addedBefore = askedAdded.get(p.name);
310
+ if (msg.type === 'load') { asked.set(p.name, p.modules); askedAdded.set(p.name, p.added); }
311
+ const reply = await control.request({...msg, notice: require('./command-line').fitHeld(notice, short(p.name))});
312
+ if (msg.type === 'load') askOr(p.name, reply, before);
313
+ if (msg.type === 'load' && reply.ok !== true && NEVER_REACHED.includes(reply.code)) askedAdded.set(p.name, addedBefore);
314
+ if (msg.type === 'load') {
315
+ loadsSent.add(p.name);
316
+ // (only a request that reached the runtime: refused, or not answered,
317
+ // where it may be serving; never CONTROL_BUSY or SEND_FAILED, which
318
+ // left it unloaded: the reviewer's round 2 on #106, 3)
319
+ if (reply.ok === true || NEVER_REACHED.includes(reply.code)) loadFailed.delete(p.name); else loadFailed.add(p.name);
320
+ if (refusedBy(reply) != null) loadRefused.set(p.name, reply.code);
321
+ if (unanswered(reply)) loadUnanswered.set(p.name, p.version); else if (reply.ok === true || refusedBy(reply) != null) loadUnanswered.delete(p.name);
322
+ }
323
+ if (reply.ok === true) {
324
+ planned.delete(p.name);
325
+ resolvedToAct(`pack:${p.name}`);
326
+ if (msg.type === 'unload') loaded.delete(p.name); else loaded.set(p.name, entryFor(p));
327
+ // a load: where its keys go is said now, and it is wanted again, so a
328
+ // later refused unload of it is told again (the Reviewer's round 3, 3, 5)
329
+ if (msg.type === 'load') {
330
+ sayWhereKeysGo(msg);
331
+ if (stuck.delete(p.name)) tell(`module ${short(p.name)} is served again as it should be; the earlier "${earlierLine()}" no longer applies`, {about: short(p.name)});
332
+ }
333
+ writeRun();
334
+ history({module: p.name, change, notice});
335
+ // a request's notice rides on it, and the runtime tells the sessions
336
+ // (an unload's, those that listed it before it goes: B3 Task 6): said
337
+ // here only, never told again (the high review of L2a, 7)
338
+ say(notice);
339
+ return;
340
+ }
341
+ history({module: p.name, change, notice, problem: `${reply.code || 'failed'}: ${reply.message || ''}`.slice(0, 300)});
342
+ const failed = `: not applied in place (${reply.code || 'failed'}); ${notApplied()}`;
343
+ const head = typeof given !== 'string' ? given.head
344
+ : shared && (codePoints(given) + codePoints(failed) > NOTICE_MAX || given.includes(restartLine())) ? require('./command-line').beforeCommand(given) : given;
345
+ sayToAct(fitShared(head, failed), `pack:${p.name}`, short(p.name));
346
+ };
347
+ // Part 3 while start runs: an edit made outside the tools is said and
348
+ // recorded (under the settings lock, as at start), and what is applied is
349
+ // bound by the operator's ceiling as start's values are: a cap or timeout
350
+ // clamped, a pack turned on that it forbids left off; under a ceiling that
351
+ // cannot be trusted, a change that loosens keeps the settings in effect.
352
+ let recheck = null;
353
+ // (each pack's clash notice as last said: said once per change)
354
+ const clashSaid = new Map();
355
+ // packs whose load the runtime refused or did not answer: whether a
356
+ // restart loads one is not known, and an unanswered one may be serving, so
357
+ // the held-back list does not name it (the medium on #106's round 1, 5)
358
+ const loadFailed = new Set();
359
+ // (the loads sent in this apply: a pack whose load failed and that was not
360
+ // sent this time -- a clash, a frozen home, no longer available -- has its
361
+ // own reason now, and the list names it again: round 2, 3)
362
+ const loadsSent = new Set();
363
+ // the credentials' states as last read (start's at first): a store that
364
+ // could not be read (EBUSY, a racing add) decides nothing; the last good
365
+ // states stand and it is read again shortly, so only a read that
366
+ // succeeds and differs unloads (the Reviewer's high review of L5a, 3)
367
+ // A last good state stands only for a module whose declaration is the
368
+ // same as when it was read: one installed or changed since is not usable
369
+ // until a read decides it (the medium on the high round, 2). A read that
370
+ // keeps failing is tried again after 1 s, then 2, 4 ... up to 60 s (3).
371
+ let lastCredentialStates = state.credentialStates instanceof Map ? state.credentialStates : null;
372
+ const declKey = (d) => (d == null ? '' : `${d.problem || ''} ${d.variable} ${d.origin}`);
373
+ let lastDecls = lastCredentialStates != null && state.credentialDecls instanceof Map
374
+ ? new Map([...state.credentialDecls].map(([m, d]) => [m, declKey(d)])) : null;
375
+ let credentialProblemSaid = null;
376
+ let retryMs = 1000;
377
+ let credentialRetry = null;
378
+ const credentialStates = (record) => {
379
+ const now = moduleCredentials.applyStates(where, record, identities, {shared, platform: io.platform, startStates: state.credentialStates, seen: state.credentialSeen});
380
+ const decls = now.decls != null ? now.decls : moduleCredentials.declarations(where, record);
381
+ if (now.unreadable == null) {
382
+ // a good read: a pending retry, armed with an old delay, goes (6)
383
+ if (credentialRetry != null) { clearTimeout(credentialRetry); credentialRetry = null; }
384
+ lastCredentialStates = now;
385
+ lastDecls = new Map([...decls].map(([m, d]) => [m, declKey(d)]));
386
+ credentialProblemSaid = null;
387
+ retryMs = 1000;
388
+ return now;
389
+ }
390
+ if (credentialProblemSaid !== now.unreadable) {
391
+ credentialProblemSaid = now.unreadable;
392
+ say(`the stored credentials could not be read (${now.unreadable}); what is loaded stays as it is, and they are read again shortly`);
393
+ }
394
+ // its own timer: the settings' 250 ms busy retry (recheck) never waits
395
+ // behind it (the Reviewer's round 3, 4)
396
+ if (credentialRetry == null) {
397
+ credentialRetry = setTimeout(() => { credentialRetry = null; state.reapply(); }, retryMs);
398
+ if (typeof credentialRetry.unref === 'function') credentialRetry.unref();
399
+ retryMs = Math.min(retryMs * 2, 60000);
400
+ }
401
+ const out = new Map();
402
+ for (const [m, d] of decls) {
403
+ const kept = lastCredentialStates != null && lastDecls != null && lastDecls.get(m) === declKey(d) ? lastCredentialStates.get(m) : null;
404
+ out.set(m, kept != null ? kept : {state: 'store-problem', reason: `the stored credentials are not used (${now.unreadable})`});
405
+ }
406
+ return out;
407
+ };
408
+ const bound = (given, record = null) => {
409
+ const platform = io.platform || process.platform;
410
+ const ceiling = ceilingFor(where, {platform, env: io.env});
411
+ const settings = {...given, values: {...given.values}};
412
+ let busy = false;
413
+ // never waits on start's event loop: a writer holding the lock is
414
+ // looked at again shortly (its change fires the watcher too)
415
+ try {
416
+ const edits = withSettingsLock(where, () => reportOutsideEdits(where, readSettings(where), {say: (line) => tell(line, {fit: false}), host, pid: io.pid, refusal: forbiddenBy(ceiling)}), {waitMs: 0});
417
+ for (const e of edits) if (e.refused != null) settings.values[e.setting] = valueOf(applied, e.setting);
418
+ } catch (err) {
419
+ if (err.code === 'SETTINGS_BUSY' && recheck == null) {
420
+ recheck = setTimeout(() => { recheck = null; state.reapply(); }, 250);
421
+ if (typeof recheck.unref === 'function') recheck.unref();
422
+ }
423
+ // a lock held never turns the checks off: what loosens keeps what is in
424
+ // effect until the history can be compared (the review of #18)
425
+ busy = true;
426
+ }
427
+ if (busy || ceiling.state === 'untrusted') {
428
+ // each loosening against what is in effect keeps what is in effect;
429
+ // tightenings apply
430
+ const kept = [];
431
+ for (const name of new Set([...Object.keys(applied.values), ...Object.keys(settings.values)])) {
432
+ if (!loosens(name, valueOf(applied, name), valueOf(settings, name))) continue;
433
+ if (Object.prototype.hasOwnProperty.call(applied.values, name)) settings.values[name] = applied.values[name]; else delete settings.values[name];
434
+ kept.push(name);
435
+ }
436
+ // the outcome first: a notice is cut at 200 characters
437
+ const why = kept.length === 0 ? null : busy
438
+ ? `${kept.join(', ')} not loosened yet, the values in effect kept: the settings are being changed by another writer`
439
+ : `${kept.join(', ')} not loosened, the values in effect kept: ${require('./ceiling').untrustedWhy(ceiling)}`;
440
+ if (why != null && ceilingSaid !== why) tell(why, {fit: false});
441
+ ceilingSaid = why;
442
+ return settings;
443
+ }
444
+ ceilingSaid = null;
445
+ const bounded = startUnderCeiling(settings, ceiling, {where, forcedAudit: !enforceAvailable(where, platform)});
446
+ const values = bounded.values;
447
+ // (a pack or a module turned on in the file: section 8, by module)
448
+ // (apply's own record, read once: the high review of #90, 10)
449
+ const ceilingRecord = record;
450
+ for (const name of Object.keys(values).filter((k) => /^(pack|enabled)\./.test(k))) {
451
+ if (valueOf(applied, name) !== false || values[name] !== true) continue;
452
+ const refusal = ceilingRefusal(ceiling, name, true, ceilingRecord);
453
+ if (refusal == null) continue;
454
+ values[name] = false;
455
+ bounded.notes.push(`${name.replace(/^(pack|enabled)\./, '')} not loaded: ${refusal.message.replace(/; nothing was changed$/, '')}`);
456
+ }
457
+ for (const note of bounded.notes) if (!notesSaid.has(note)) { tell(note, {fit: false}); notesSaid.add(note); }
458
+ return {...settings, values};
459
+ };
460
+ const apply = async () => {
461
+ let record;
462
+ try { record = readRecord(where); } catch (err) { say(`the home cannot be read (${err.message}); nothing applied`); return; }
463
+ lastRecord = record;
464
+ let settings = readSettings(where);
465
+ if (settings.error != null) {
466
+ // fail closed: the last good settings stand
467
+ if (settingsSaid !== settings.error) { say(`${settings.error}; the settings in effect are kept`); settingsSaid = settings.error; }
468
+ settings = applied;
469
+ } else {
470
+ settingsSaid = null;
471
+ settings = bound(settings, record);
472
+ }
473
+ const runtimeChanged = state.runtimeVersions != null && JSON.stringify(record.runtime.versions) !== runtimeAtSpawn;
474
+ // whose home this is (#413 section 9.8): one rule with start
475
+ // (lib/packs.js recordRelease). A process the home was upgraded or
476
+ // rolled back under is frozen: judged by none of its pins, nothing
477
+ // loaded or reloaded, only what no pins decide applied. A record of
478
+ // another release under the home's own ch-local is judged by these
479
+ // pins, and "run ch-local install" said. A changed runtime loads and
480
+ // reloads nothing either. Each said once, start's lines included.
481
+ const ours = releaseOf(io);
482
+ const whose = recordRelease(record, io, where);
483
+ // the home upgraded or rolled back under this process
484
+ const frozenByHome = whose.state === 'stale';
485
+ const frozen = frozenByHome || runtimeChanged;
486
+ const once = (notice, change, about = null) => {
487
+ if (notesSaid.has(notice)) return;
488
+ notesSaid.add(notice);
489
+ history({change, notice});
490
+ tell(notice, {about});
491
+ };
492
+ if (frozenByHome) once(staleLine(whose.installed, whose.how, where, shared), 'release changed');
493
+ else if (whose.state === 'other') once(installLine(whose.ours, where, record, whose.fromHome), 'record of another release');
494
+ if (runtimeChanged && !frozenByHome && !runtimeSaid) {
495
+ runtimeSaid = true;
496
+ // (the command once: M3)
497
+ const notice = shared ? `a runtime update is installed: ${restartTo('use it')}` : `a runtime update applies ${nextStart()}: ${restartTo('use it and the packs installed with it')}`;
498
+ history({change: 'runtime update', notice});
499
+ sayToAct(notice);
500
+ }
501
+ // the operator's allowlist of packs (cached: ceilingFor): an unlisted pack
502
+ // never loads, and one loaded before the list named it is unloaded
503
+ const ceilingNow = ceilingFor(where, {platform: io.platform || process.platform, env: io.env});
504
+ // what is wanted, by module (section 5.2); a credential not set leaves a
505
+ // module out, as start's does
506
+ // the user's own modules (B-own-add): an own.json that can't be read
507
+ // wants none of them (those loaded are unloaded), said once; the sandbox
508
+ // as this start runs it
509
+ let ownRecord = null;
510
+ let ownRead = false;
511
+ // (before it is read: never later than what is)
512
+ const readAt = require('./own-applied').stampOf(where);
513
+ try {
514
+ ownRecord = readOwnRecord(where);
515
+ ownRead = true;
516
+ } catch (err) {
517
+ // (the record's problem cut before the command, which arrives whole)
518
+ // (the record by its name: its problem is what must fit)
519
+ once(err.reason != null ? `your own modules are not loaded: ${err.reason.replace(where.ownRecord, require('node:path').basename(where.ownRecord))}; \`${chLocal(where, 'status')}\` shows them` : `your own modules are not loaded: ${err.message}`, 'own modules unreadable');
520
+ }
521
+ const credentialNow = credentialStates(record);
522
+ const availableWith = (states, sandboxOk) => availability(where, record, {release: ours, pins: !frozenByHome,
523
+ seams: Object.assign(moduleSeams({settings, ceiling: ceilingNow, record, where}), {credential: moduleCredentials.credentialSeam(states)}),
524
+ own: {record: ownRecord, sandboxOk}});
525
+ const av = availableWith(credentialNow, state.ownSandboxOk === true);
526
+ for (const [m, u] of av.shadowed) once(u.line, 'not loaded', short(m));
527
+ // a module the runtime stopped for good is not loaded again in this
528
+ // start unless what it would run has changed (section 7.3): a member of
529
+ // its closure at another version than the runtime was asked to run, or
530
+ // (never asked) its version another than the record named at the stop.
531
+ // Only a record read successfully decides: no failed read, and no
532
+ // rewrite that leaves the module as it was, lets it back in (the high
533
+ // review of L2a's medium round, 7). run.json written once.
534
+ let unstopped = false;
535
+ for (const [m, st] of [...stopped]) {
536
+ const unit = av.units.find((u) => u.name === m);
537
+ // (no baseline at all: no record ever read, nothing asked: kept out for
538
+ // the rest of this start; a fresh start tries it again: the medium
539
+ // review of the high round, 3)
540
+ const changed = unit != null && (st.modules != null ? !sameModules(unit.modules, st.modules)
541
+ : st.known ? st.version == null || unit.version !== st.version : false);
542
+ // (or one of the user's own, added again: what they confirmed is tried)
543
+ if (changed || (unit != null && addedAgain(st, unit) != null)) { stopped.delete(m); unstopped = true; }
544
+ }
545
+ if (unstopped) writeRun();
546
+ const load = av.units.filter((u) => !stopped.has(u.name));
547
+ // a module not available is told once, with its reason (start's lines
548
+ // included: never repeated); one turned off is the user's own doing, and
549
+ // under another release's record nothing new is judged
550
+ if (!frozenByHome) {
551
+ for (const [m, u] of av.unavailable) {
552
+ if (u.kind === 'off' || loaded.has(m) || notesSaid.has(u.line) || (u.kind === 'withdrawn' && withdrawnTold.has(m))) continue;
553
+ notesSaid.add(u.line);
554
+ if (u.kind === 'withdrawn') withdrawnTold.add(m);
555
+ history({module: m, change: 'not loaded', notice: u.line, problem: u.reason});
556
+ tell(u.line, {about: short(m)});
557
+ }
558
+ }
559
+ const target = new Map(load.map((u) => [u.name, u]));
560
+ // the unloads: each loaded top-level module no longer wanted, its reason
561
+ // the notice (section 9.8); under another release's record only those no
562
+ // pins decide (turned off, removed, the ceiling, the credential), and
563
+ // what the record withdrew or moved back, with the modules that call it
564
+ // (under a home upgraded or rolled back under this process)
565
+ const inPacks = (m) => entryOf(record, m) != null;
566
+ const inRecord = (m) => inPacks(m) || (ownRecord != null && holds(ownRecord.modules, m));
567
+ const packOf = (m) => Object.keys(record.packs || {}).find((n) => record.packs[n] != null && holds(record.packs[n].modules, m)) || null;
568
+ const withdrawnNow = new Set(frozenByHome && Array.isArray(record.withdrawn) ? record.withdrawn : []);
569
+ for (const name of [...loaded.keys()]) {
570
+ if (target.has(name) && !frozenByHome) continue;
571
+ const mods = Object.keys(loaded.get(name).modules || {});
572
+ if (frozenByHome) {
573
+ // what the release just installed (or the rollback just made)
574
+ // withdrew, or moved back (the medium review of the refinement, 9)
575
+ const cause = whose.how === 'rolled back' ? 'the rollback just made' : 'the release just installed';
576
+ const w = mods.find((m) => withdrawnNow.has(m));
577
+ const low = w == null ? mods.find((m) => inPacks(m) && compareVersions(loaded.get(name).modules[m], record.modules[m].version) === 1) : null;
578
+ const by = name === (w || low) ? '' : `; ${short(name)} calls it and is stopped with it`;
579
+ if (w != null) {
580
+ // as any withdrawn unload: retried, "restart now" if refused twice,
581
+ // and told once (the high review of L2a, 2)
582
+ withdrawnTold.add(w);
583
+ await unloadWithdrawn(name, null, `module ${short(w)} was withdrawn in ${cause} and is no longer served${by}`, {about: w, release: cause});
584
+ continue;
585
+ }
586
+ if (low != null) { await send('moved back', {name}, {type: 'unload', name}, (shared ? {text: `${short(low)} was moved back to ${record.modules[low].version} by ${cause}${by}; stopped until \`${restartLine()}\` is run`, head: `${short(low)} was moved back to ${record.modules[low].version} by ${cause}${by}`} : `${short(low)} was moved back to ${record.modules[low].version} by ${cause}; it is stopped here until this client restarts${by}`)); continue; }
587
+ if (target.has(name)) continue;
588
+ }
589
+ const u = av.unavailable.get(name);
590
+ // the unload's notice tells why; its line is never told again once it
591
+ // is no longer loaded (the medium review of the high round, 2)
592
+ if (u != null) notesSaid.add(u.line);
593
+ // installed still, but no pack's top-level module any more: never
594
+ // said to be removed (the high review of L2a, 6)
595
+ const kind = !inRecord(name) ? 'removed' : u == null ? 'not top-level' : u.kind;
596
+ // (no longer a pack's top-level module is a pack removed: no pins
597
+ // decide it either; the medium review of the high round, 4; nor does a
598
+ // callee lost to one of these: the high review of its medium round, 6)
599
+ if (frozenByHome && !NO_PINS.includes(kind) && !(kind === 'calls' && u != null && NO_PINS.includes(u.root))) continue;
600
+ if (kind === 'not top-level') { await send('not top-level', {name}, {type: 'unload', name}, `${short(name)} unloaded: it is no longer a pack's top-level module`); continue; }
601
+ if (kind === 'withdrawn') { withdrawnTold.add(name); await unloadWithdrawn(name, packOf(name)); continue; }
602
+ if (kind === 'removed') { await send('removed', {name}, {type: 'unload', name}, `${short(name)} removed`); continue; }
603
+ // reason: what the runtime needs to tell every session its own text
604
+ // (#449's moduleMessages: id 9 "off", id 10 "calls" with because);
605
+ // only the reasons the vectors pin are sent. The ceiling sends none:
606
+ // the module may still be turned on, so the runtime tells this notice,
607
+ // which says why it can't simply be turned back on (the Reviewer on
608
+ // A-reason)
609
+ if (kind === 'off') { await send('turned off', {name}, {type: 'unload', name, reason: 'off'}, `${short(name)} turned off`); continue; }
610
+ if (kind === 'ceiling') { await send('turned off', {name}, {type: 'unload', name}, `${short(name)} turned off: the operator's settings don't allow it`); continue; }
611
+ // a credential's, its own or a callee's (its state's own reason:
612
+ // the /code-review medium on L5a, 5): retried and told, never left
613
+ // serving silently (the Fable pass, F4)
614
+ if (kind === 'credential' || (kind === 'calls' && u != null && u.root === 'credential')) {
615
+ const notice = `${short(name)} unloaded: ${u.reason}`;
616
+ await unloadOrTell(name, notice, 'credential', `${short(name)} could not be stopped in place after a credential was removed or changed: ${restartTo('stop it', true)}`, {sayIt: true});
617
+ continue;
618
+ }
619
+ // a caller kept from loading only by a module it calls that is turned
620
+ // off: the runtime tells its line with the way back (availability's
621
+ // becauseOff: a direct callee, the only blocker)
622
+ const why = kind === 'calls' && u != null && u.becauseOff != null ? {reason: 'calls', because: u.becauseOff} : {};
623
+ // (a callee turned off said directly, its way back at the end: the
624
+ // nested reason would not fit the notice cut with "turned off" kept --
625
+ // the closing pass's second medium)
626
+ const said = why.because != null
627
+ ? `${short(name)} unloaded: it calls ${short(why.because)}, which is turned off: \`${chLocal(where, `settings set enabled.${why.because} on`)}\``
628
+ : `${short(name)} unloaded: ${u.reason}`;
629
+ await send('not available', {name}, {type: 'unload', name, ...why}, said);
630
+ }
631
+ // a setting the runtime takes at once is sent; any other waits for the
632
+ // next start, and is said so
633
+ for (const name of LIVE) {
634
+ const was = valueOf(applied, name);
635
+ const now = valueOf(settings, name);
636
+ if (was === now) continue;
637
+ // in the runtime's unit (requestTimeout: seconds), as start passes it
638
+ const reply = await control.request({type: 'set', name, value: runtimeValue(name, now)});
639
+ // a loosening is told to the client as well (part 3, section 5); the
640
+ // history holds what was said
641
+ const loosening = loosens(name, was, now);
642
+ const notice = loosening ? loosenedText(name, was, now, reply.ok === true ? false : (reply.code || 'not applied now'))
643
+ : reply.ok === true ? `${name} set to ${shown(name, now)}` : `${name} set to ${shown(name, now)}: applies ${nextStart()} (${reply.code || 'not applied now'})`;
644
+ history({setting: name, change: 'set', notice, ...(reply.ok === true ? {} : {problem: reply.code || 'failed'})});
645
+ // (a setting applied is said; only one left for a restart needs action: N3)
646
+ if (loosening || reply.ok === true) resolvedToAct(`set:${name}`);
647
+ if (loosening) tell(notice, {fit: false}); else if (reply.ok === true) say(notice); else sayToAct(notice, `set:${name}`, name);
648
+ }
649
+ // a module's settings changed (module.*, kept names: #413 section 4.3):
650
+ // the runtime reads them again and applies each it accepts (its own
651
+ // refusal is its notice and history line); one it could not take is
652
+ // said, and applies at the next load
653
+ const moduleText = (s) => JSON.stringify(Object.entries((s && s.kept) || {}).filter(([n]) => n.startsWith('module.')).sort(([a], [b]) => (a < b ? -1 : 1)));
654
+ if (moduleText(applied) !== moduleText(settings)) {
655
+ const reply = await control.request({type: 'reread', what: 'module-settings'});
656
+ if (reply.ok !== true) {
657
+ const notice = `a module's settings changed: not applied in place (${reply.code || 'failed'}); they apply at the module's next load`;
658
+ history({setting: 'module.*', change: 'reread', notice, problem: reply.code || 'failed'});
659
+ say(notice);
660
+ }
661
+ }
662
+ for (const name of ['moduleSandbox', 'autoUpgrade']) {
663
+ const was = valueOf(applied, name);
664
+ const now = valueOf(settings, name);
665
+ if (was === now) continue;
666
+ if (loosens(name, was, now)) tell(loosenedText(name, was, now, true), {fit: false});
667
+ else sayToAct(`${name} set to ${shown(name, now)}: applies ${nextStart()}`, `set:${name}`, name);
668
+ }
669
+ applied = settings;
670
+ // The reloads in ONE request naming every loaded pack whose modules
671
+ // changed: a part two loaded packs share moves only with both named
672
+ // (countinghouse's PART_VERSION_CONFLICT; the vectors' "a reload of two
673
+ // names that share a part": #83's high review, 1). It goes before any
674
+ // new pack loads, so one that shares a part at its new version meets it
675
+ // there (the medium review of #83's fixes, 4). Packs that share a moved
676
+ // module go together or not at all: one that cannot be reloaded in
677
+ // place keeps the others of its group back too, each said (5).
678
+ const reloads = [];
679
+ const loads = [];
680
+ // an own module whose code changed (its tree; its package version may
681
+ // not), or a module that changed between own and a pack's: unloaded,
682
+ // then loaded -- the runtime's reload switches a module only when its
683
+ // version changes (B-own-add)
684
+ const swaps = [];
685
+ for (const p of load) {
686
+ const was = loaded.get(p.name);
687
+ if (was != null && sameModules(was.modules, p.modules) && (was.own === true) === (p.own === true) && addedAgain(was, p) == null) continue;
688
+ if (frozen) continue; // the next start loads it, with its release and runtime
689
+ if (was == null) { loads.push(p); continue; }
690
+ // (or one whose closure holds an own module whose code changed: an own
691
+ // caller is never left calling its callee's old code -- the
692
+ // reviewer's high on #113, 5)
693
+ if (((was.own === true || p.own === true) && ((was.own === true) !== (p.own === true) || was.modules[p.name] !== p.modules[p.name])) || ownCodeChanged(was.modules, p.modules) != null || addedAgain(was, p) != null) { swaps.push(p); continue; }
694
+ if (p.own === true) { reloads.push({p, was, how: 'updated', notice: `${p.short} updated ${shownVersion(p)}`}); continue; }
695
+ const order = compareVersions(p.version, was.version);
696
+ const how = order === 1 ? 'upgraded' : order === -1 ? 'rolled back' : 'updated';
697
+ reloads.push({p, was, how, notice: `${p.short} ${how} ${was.version} → ${p.version}`});
698
+ }
699
+ // callers out first (one no other swapped unit's closure holds), then
700
+ // back in callees first
701
+ const order = [];
702
+ for (const left = [...swaps]; left.length > 0;) {
703
+ const i = left.findIndex((p) => !left.some((q) => q !== p && Object.prototype.hasOwnProperty.call(q.modules, p.name)));
704
+ order.push(left.splice(i === -1 ? 0 : i, 1)[0]);
705
+ }
706
+ for (const p of order) {
707
+ const was = loaded.get(p.name);
708
+ const callee = was != null && was.modules[p.name] === p.modules[p.name] ? ownCodeChanged(was.modules, p.modules) : null;
709
+ const again = callee == null && was != null && was.modules[p.name] === p.modules[p.name] ? addedAgain(was, p) : null;
710
+ await send('replaced', {name: p.name}, {type: 'unload', name: p.name}, callee != null
711
+ ? `${p.short} unloaded: the code of ${short(callee)}, which it calls, changed; loading it again`
712
+ : again === p.name ? `${p.short} unloaded: you added it again; loading it again`
713
+ : again != null ? `${p.short} unloaded: ${short(again)}, which it calls, was added again; loading it again`
714
+ : `${p.short} unloaded: its code changed; loading the new code`);
715
+ }
716
+ loads.unshift(...order.slice().reverse().filter((p) => !loaded.has(p.name)));
717
+ // groups: packs joined by a module that moves in both, a module a pack
718
+ // drops included (it moves from its old version to none: the medium
719
+ // review of the Reviewer's round on #83, 1); each pack's moved set once
720
+ for (const r of reloads) r.moved = new Set([...Object.keys(r.was.modules), ...Object.keys(r.p.modules)].filter((m) => r.was.modules[m] !== r.p.modules[m]));
721
+ const group = new Map(reloads.map((r) => [r.p.name, r.p.name]));
722
+ const root = (n) => (group.get(n) === n ? n : root(group.get(n)));
723
+ for (let i = 0; i < reloads.length; i++) {
724
+ for (let j = i + 1; j < reloads.length; j++) {
725
+ if ([...reloads[j].moved].some((m) => reloads[i].moved.has(m))) group.set(root(reloads[j].p.name), root(reloads[i].p.name));
726
+ }
727
+ }
728
+ const groups = new Map();
729
+ for (const r of reloads) {
730
+ const g = root(r.p.name);
731
+ if (!groups.has(g)) groups.set(g, []);
732
+ groups.get(g).push(r);
733
+ }
734
+ // each group its own reload: all or none within a group, never across
735
+ // groups, so packs that share nothing never fail together (the
736
+ // Reviewer's check of #83's fixes, 6)
737
+ for (const list of groups.values()) await sendReload(list);
738
+ // a new pack that takes a module at another version than one still
739
+ // loaded waits: beside it, it would conflict. Checked against every
740
+ // loaded pack's versions after the reloads, which covers a held-back
741
+ // group, a refused reload and a refused unload alike (the Reviewer's
742
+ // round on #83, 6); at the same version it loads
743
+ // (module -> [{pack, version}] every loaded pack's, once, kept up to date
744
+ // as each new pack loads: the medium review of the Reviewer's round, 10;
745
+ // a module whose holders hold another version, whichever one, clashes:
746
+ // the runtime holds one version of a module, 3)
747
+ const holders = new Map();
748
+ const hold = (n, modules) => { for (const [m, ver] of Object.entries(modules || {})) { if (!holders.has(m)) holders.set(m, []); holders.get(m).push({pack: n, version: ver}); } };
749
+ for (const [n, v] of loaded) hold(n, v.modules);
750
+ const otherVersion = (m, ver) => (holders.get(m) || []).find((h) => h.version !== ver) || null;
751
+ // the module form: the scenario by its package name, each module by its
752
+ // store directory; no device config is written (--deviceConfigPath
753
+ // names the start's own empty directory: #413 rev 3, P3)
754
+ // (a pack no longer among the loads -- turned off, removed, loaded, or
755
+ // waiting under another release -- has its clash notice forgotten, so
756
+ // a later clash is said again: the medium on #106's round 1, 3)
757
+ for (const n of [...clashSaid.keys()]) if (!loads.some((p) => p.name === n)) { clashSaid.delete(n); resolvedToAct(`clash:${n}`); }
758
+ loadsSent.clear();
759
+ loadRefused.clear();
760
+ const heldAtLoad = new Map();
761
+ for (const p of loads) {
762
+ const clashes = Object.keys(p.modules).map((m) => [m, otherVersion(m, p.modules[m])]).filter(([, h]) => h != null);
763
+ if (clashes.length > 0) {
764
+ const [clash, by] = clashes[0];
765
+ // (a pack turned on may be a loosening: in shared mode no command --
766
+ // the medium on #147's last round, 1)
767
+ const problem = shared ? `${clash} ${p.modules[clash]} is kept at ${by.version} by ${short(by.pack)}; ${notApplied()}` : `it takes ${clash} ${p.modules[clash]}, which ${short(by.pack)} keeps at ${by.version} for now; ${restartBare()}`;
768
+ const notice = `${p.short} not loaded in place: ${problem}`;
769
+ // (said once per change, not on every apply: the reviewer's high on
770
+ // #106, 2)
771
+ if (clashSaid.get(p.name) !== notice) {
772
+ clashSaid.set(p.name, notice);
773
+ history({module: p.name, change: 'added', notice, problem});
774
+ sayToAct(notice, `clash:${p.name}`);
775
+ }
776
+ continue;
777
+ }
778
+ if (clashSaid.delete(p.name)) resolvedToAct(`clash:${p.name}`);
779
+ // (an own copy changed since this apply looked, the unload awaited
780
+ // meanwhile: not loaded; the next apply holds it back, and says so)
781
+ const copies = Object.keys(p.added || {}).map((m) => [m, copyState(where, m, p.modules[m])]);
782
+ const [unlike, kind] = copies.find(([m, c]) => c !== 'intact' && m === p.name) || copies.find(([, c]) => c !== 'intact') || [];
783
+ if (unlike != null) {
784
+ heldAtLoad.set(p.name, unlike === p.name ? {kind} : {kind: 'calls', root: kind, via: unlike});
785
+ state.reapply();
786
+ continue;
787
+ }
788
+ await send('added', p, withAllowance({type: 'load', name: p.name, dirs: p.dirs}, p.packages), `${p.short} added ${shownVersion(p)}`);
789
+ if (loaded.has(p.name)) hold(p.name, p.modules);
790
+ }
791
+ // own.json, applied: each entry as it ended (an own.json that could not
792
+ // be read was not applied: the last one seen stands)
793
+ if (ownRead && !closed) {
794
+ let restarted = null;
795
+ // (the next start's sandbox: a client's own option, as now, else what the
796
+ // settings name by then)
797
+ const atRestart = () => {
798
+ const sandboxOk = state.sandboxPassed === true ? state.ownSandboxOk === true
799
+ : enforceAvailable(where, io.platform || process.platform) && valueOf(settings, 'moduleSandbox') !== 'audit';
800
+ if (restarted == null) restarted = availableWith(new Map([...credentialNow].map(([m, s]) => [m, s.restart === true ? {state: 'ok', binding: {variable: null}} : s])), sandboxOk);
801
+ return restarted;
802
+ };
803
+ const stateOf = (name, e) => {
804
+ const was = loaded.get(name);
805
+ // (loaded, but added again since, and not loaded again: again)
806
+ if (was != null && was.own === true && was.version === e.tree) return was.added != null && was.added[name] !== e.addedAt ? {state: 'restart', again: true} : {state: planned.has(name) ? 'waits' : 'loaded'};
807
+ if (heldAtLoad.has(name)) return {state: 'kept', kind: heldAtLoad.get(name).kind};
808
+ const held = av.unavailable.get(name) || av.shadowed.get(name);
809
+ // (a stored key this runtime wasn't started with, its own or a
810
+ // callee's: status finds it usable, and the next start is given it --
811
+ // said so only where nothing else would keep it out of that start)
812
+ if (held != null && (held.kind === 'credential' || (held.kind === 'calls' && held.root === 'credential')) && !atRestart().unavailable.has(name)) return {state: 'restart'};
813
+ if (held != null) return {state: 'kept', ...(typeof held.kind === 'string' ? {kind: held.kind} : {})};
814
+ if (stopped.has(name)) return {state: 'kept', kind: 'stopped'};
815
+ if (loadRefused.has(name)) return {state: 'refused', code: loadRefused.get(name)};
816
+ return {state: loadUnanswered.get(name) === e.tree ? 'waits' : 'restart'};
817
+ };
818
+ ownSeen = Object.fromEntries(Object.entries(ownRecord != null ? ownRecord.modules : {}).map(([name, e]) => [name, {addedAt: e.addedAt, ...stateOf(name, e)}]));
819
+ ownAt = readAt;
820
+ writeRun();
821
+ }
822
+ // what is held back, as it ended up after the unloads and the loads,
823
+ // under another release's record or runtime too (the reviewer's high on
824
+ // #106, 4 and 9): what is wanted and not loaded, and why. (One frozen
825
+ // in place still serves: not held back.)
826
+ // - availability keeps it out: its reason;
827
+ // - the runtime stopped it: stopped, until its version changes;
828
+ // - available, but not loaded here (a clash, a refused load, another
829
+ // release's record or runtime): restart, which loads it.
830
+ for (const n of [...loadFailed]) if (!loadsSent.has(n)) loadFailed.delete(n);
831
+ const heldNow = new Map();
832
+ for (const [name, u] of av.unavailable) if (!loaded.has(name)) heldNow.set(name, u);
833
+ for (const u of av.units) {
834
+ if (loaded.has(u.name) || heldNow.has(u.name)) continue;
835
+ if (heldAtLoad.has(u.name)) { heldNow.set(u.name, heldAtLoad.get(u.name)); continue; }
836
+ // (an own module the runtime stopped: this release's runtime refuses
837
+ // it -- refused, with its code; the feature audit, F9)
838
+ if (stopped.has(u.name)) heldNow.set(u.name, stopped.get(u.name).refused === true ? {kind: 'refused', code: stopped.get(u.name).code} : {kind: 'stopped'});
839
+ else if (!loadFailed.has(u.name)) heldNow.set(u.name, {kind: 'restart'});
840
+ }
841
+ await heldBackNow(heldNow);
842
+ };
843
+ // The held-back file (lib/held-back.js; A-firstrun d1): rewritten when the
844
+ // set changes, then re-read by the runtime. A write or a reread that fails
845
+ // is said once and tried again (sendHeld); the runtime's list is empty
846
+ // after a read it could not make (#490's reread).
847
+ // (off when start passed the runtime no file: nothing would read it; the
848
+ // medium on d1, 3)
849
+ const heldOn = state.heldBack != null;
850
+ // (the text the runtime took; null once a reread reached it and failed:
851
+ // its list is empty then, #490's reread, so any text is sent again: the
852
+ // medium on round 2, 1)
853
+ let heldSent = heldOn ? state.heldBack : null;
854
+ let heldWritten = heldSent; // the text in the file now
855
+ let heldPending = null; // the text to send, not yet taken
856
+ let heldGivenUp = null; // a text not sent again until what is held back changes
857
+ let heldGen = 0; // one per pending text: a retry for an older one does nothing
858
+ let heldAttempts = 0;
859
+ let heldRetry = null;
860
+ // (the first retry's delay: 1 s; a test's io may shorten it)
861
+ const HELD_FIRST_MS = Number.isInteger(io.heldRetryMs) && io.heldRetryMs > 0 ? io.heldRetryMs : 1000;
862
+ let heldDelay = HELD_FIRST_MS;
863
+ const HELD_TRIES = 5;
864
+ const NOT_REACHED = ['CONTROL_UNKNOWN', ...NEVER_REACHED];
865
+ const clearHeldRetry = () => { if (heldRetry != null) { clearTimeout(heldRetry); heldRetry = null; } };
866
+ // The pending text written (once) and the runtime asked to read it again. A
867
+ // retry sends only this, never a whole apply (the reviewer's round 2 on
868
+ // #106, 1: an apply re-sends refused loads and re-says them). CONTROL_FAILED
869
+ // is any failed read, a passing one on Windows included (#490's reread), so
870
+ // it is tried again, 1 s doubling; but a runtime without the request, or
871
+ // one that can't use the file (no --heldBackFile, a file it judges not
872
+ // this user's), answers so for good: after HELD_TRIES, or at once on
873
+ // CONTROL_UNKNOWN, it is not sent again until the text changes, said once
874
+ // (round 2, 1 and 2). It runs only on the applier's chain, as heldBackNow
875
+ // does, so the two never interleave; gen is the pending text's own.
876
+ const sendHeld = async (gen) => {
877
+ const text = heldPending;
878
+ if (closed || text == null || gen !== heldGen) return;
879
+ heldAttempts += 1;
880
+ let problem = null;
881
+ let reached = false;
882
+ try {
883
+ if (heldWritten !== text) { heldBack.write(runDir, text); heldWritten = text; }
884
+ const reply = await control.request({type: 'reread', what: 'held-back'});
885
+ if (reply == null || reply.ok !== true) {
886
+ problem = (reply && reply.code) || 'failed';
887
+ reached = !NOT_REACHED.includes(problem);
888
+ }
889
+ } catch (e) { problem = e.code || e.message; }
890
+ if (closed) return;
891
+ if (problem == null) { heldSent = text; heldPending = null; clearHeldRetry(); return; }
892
+ if (reached) heldSent = null;
893
+ const final = problem === 'CONTROL_UNKNOWN' || heldAttempts >= HELD_TRIES;
894
+ if (final) {
895
+ heldGivenUp = text;
896
+ heldPending = null;
897
+ clearHeldRetry();
898
+ // (one line for one event: a failure final at its first try says only
899
+ // this; the medium on round 2, 10)
900
+ say(`the runtime did not take the held-back list after ${heldAttempts} ${heldAttempts === 1 ? 'try' : 'tries'} (${problem}); it is sent again when what is held back changes`);
901
+ return;
902
+ }
903
+ if (heldAttempts === 1) say(`the overview may not say which modules are held back for now (${problem}); it is tried again`);
904
+ clearHeldRetry();
905
+ heldRetry = setTimeout(() => { heldRetry = null; chain = chain.then(() => sendHeldSafe(gen), () => sendHeldSafe(gen)); }, heldDelay);
906
+ if (typeof heldRetry.unref === 'function') heldRetry.unref();
907
+ heldDelay *= 2;
908
+ };
909
+ const sendHeldSafe = (gen) => sendHeld(gen).catch(() => {});
910
+ // what is held back now -> sent if the runtime doesn't have it: a new text
911
+ // replaces any retry for an older one, armed or already queued, and starts
912
+ // its own tries from 1 s (round 2, 4; its medium, 2)
913
+ const heldBackNow = async (held) => {
914
+ if (!heldOn || closed) return;
915
+ const text = heldBack.contentOf(where, held, io.platform || process.platform);
916
+ if (text === heldPending || text === heldGivenUp) return;
917
+ if (heldPending == null && text === heldSent) return;
918
+ clearHeldRetry();
919
+ heldGen += 1;
920
+ heldPending = text;
921
+ heldGivenUp = null;
922
+ heldAttempts = 0;
923
+ heldDelay = HELD_FIRST_MS;
924
+ await sendHeld(heldGen);
925
+ };
926
+ // Ended with start (its finally): no timer left to run apply again, and
927
+ // nothing applied after (the reviewer's high on #106, 1: a daemon calls
928
+ // start again on every runtime restart, and an old applier kept running)
929
+ const close = () => {
930
+ closed = true;
931
+ for (const t of [recheck, credentialRetry, heldRetry, runRetry]) if (t != null) clearTimeout(t);
932
+ recheck = null; credentialRetry = null; heldRetry = null;
933
+ };
934
+ const safe = () => (closed ? Promise.resolve() : apply()).catch((err) => sayToAct(fitShared(`a change could not be applied in place (${require('./command-line').terminalText(err.message, 80)})`, `; ${notApplied()}`)));
935
+ let chain = Promise.resolve();
936
+ const run = () => { chain = chain.then(safe, safe); return chain; };
937
+ state.reapply = run;
938
+ // a withdrawn pack's unload: the notice rides on it, as any unload's does.
939
+ // A refusal (a runtime busy or mid-reload) is tried again 250 ms later; one
940
+ // refused twice is said once per start, "restart your client now", never
941
+ // "restart to apply"; every later apply tries again, quietly.
942
+ // about: the withdrawn module (the unloaded one, or a module it calls);
943
+ // release: the words for the release that withdrew it
944
+ // An unload that must happen (a withdrawn module, a credential removed
945
+ // or changed): retried once, and if the runtime still refuses or never
946
+ // answers, the sessions are told to restart now, once; never left serving
947
+ // silently (the Fable pass on L5a, F4).
948
+ const unloadOrTell = async (name, notice, change, stuckLine, {sayIt = false} = {}) => {
949
+ const msg = {type: 'unload', name, notice: require('./command-line').fitHeld(notice, short(name))};
950
+ for (let attempt = 0; attempt < 2; attempt++) {
951
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 250));
952
+ const reply = await control.request(msg);
953
+ if (reply.ok === true) {
954
+ loaded.delete(name);
955
+ writeRun();
956
+ history({module: name, change, notice});
957
+ // (said once it happened, never before: the medium on the high round, 1)
958
+ if (sayIt) say(notice);
959
+ if (stuck.delete(name)) tell(`module ${short(name)} is no longer served`);
960
+ return;
961
+ }
962
+ if (attempt === 1 && !stuck.has(name)) {
963
+ stuck.add(name);
964
+ history({module: name, change, notice, problem: `${reply.code || 'failed'}: ${reply.message || ''}`.slice(0, 300)});
965
+ tell(stuckLine, {about: short(name)});
966
+ }
967
+ }
968
+ };
969
+ const unloadWithdrawn = async (name, pack, notice = `module ${short(name)} was withdrawn in this release and is no longer served; ${removeHint(pack || '<pack>', where)}`, {about = name, release = 'this release'} = {}) => {
970
+ const what = about === name ? `module ${short(name)} was withdrawn in ${release}` : `module ${short(about)} was withdrawn in ${release}, and ${short(name)}, which calls it,`;
971
+ // (shared: shorter, within a notice's 200 characters with a launcher path: M3)
972
+ const stuckLine = shared
973
+ ? `${short(name)} (${about === name ? 'withdrawn' : `it calls ${short(about)}, withdrawn`}) could not be stopped here: ${restartBare()}`
974
+ : `${what} could not be stopped in place: ${restartTo('stop it', true)}`;
975
+ await unloadOrTell(name, notice, 'withdrawn', stuckLine);
976
+ };
977
+ // (M5b removed the runtime's load-pack and unload-pack asks, and M6 the
978
+ // pack form: the applier answers none of them; a module is turned on and
979
+ // off at a terminal or as a stored value, #413 section 5.3. L6)
980
+ const stuck = new Set();
981
+ // module-stopped {name, code, when}: the runtime stopped a top-level module
982
+ // for good, after unloading it itself (when: 'restart'), or refused it in
983
+ // start's own plan (when: 'start'). On the applier's chain: out of what is
984
+ // loaded and of run.json's loaded, recorded as stopped, said once to the
985
+ // sessions, and written to the history.
986
+ const moduleStopped = (msg) => {
987
+ const p = chain.then(async () => {
988
+ if (closed) return;
989
+ const name = String(msg && msg.name);
990
+ const code = msg != null && typeof msg.code === 'string' && msg.code !== '' ? msg.code : 'MODULE_STOPPED';
991
+ if (stopped.has(name)) return;
992
+ // kept out at what the runtime was asked to run (start's plan, each
993
+ // load and reload as sent); never asked, at the version the record
994
+ // names now, or the last record read when this one cannot be
995
+ const modules = asked.has(name) ? asked.get(name) : loaded.has(name) ? loaded.get(name).modules || null : null;
996
+ let version = null;
997
+ let known = modules != null;
998
+ if (modules == null) {
999
+ let r = lastRecord;
1000
+ try { r = readRecord(where); } catch (err) { /* the last one read */ }
1001
+ known = r != null;
1002
+ const e = known ? entryOf(r, name) : null;
1003
+ version = e != null ? e.version : null;
1004
+ }
1005
+ // (the user's own module, refused as it was started: this release's
1006
+ // runtime refuses it -- the feature audit, F9; a stop later, at a
1007
+ // restart, is a stop like any other's. Own by what this start loaded,
1008
+ // else by own.json; its tree, so status says it of that code only)
1009
+ const was = loaded.get(name);
1010
+ const isOwn = (was != null && was.own === true) || (() => { try { const r = readOwnRecord(where); return r != null && Object.prototype.hasOwnProperty.call(r.modules, name); } catch (e) { return false; } })();
1011
+ const refused = isOwn && msg != null && msg.when === 'start';
1012
+ const shownCode = CODE.test(code) ? code : null;
1013
+ const tree = was != null && was.own === true ? was.version : null;
1014
+ loaded.delete(name);
1015
+ stopped.set(name, {code: refused ? (shownCode || 'MODULE_STOPPED') : code, modules, version, known, refused, tree, added: was != null ? was.added : askedAdded.get(name)});
1016
+ writeRun();
1017
+ // (said as the user's own, with where to see why and how to remove it)
1018
+ // (one command, which says how to remove it too; the explanation cut
1019
+ // before it in either mode, so the command arrives whole within the
1020
+ // runtime's notice cut: the final pass on #134, M1)
1021
+ const notice = refused
1022
+ ? `${short(name)}, your own module, is not loaded: this release's runtime refuses it${shownCode != null ? ` (${shownCode})` : ''}; \`${chLocal(where, 'status')}\` says why and how to remove it`
1023
+ : `${short(name)} stopped (${code}); ${restartBare()}`;
1024
+ history({module: name, change: 'stopped', notice, when: msg != null && msg.when === 'start' ? 'start' : 'restart'});
1025
+ tell(notice, {about: short(name)});
1026
+ // (the held-back list follows: applied once more, after this; the
1027
+ // reviewer's high on #106, 4)
1028
+ if (heldOn) run();
1029
+ });
1030
+ chain = p.catch(() => {});
1031
+ return p;
1032
+ };
1033
+ return {apply: run, moduleStopped, close};
1034
+ }
1035
+
1036
+ module.exports = {inPlace, ownCodeChanged};