@rocket.chat/houston 0.27.0-next.2 → 2.1.8

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 (291) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -192
  284. package/src/bin.js +0 -4
  285. package/src/cli.ts +0 -25
  286. package/src/commands/createBranch.ts +0 -25
  287. package/src-old/logs.js +0 -323
  288. package/src-old/md.js +0 -191
  289. package/src-old/release-table.js +0 -60
  290. package/src-old/set-version.js +0 -614
  291. package/src-old/utils.js +0 -15
@@ -0,0 +1,804 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SUMMARY_SCHEMA = exports.SERVE_PID_NAME = exports.PEER_ENV = void 0;
37
+ exports.servePidPath = servePidPath;
38
+ exports.serveIsRunning = serveIsRunning;
39
+ exports.lockPaths = lockPaths;
40
+ exports.withAllStateLocks = withAllStateLocks;
41
+ exports.validateHome = validateHome;
42
+ exports.peerValidate = peerValidate;
43
+ exports.differences = differences;
44
+ exports.promote = promote;
45
+ exports.adoptRetiredHome = adoptRetiredHome;
46
+ exports.recover = recover;
47
+ /**
48
+ * Promote an exclusively-owned home to `dual-v1`, or refuse and leave it alone.
49
+ *
50
+ * One side of a two-sided protocol; the other is the previous implementation's. The
51
+ * operation's whole purpose is that EITHER implementation can perform it and each refuses
52
+ * while the other is performing it. A protocol only one side implements is not a protocol.
53
+ *
54
+ * `IMPLEMENTATION` holds the marker value earlier releases write or `typescript`, and each
55
+ * build refuses a home the other owns. `dual-v1` is the third value and it means something
56
+ * specific -- **every state format in this home has been read by both builds and they
57
+ * agreed**. It is the recorded result of a check, and this module is the check.
58
+ *
59
+ * **Why it is a migration, not an assignment.** Between "the formats validate" and "the
60
+ * marker says dual-v1" there is a window, and a kill inside it must not leave a home
61
+ * nobody can classify. So the operation writes `IMPLEMENTATION.transition` FIRST and
62
+ * removes it LAST, every command in both builds refuses while it exists
63
+ * (`lock.transitionReason`), and the three reachable end states are all explainable:
64
+ *
65
+ * journal + exclusive marker -> interrupted before the swap; recover() re-validates
66
+ * journal + dual-v1 -> the swap landed, the cleanup did not; recover() tidies
67
+ * no journal -> nothing in flight, whatever the marker says
68
+ *
69
+ * **How quiescence is established**, in this order and for this reason:
70
+ *
71
+ * 1. the journal appears, so no command that STARTS from now on will do anything;
72
+ * 2. `serve` is asked for -- a live GUI has work the locks do not represent, and its
73
+ * in-memory caches would outlive the marker it was started under;
74
+ * 3. all five state locks are taken, in the fixed order `lock.LOCK_ORDER` names, so
75
+ * anything already in flight has finished.
76
+ *
77
+ * (1) closes the future and (3) closes the past. Neither alone is quiescence.
78
+ *
79
+ * **Both readers, really both.** `validateHome()` reads every format with THIS build's
80
+ * real readers. The peer build's answer comes from the command named by
81
+ * `HOUSTON_PEER_VALIDATOR`. With no peer configured there is no second reader and
82
+ * promotion REFUSES -- a marker that says two builds agreed must never be written on the
83
+ * strength of one.
84
+ */
85
+ const fs = __importStar(require("fs"));
86
+ const path = __importStar(require("path"));
87
+ const paths_1 = require("./edge/paths");
88
+ const errors_1 = require("../lib/errors");
89
+ const events_1 = require("../lib/events");
90
+ const home_1 = require("../lib/home");
91
+ const lock = __importStar(require("../lib/lock"));
92
+ const lock_1 = require("../seams/fs/lock");
93
+ /**
94
+ * The command that validates a home with the OTHER build. It receives the home as its
95
+ * last argument and must print one JSON document of the shape `validateHome` returns.
96
+ */
97
+ exports.PEER_ENV = 'HOUSTON_PEER_VALIDATOR';
98
+ /** Written by `serve` while it runs, so promotion can tell a live GUI from a stale file. */
99
+ exports.SERVE_PID_NAME = 'serve.pid';
100
+ /**
101
+ * The document version. A peer that answers a different one has not been taught this
102
+ * protocol, and disagreeing about the QUESTION is not the same as disagreeing about the
103
+ * answer -- so it is reported as a refusal rather than as a format mismatch.
104
+ */
105
+ exports.SUMMARY_SCHEMA = 'houston.state.validation.v1';
106
+ /**
107
+ * `SERVE_PID_NAME` under the home. Every path in this module is joined onto the home
108
+ * component by component, a `..` kept as written (`joinPath`), because `path.join` folds
109
+ * a `..` in the home that the kernel -- and so the previous implementation -- resolves
110
+ * through a symlink: an earlier version validated a different directory from the one the
111
+ * previous implementation validates.
112
+ */
113
+ function servePidPath(home) {
114
+ return (0, home_1.joinPath)(home, exports.SERVE_PID_NAME);
115
+ }
116
+ /**
117
+ * The pid of a live `serve` against this home, or null.
118
+ *
119
+ * A STALE file is not a live server: `serve` removes it on a clean exit and a kill -9
120
+ * leaves it behind. `process.kill(pid, 0)` asks the kernel instead of trusting the file,
121
+ * so a crashed GUI from last week does not block a promotion forever.
122
+ */
123
+ function serveIsRunning(home) {
124
+ let raw;
125
+ try {
126
+ raw = fs.readFileSync(servePidPath(home), 'utf8').trim();
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ // `toInt`'s question, not `parseInt`'s: a trailing-garbage pid is not a pid.
132
+ if (!/^\d+$/u.test(raw))
133
+ return null;
134
+ const pid = Number(raw);
135
+ if (!Number.isInteger(pid) || pid <= 0)
136
+ return null;
137
+ try {
138
+ process.kill(pid, 0);
139
+ }
140
+ catch (error) {
141
+ const code = error.code;
142
+ // EPERM is alive and owned by somebody else, which is still alive.
143
+ if (code === 'EPERM')
144
+ return pid;
145
+ return null;
146
+ }
147
+ return pid;
148
+ }
149
+ // ------------------------------------------------------------------- the five locks
150
+ /**
151
+ * Every per-workspace runner lock, in sorted name order.
152
+ *
153
+ * The runner's lock is per repro, so "all five" expands here. Sorted, because the ORDER
154
+ * is the deadlock-avoidance property and sorting is the one ordering both builds reach
155
+ * without sharing a data structure.
156
+ */
157
+ function workspaceLockNames(home) {
158
+ const repros = (0, home_1.joinPath)(home, 'repros');
159
+ let entries;
160
+ try {
161
+ entries = fs.readdirSync(repros, { withFileTypes: true });
162
+ }
163
+ catch {
164
+ return [];
165
+ }
166
+ return entries
167
+ .filter((entry) => entry.isDirectory())
168
+ .map((entry) => entry.name)
169
+ .sort()
170
+ .map((name) => `locks/${name}.lock`);
171
+ }
172
+ /**
173
+ * The established state locks, expanded in order, followed by the shared edge lock.
174
+ *
175
+ * Relative to the home so the two implementations' answers can be compared as strings:
176
+ * "the same order" is only checkable if each can say what its order IS.
177
+ */
178
+ function lockPaths(home) {
179
+ const out = [];
180
+ for (const entry of lock.LOCK_ORDER) {
181
+ if (entry === 'locks/<workspace>.lock')
182
+ out.push(...workspaceLockNames(home));
183
+ else
184
+ out.push(entry);
185
+ }
186
+ // Shared edge mutations run after their caller's workspace lock. Promotion must
187
+ // wait for edge-only operations too, without changing the established peer order.
188
+ out.push(`locks/${paths_1.PROJECT}.lock`);
189
+ return out;
190
+ }
191
+ /**
192
+ * Hold the established state locks and then the shared edge lock, released in reverse.
193
+ *
194
+ * Recursive rather than a loop, because `withFileLock` is scoped: each lock has to stay
195
+ * held for the duration of the next one's acquisition and of the body, and unwinding has
196
+ * to happen in reverse whether the body returned or threw. A loop would need the release
197
+ * callbacks stored and replayed by hand, which is where the unwinding order goes wrong.
198
+ */
199
+ async function withAllStateLocks(home, body, timeoutMs = 30000) {
200
+ const wanted = lockPaths(home);
201
+ const held = [];
202
+ const take = async (index) => {
203
+ if (index >= wanted.length)
204
+ return body(held);
205
+ const relative = wanted[index];
206
+ const target = (0, home_1.joinPath)(home, relative);
207
+ fs.mkdirSync(path.dirname(target), { recursive: true });
208
+ if (!fs.existsSync(target))
209
+ fs.closeSync(fs.openSync(target, 'a', 0o600));
210
+ try {
211
+ return await (0, lock_1.withFileLock)(target, async () => {
212
+ held.push(relative);
213
+ return take(index + 1);
214
+ }, { timeoutMs });
215
+ }
216
+ catch (error) {
217
+ if (error instanceof errors_1.ConflictError || error instanceof errors_1.ValidationError)
218
+ throw error;
219
+ throw new errors_1.ConflictError(`another houston process is still holding ${relative} ` +
220
+ `(waited ${String(Math.round(timeoutMs / 1000))}s). Promotion needs this home ` +
221
+ 'quiet: stop any running command or `houston serve`, then retry.');
222
+ }
223
+ };
224
+ return take(0);
225
+ }
226
+ /**
227
+ * Read every state format in this home with THIS build's real readers.
228
+ *
229
+ * Deliberately made of what each READER answers rather than of file bytes: two builds
230
+ * agreeing about bytes they both misread is not the property `dual-v1` claims.
231
+ *
232
+ * A format that is ABSENT is reported as absent, never as a default. That distinction is
233
+ * what `repro.json` is built on -- an absent `extra.runtime` means docker -- and a
234
+ * validator that filled it in would be asserting the very thing it is meant to check.
235
+ */
236
+ async function validateHome(home) {
237
+ // CALL-TIME requires: `config.home()` is read when these modules load, and this function
238
+ // is handed a home that is not necessarily the ambient one.
239
+ const previous = process.env.HOUSTON_HOME;
240
+ process.env.HOUSTON_HOME = home;
241
+ try {
242
+ const config = require('../lib/config');
243
+ const users = require('./users');
244
+ const sessions = require('./sessions');
245
+ const audit = require('./audit');
246
+ const record = require('./runner/record');
247
+ const backup = require('./backup');
248
+ const journal = require('./journal');
249
+ const formats = {};
250
+ const cfg = config.loadConfig(false);
251
+ formats.config = {
252
+ present: fs.existsSync((0, home_1.joinPath)(home, 'config.yaml')),
253
+ keys: Object.keys(cfg).sort(),
254
+ values: Object.fromEntries(Object.keys(cfg)
255
+ .sort()
256
+ .map((key) => [key, canonical(cfg[key])])),
257
+ };
258
+ const accounts = users.listUsers();
259
+ formats.users = {
260
+ present: fs.existsSync(users.usersFile()),
261
+ names: accounts.map((row) => row.name).sort(),
262
+ // The role, NOT the hash. A validation document is written to a journal and
263
+ // printed by a peer process; the question here is whether both builds read the
264
+ // same accounts, not whether a password verifies.
265
+ roles: Object.fromEntries(accounts.map((row) => [row.name, row.role])),
266
+ created: Object.fromEntries(accounts.map((row) => [row.name, row.createdAt])),
267
+ };
268
+ formats.sessions = {
269
+ present: fs.existsSync(sessions.sessionsFile()),
270
+ sids: sessionSids(sessions),
271
+ };
272
+ const page = audit.read({ limit: 100000 });
273
+ formats.audit = {
274
+ present: fs.existsSync(audit.auditPath()),
275
+ records: page.lines.map((row) => [row.actor, row.kind, row.label, row.origin, row.outcome]),
276
+ };
277
+ formats.workspaces = await workspaces(home, record);
278
+ formats.backups = await backups(backup);
279
+ formats.journal = journalEntries(journal);
280
+ formats.eventlog = eventlogState(home);
281
+ // The rest of the table. Read as DIRECTORY CONTENTS and the few decoded fields a
282
+ // reader branches on, rather than as bytes: a certificate and a CA key are random by
283
+ // construction, and what the two builds have to agree about is which files are there
284
+ // and what the JSON beside them says.
285
+ formats.firstrun = firstrunState();
286
+ formats.edge = edgeState(home);
287
+ formats.acme = acmeState();
288
+ formats.ca = caState();
289
+ formats.clusters = clustersState(home);
290
+ formats.presets = presetsState(config);
291
+ return { schema: exports.SUMMARY_SCHEMA, build: lock.THIS_IMPLEMENTATION, formats };
292
+ }
293
+ finally {
294
+ if (previous === undefined)
295
+ delete process.env.HOUSTON_HOME;
296
+ else
297
+ process.env.HOUSTON_HOME = previous;
298
+ }
299
+ }
300
+ function sessionSids(sessions) {
301
+ let text;
302
+ try {
303
+ text = fs.readFileSync(sessions.sessionsFile(), 'utf8');
304
+ }
305
+ catch {
306
+ return [];
307
+ }
308
+ const out = [];
309
+ for (const line of text.split('\n')) {
310
+ // The module's own line parser, not a second one written here.
311
+ const parsed = sessions.parse(line);
312
+ if (parsed !== null)
313
+ out.push(parsed.sid);
314
+ }
315
+ return out.sort();
316
+ }
317
+ async function workspaces(home, record) {
318
+ const out = {};
319
+ let names;
320
+ try {
321
+ names = fs
322
+ .readdirSync((0, home_1.joinPath)(home, 'repros'), { withFileTypes: true })
323
+ .filter((entry) => entry.isDirectory())
324
+ .map((entry) => entry.name)
325
+ .sort();
326
+ }
327
+ catch {
328
+ return out;
329
+ }
330
+ for (const name of names) {
331
+ let meta;
332
+ try {
333
+ meta = await record.readMeta(name);
334
+ }
335
+ catch (error) {
336
+ out[name] = { error: error.constructor.name };
337
+ continue;
338
+ }
339
+ const extra = meta.extra;
340
+ const env = extra.env;
341
+ const isEnv = env !== null && typeof env === 'object' && !Array.isArray(env);
342
+ out[name] = {
343
+ // KEY PRESENCE, separately from the values: an absent `extra.runtime` means docker
344
+ // and an absent `extra.last_upgrade_backup` means nothing to restore, so a build
345
+ // that materialised either would differ HERE even though every resolved value
346
+ // still matched.
347
+ extraKeys: Object.keys(extra).sort(),
348
+ adminPass: record.adminPass(meta),
349
+ rcVersion: meta.rcVersion,
350
+ hostPort: meta.hostPort,
351
+ envKeys: isEnv ? Object.keys(env).sort() : null,
352
+ envNullKeys: isEnv
353
+ ? Object.keys(env)
354
+ .filter((key) => env[key] === null)
355
+ .sort()
356
+ : null,
357
+ };
358
+ }
359
+ return out;
360
+ }
361
+ async function backups(backup) {
362
+ try {
363
+ const rows = await backup.listBackups();
364
+ return {
365
+ bundles: rows
366
+ .map((row) => [path.basename(String(row.path)), row.repro ?? '', row.error ?? ''])
367
+ .sort((a, b) => (JSON.stringify(a) < JSON.stringify(b) ? -1 : 1)),
368
+ };
369
+ }
370
+ catch (error) {
371
+ return { error: error.constructor.name };
372
+ }
373
+ }
374
+ function journalEntries(journal) {
375
+ try {
376
+ return {
377
+ entries: journal
378
+ .openEntries()
379
+ .map((entry) => [entry.kind, entry.workspace])
380
+ .sort((a, b) => (JSON.stringify(a) < JSON.stringify(b) ? -1 : 1)),
381
+ };
382
+ }
383
+ catch (error) {
384
+ return { error: error.constructor.name };
385
+ }
386
+ }
387
+ function eventlogState(home) {
388
+ const directory = (0, home_1.joinPath)(home, 'logs');
389
+ let names;
390
+ try {
391
+ names = fs
392
+ .readdirSync(directory)
393
+ .filter((name) => name.startsWith('houston.log'))
394
+ .sort();
395
+ }
396
+ catch {
397
+ return { files: [], records: 0 };
398
+ }
399
+ let records = 0;
400
+ for (const name of names) {
401
+ try {
402
+ for (const line of fs.readFileSync((0, home_1.joinPath)(directory, name), 'utf8').split('\n')) {
403
+ if (line.trim() !== '')
404
+ records += 1;
405
+ }
406
+ }
407
+ catch {
408
+ continue;
409
+ }
410
+ }
411
+ return { files: names, records };
412
+ }
413
+ /**
414
+ * Presence and SHAPE only. The file holds a one-shot credential's digest, and a
415
+ * validation document is written to a journal and printed by a peer process.
416
+ */
417
+ function firstrunState() {
418
+ const firstrun = require('./firstrun');
419
+ const target = firstrun.keyPath();
420
+ if (!fs.existsSync(target))
421
+ return { present: false };
422
+ const lines = fs.readFileSync(target, 'utf8').split('\n');
423
+ return {
424
+ present: true,
425
+ headers: lines.filter((line) => line.startsWith('#')),
426
+ rows: lines.filter((line) => line !== '' && !line.startsWith('#')).length,
427
+ mode: fs.statSync(target).mode & 0o777,
428
+ };
429
+ }
430
+ function edgeState(home) {
431
+ const spec = require('./edge/spec');
432
+ let routes;
433
+ try {
434
+ routes = fs.readdirSync((0, home_1.joinPath)(home, 'edge', 'routes')).sort();
435
+ }
436
+ catch {
437
+ routes = [];
438
+ }
439
+ return { domain: spec.servedDomain(), configured: spec.current() !== null, routes };
440
+ }
441
+ function acmeState() {
442
+ const tls = require('./tls');
443
+ const issued = (0, home_1.joinPath)(tls.acmeDir(), 'issued.json');
444
+ if (!fs.existsSync(issued))
445
+ return { present: false };
446
+ try {
447
+ const data = JSON.parse(fs.readFileSync(issued, 'utf8'));
448
+ const isObject = data !== null && typeof data === 'object' && !Array.isArray(data);
449
+ return { present: true, hosts: isObject ? Object.keys(data).sort() : null };
450
+ }
451
+ catch {
452
+ return { present: true, malformed: true };
453
+ }
454
+ }
455
+ /**
456
+ * File names and modes. The PEM BYTES are openssl's and random by construction -- what
457
+ * another build reads is whether the CA is there and usable.
458
+ */
459
+ function caState() {
460
+ const tls = require('./tls');
461
+ const directory = tls.caDir();
462
+ let names;
463
+ try {
464
+ names = fs.readdirSync(directory).sort();
465
+ }
466
+ catch {
467
+ return { present: false, files: [] };
468
+ }
469
+ return {
470
+ present: true,
471
+ files: names.map((name) => [name, fs.statSync((0, home_1.joinPath)(directory, name)).mode & 0o777]),
472
+ };
473
+ }
474
+ function clustersState(home) {
475
+ try {
476
+ return { names: fs.readdirSync((0, home_1.joinPath)(home, 'clusters')).sort() };
477
+ }
478
+ catch {
479
+ return { names: [] };
480
+ }
481
+ }
482
+ /**
483
+ * USER-AUTHORED preset files. Neither build writes these; both read them, and a
484
+ * disagreement about which exist is a disagreement about what `up --preset` can do.
485
+ */
486
+ function presetsState(config) {
487
+ try {
488
+ return { names: fs.readdirSync(config.presetDir()).sort() };
489
+ }
490
+ catch {
491
+ return { names: [] };
492
+ }
493
+ }
494
+ /** The wire shape the two builds compare. */
495
+ function canonical(value) {
496
+ if (value === null || value === undefined)
497
+ return null;
498
+ const type = typeof value;
499
+ if (type === 'boolean' || type === 'string')
500
+ return value;
501
+ if (type === 'number') {
502
+ const held = value;
503
+ if (Number.isNaN(held))
504
+ return { $float: 'nan' };
505
+ if (held === Infinity)
506
+ return { $float: 'inf' };
507
+ if (held === -Infinity)
508
+ return { $float: '-inf' };
509
+ return held;
510
+ }
511
+ if (Array.isArray(value))
512
+ return value.map(canonical);
513
+ if (value instanceof Date)
514
+ return { $datetime: value.toISOString() };
515
+ if (type === 'object') {
516
+ const out = {};
517
+ for (const key of Object.keys(value).sort()) {
518
+ out[key] = canonical(value[key]);
519
+ }
520
+ return out;
521
+ }
522
+ return String(value);
523
+ }
524
+ /**
525
+ * What the OTHER build makes of this home.
526
+ *
527
+ * Through the exec seam, because that is the only module allowed to spawn anything: the
528
+ * seam owns quoting, the timeout and the error typing, and a second subprocess site here
529
+ * would be a fourth place to get those subtly different.
530
+ */
531
+ async function peerValidate(home) {
532
+ const command = (process.env[exports.PEER_ENV] ?? '').trim();
533
+ if (command === '') {
534
+ throw new errors_1.ValidationError(`${exports.PEER_ENV} is not set, so there is no second reader and nothing to validate ` +
535
+ `against. A '${lock.DUAL_IMPLEMENTATION}' marker says both builds have read ` +
536
+ 'every format in this home and agreed; it must not be written on one build’s ' +
537
+ 'word. Set it to the command that validates a home with the other build.');
538
+ }
539
+ const exec = require('../seams/exec');
540
+ const parts = splitCommand(command);
541
+ if (parts.length === 0) {
542
+ throw new errors_1.ValidationError(`${exports.PEER_ENV} is set but holds no command.`);
543
+ }
544
+ const argv = [parts[0], ...parts.slice(1), home];
545
+ const result = await exec.capture(argv, { timeoutMs: 300000, encoding: 'utf8' });
546
+ if (result.exitCode !== 0) {
547
+ throw new errors_1.ValidationError(`the peer validator (${command}) exited ${String(result.exitCode)} and this home ` +
548
+ `cannot be promoted until it succeeds: ${String(result.stderr ?? '')
549
+ .trim()
550
+ .slice(0, 400)}`);
551
+ }
552
+ let loaded;
553
+ try {
554
+ loaded = JSON.parse(String(result.stdout ?? ''));
555
+ }
556
+ catch (error) {
557
+ throw new errors_1.ValidationError(`the peer validator (${command}) did not print one JSON document: ${String(error)}`);
558
+ }
559
+ const record = loaded;
560
+ if (record !== null && typeof record === 'object' && record.build === lock.THIS_IMPLEMENTATION) {
561
+ throw new errors_1.ValidationError(`the peer validator (${command}) is the '${lock.THIS_IMPLEMENTATION}' build, which ` +
562
+ `is this build. A '${lock.DUAL_IMPLEMENTATION}' marker says TWO implementations ` +
563
+ 'read this home and agreed; one build agreeing with itself is not that, and it ' +
564
+ `would agree whatever either of them got wrong. Point ${exports.PEER_ENV} at the other build.`);
565
+ }
566
+ if (record === null || typeof record !== 'object' || record.schema !== exports.SUMMARY_SCHEMA) {
567
+ throw new errors_1.ValidationError(`the peer validator answered schema ${JSON.stringify(record?.schema ?? null)}, this ` +
568
+ `build speaks ${JSON.stringify(exports.SUMMARY_SCHEMA)}. The two builds disagree about ` +
569
+ 'the QUESTION, which is not something a state comparison can resolve.');
570
+ }
571
+ return loaded;
572
+ }
573
+ /** `shlex.split` for the shapes a validator command actually takes. */
574
+ function splitCommand(command) {
575
+ const out = [];
576
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/gu;
577
+ let match;
578
+ while ((match = pattern.exec(command)) !== null) {
579
+ out.push(match[1] ?? match[2] ?? match[3] ?? '');
580
+ }
581
+ return out;
582
+ }
583
+ /** Every path at which the two validation documents disagree. */
584
+ function differences(ours, theirs) {
585
+ const out = [];
586
+ const walk = (left, right, at) => {
587
+ if (JSON.stringify(left) === JSON.stringify(right))
588
+ return;
589
+ if (left !== null &&
590
+ right !== null &&
591
+ typeof left === 'object' &&
592
+ typeof right === 'object' &&
593
+ !Array.isArray(left) &&
594
+ !Array.isArray(right)) {
595
+ const keys = [
596
+ ...new Set([
597
+ ...Object.keys(left),
598
+ ...Object.keys(right),
599
+ ]),
600
+ ].sort();
601
+ for (const key of keys) {
602
+ walk(left[key], right[key], `${at}.${key}`);
603
+ }
604
+ return;
605
+ }
606
+ out.push(at === '' ? '$' : at);
607
+ };
608
+ walk(ours.formats, theirs.formats, '');
609
+ return out;
610
+ }
611
+ /**
612
+ * Promote this home to `dual-v1`, or refuse and leave it exactly as it was.
613
+ *
614
+ * The order is the contract and every step is here in it. The journal is removed on
615
+ * EVERY failure path, because a refusal that left it behind would lock the operator out
616
+ * of their own home for a reason that no longer applies.
617
+ */
618
+ async function promote(home, { emit = events_1.nullEmit, timeoutMs = 30000, peer = 'required', } = {}) {
619
+ const found = lock.readImplementation(home);
620
+ if (found === lock.DUAL_IMPLEMENTATION) {
621
+ emit((0, events_1.event)(`${home} is already ${lock.DUAL_IMPLEMENTATION}`, { phase: 'preflight', pct: 100 }));
622
+ return { marker: found, promoted: false, reason: 'already-dual' };
623
+ }
624
+ if (found === null) {
625
+ throw new errors_1.ValidationError(`${lock.markerPath(home)} names no owner, so there is nothing to promote. Run a ` +
626
+ 'command against this home first, or check HOUSTON_HOME.');
627
+ }
628
+ if (found !== lock.THIS_IMPLEMENTATION && found !== 'python') {
629
+ throw new errors_1.ValidationError(`${lock.markerPath(home)} says '${found}', which is not a marker this build ` +
630
+ 'understands. Refusing rather than rewriting it: an unrecognised marker is ' +
631
+ 'evidence, and promotion is not a repair tool.');
632
+ }
633
+ // 1. THE JOURNAL FIRST, and the exclusive marker untouched. From this instant every
634
+ // command in both builds refuses, so nothing new can start writing.
635
+ const record = {
636
+ schema: exports.SUMMARY_SCHEMA,
637
+ from: found,
638
+ to: lock.DUAL_IMPLEMENTATION,
639
+ started_by: `${lock.THIS_IMPLEMENTATION}:${String(process.pid)}`,
640
+ started_at: new Date().toISOString().replace(/\.\d{3}Z$/u, 'Z'),
641
+ };
642
+ if (!lock.beginTransition(home, record)) {
643
+ throw new errors_1.ConflictError(lock.transitionReason(home) ?? `${lock.transitionPath(home)} already exists`);
644
+ }
645
+ emit((0, events_1.event)('transition journal written', { phase: 'preflight', pct: 10 }));
646
+ try {
647
+ return await runPromotion(home, found, emit, timeoutMs, peer);
648
+ }
649
+ catch (error) {
650
+ // EVERY failure path: the journal is removed and the original marker is still
651
+ // whatever it was. A refusal must leave the home usable, and the marker is
652
+ // deliberately not touched before this point.
653
+ lock.clearTransition(home);
654
+ throw error;
655
+ }
656
+ }
657
+ async function runPromotion(home, found, emit, timeoutMs, peer) {
658
+ // 2. No live `serve`. Its jobs are work the locks do not represent, and its caches
659
+ // would outlive the marker it was started under.
660
+ const pid = serveIsRunning(home);
661
+ if (pid !== null) {
662
+ throw new errors_1.ConflictError(`\`houston serve\` is running against this home (pid ${String(pid)}). Promotion ` +
663
+ 'needs the home quiet, and a live GUI holds state in memory that would outlive ' +
664
+ 'the marker it started under. Stop it, then retry.');
665
+ }
666
+ emit((0, events_1.event)('no serve running', { phase: 'preflight', pct: 20 }));
667
+ await withAllStateLocks(home, async (held) => {
668
+ // 3. All five, in the fixed order. Anything already in flight has now finished.
669
+ emit((0, events_1.event)(`holding ${String(held.length)} state locks`, { phase: 'preflight', pct: 40 }));
670
+ // 4. Both readers, under those locks, on a home nothing else can move. Only this
671
+ // build ships, so for the marker window an adoption asks a peer only when one is
672
+ // configured: this build's reading of every format, under every lock, is the
673
+ // validation a home the previous implementation left gets.
674
+ const ours = await validateHome(home);
675
+ emit((0, events_1.event)('this build read every format', { phase: 'plan', pct: 60 }));
676
+ if (peer === 'optional' && (process.env[exports.PEER_ENV] ?? '').trim() === '') {
677
+ emit((0, events_1.event)('no peer configured: the other build is retired, this reading stands', {
678
+ phase: 'plan',
679
+ pct: 85,
680
+ }));
681
+ }
682
+ else {
683
+ const theirs = await peerValidate(home);
684
+ emit((0, events_1.event)('the peer build read every format', { phase: 'plan', pct: 75 }));
685
+ const diverged = differences(ours, theirs);
686
+ if (diverged.length > 0) {
687
+ const extra = diverged.length <= 12 ? '' : ` (and ${String(diverged.length - 12)} more)`;
688
+ throw new errors_1.ValidationError('the two builds do not agree about this home, so it cannot become ' +
689
+ `'${lock.DUAL_IMPLEMENTATION}'. They differ at: ${diverged.slice(0, 12).join(', ')}${extra}.`);
690
+ }
691
+ emit((0, events_1.event)('both builds agree about every format', { phase: 'plan', pct: 85 }));
692
+ }
693
+ // 5. Only now. Atomic replace, then fsync the DIRECTORY so the entry survives a
694
+ // power loss and not just the contents.
695
+ lock.writeMarker(home, lock.DUAL_IMPLEMENTATION);
696
+ emit((0, events_1.event)(`marker is now ${lock.DUAL_IMPLEMENTATION}`, { phase: 'config', pct: 95 }));
697
+ }, timeoutMs);
698
+ // 6. The journal goes LAST, outside the locks: a kill between the swap and here leaves
699
+ // `dual-v1` plus a journal, which recovery recognises and tidies.
700
+ lock.clearTransition(home);
701
+ emit((0, events_1.event)(`${home} is now ${lock.DUAL_IMPLEMENTATION}`, {
702
+ phase: 'done',
703
+ pct: 100,
704
+ terminal: true,
705
+ }));
706
+ return {
707
+ marker: lock.DUAL_IMPLEMENTATION,
708
+ promoted: true,
709
+ from: found,
710
+ locks: lockPaths(home),
711
+ };
712
+ }
713
+ /**
714
+ * THE MARKER WINDOW (kept while 1.x installs are supported). A home whose marker is the exclusive
715
+ * value earlier releases write -- an install of an earlier release -- is not refused and
716
+ * not simply relabelled: it goes through the promotion above, every state format read back
717
+ * by this build under all five locks, the marker swapped atomically, the journal cleared
718
+ * last, and the caller told once. A peer is asked only when `HOUSTON_PEER_VALIDATOR` names
719
+ * one (a checkout with the previous implementation installed). Any other marker is left to
720
+ * `requireThisImplementation`: `dual-v1` and this build's own are used as they are, a
721
+ * transition journal and an unknown build stay refused. On any failure the marker is still
722
+ * the earlier releases' value and the journal is gone, so the home is exactly as it was.
723
+ *
724
+ * Returns the one-time notice to show, or null when there was nothing to adopt.
725
+ */
726
+ async function adoptRetiredHome(home, emit = events_1.nullEmit) {
727
+ const inFlight = lock.transitionReason(home);
728
+ if (inFlight)
729
+ throw new errors_1.PreflightError(inFlight);
730
+ if (lock.readImplementation(home) !== 'python')
731
+ return null;
732
+ const peer = (process.env[exports.PEER_ENV] ?? '').trim() === '' ? 'optional' : 'required';
733
+ await promote(home, { emit, peer });
734
+ return (`note: ${home} was last written by houston 1.x. Every state ` +
735
+ `file in it read back, and it is marked '${lock.DUAL_IMPLEMENTATION}' now: this build ` +
736
+ 'carries on with it, and nothing else in it changed.');
737
+ }
738
+ /** Whether `target` is a directory: follows a symlink, false for anything not stat'able. */
739
+ function isDirectory(target) {
740
+ try {
741
+ return fs.statSync(target).isDirectory();
742
+ }
743
+ catch {
744
+ return false;
745
+ }
746
+ }
747
+ /**
748
+ * Finish or abandon an interrupted promotion. Safe to run repeatedly.
749
+ *
750
+ * Which of the two is decided by the MARKER, because the marker is what the swap changes:
751
+ *
752
+ * - already `dual-v1` -- the swap landed and only the cleanup was lost. Remove the
753
+ * journal. Re-validating here would ask permission for something already done, and
754
+ * would fail for the ordinary reason that the other build has since written.
755
+ * - still exclusive -- the swap never happened. Re-run the WHOLE protocol under the
756
+ * same locks, because the state may have moved since the interrupted attempt read it,
757
+ * and completing on the strength of that stale read is what the journal prevents.
758
+ */
759
+ async function recover(home, { emit = events_1.nullEmit, timeoutMs = 30000 } = {}) {
760
+ const record = lock.readTransition(home);
761
+ // The two early answers carry the established three keys and no `promoted`: nothing was
762
+ // promoted by THIS call, and a key the previous implementation never writes is a
763
+ // difference in every result either build reads back.
764
+ if (record === null) {
765
+ return {
766
+ recovered: false,
767
+ reason: 'no-transition',
768
+ marker: lock.readImplementation(home),
769
+ };
770
+ }
771
+ // A DIRECTORY is no journal a promotion wrote -- `beginTransition` creates a file -- and it
772
+ // is one `clearTransition` cannot remove. Recovering on its strength would promote the home
773
+ // because of a stray directory, then leave it in place and report success while every
774
+ // command in both builds still refused.
775
+ if (isDirectory(lock.transitionPath(home))) {
776
+ throw new errors_1.ConflictError(`${lock.transitionPath(home)} is a directory, which no promotion writes. ` +
777
+ 'Recovery will not promote this home on the strength of it, and cannot remove ' +
778
+ 'it: check that no promotion is running, then remove it by hand.');
779
+ }
780
+ if (lock.readImplementation(home) === lock.DUAL_IMPLEMENTATION) {
781
+ lock.clearTransition(home);
782
+ emit((0, events_1.event)('promotion had already landed; journal cleared', {
783
+ phase: 'done',
784
+ pct: 100,
785
+ terminal: true,
786
+ }));
787
+ return {
788
+ recovered: true,
789
+ reason: 'completed-cleanup',
790
+ marker: lock.DUAL_IMPLEMENTATION,
791
+ };
792
+ }
793
+ emit((0, events_1.event)('re-validating an interrupted promotion', { phase: 'preflight', pct: 10 }));
794
+ try {
795
+ // Recovery keeps the peer requirement the interrupted attempt had: an adoption that
796
+ // was interrupted is finished by the next command's adoption, not here.
797
+ const result = await runPromotion(home, typeof record.from === 'string' ? record.from : '', emit, timeoutMs, 'required');
798
+ return { ...result, recovered: true, reason: 'revalidated' };
799
+ }
800
+ catch (error) {
801
+ lock.clearTransition(home);
802
+ throw error;
803
+ }
804
+ }