@join-pantheon/cli 0.38.1 → 0.38.3

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.
@@ -0,0 +1,314 @@
1
+ import { closeSync, constants, fstatSync, linkSync, lstatSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { posix, win32 } from "node:path";
3
+ import { managedLayout } from "./managed.js";
4
+ import { atomicWrite } from "./worker-policy.js";
5
+ export const PROBATION_FILE = "upgrade-probation.json";
6
+ export const HELD_FILE = "upgrade-held.json";
7
+ export const PROBATION_MS = 2 * 3600_000;
8
+ export const FAILS_TO_ROLL_BACK = 3;
9
+ export const STEADY_RUN_MS = 60_000;
10
+ export const CLOCK_SLACK_MS = 60_000;
11
+ export const MARK_LOCK = `${PROBATION_FILE}.lock`;
12
+ export const LOCK_STALE_MS = 10_000;
13
+ export const LOCK_WAIT_MS = 400;
14
+ export const NEVER_ONLINE_MS = 15 * 60_000;
15
+ export const NEVER_ONLINE_CHECK_MS = 60_000;
16
+ export const NEVER_ONLINE_CHECKS = 3;
17
+ const isTime = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
18
+ const pidAlive = (pid) => {
19
+ if (!(pid > 0))
20
+ return false;
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ }
25
+ catch (e) {
26
+ return e.code === "EPERM";
27
+ }
28
+ };
29
+ const pause = (ms) => { try {
30
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
31
+ }
32
+ catch { } };
33
+ const rand = () => Math.random().toString(16).slice(2, 10);
34
+ export function runtimeDir(m) {
35
+ return (/\.exe$/i.test(m.node) ? win32 : posix).dirname(m.prevDir);
36
+ }
37
+ const fileIn = (m, name) => (/\.exe$/i.test(m.node) ? win32 : posix).join(runtimeDir(m), name);
38
+ function readSmall(f) {
39
+ let fd;
40
+ try {
41
+ if (!statSync(f).isFile())
42
+ return null;
43
+ fd = openSync(f, constants.O_RDONLY | (constants.O_NONBLOCK || 0));
44
+ const st = fstatSync(fd);
45
+ if (!st.isFile() || st.size > 1_000_000)
46
+ return null;
47
+ return readFileSync(fd, "utf8").replace(/^/, "");
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ finally {
53
+ if (fd !== undefined) {
54
+ try {
55
+ closeSync(fd);
56
+ }
57
+ catch { }
58
+ }
59
+ }
60
+ }
61
+ const readJson = (f) => {
62
+ try {
63
+ const t = readSmall(f);
64
+ const v = t === null ? null : JSON.parse(t);
65
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ };
71
+ export function withMarkLock(m, fn) {
72
+ const lock = fileIn(m, MARK_LOCK);
73
+ const token = `${process.pid} ${rand()}${rand()}`;
74
+ const deadline = Date.now() + LOCK_WAIT_MS;
75
+ let mine = false;
76
+ for (;;) {
77
+ try {
78
+ writeFileSync(lock, token, { flag: "wx", mode: 0o600 });
79
+ mine = true;
80
+ break;
81
+ }
82
+ catch (e) {
83
+ const code = e.code;
84
+ if (code !== "EEXIST" && !(process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY")))
85
+ break;
86
+ }
87
+ breakStaleLock(lock);
88
+ if (Date.now() >= deadline)
89
+ break;
90
+ pause(2 + Math.floor(Math.random() * 8));
91
+ }
92
+ try {
93
+ return fn();
94
+ }
95
+ finally {
96
+ if (mine) {
97
+ try {
98
+ if (readSmall(lock) === token)
99
+ rmSync(lock, { force: true });
100
+ }
101
+ catch { }
102
+ }
103
+ }
104
+ }
105
+ function breakStaleLock(lock) {
106
+ let st;
107
+ try {
108
+ st = lstatSync(lock);
109
+ }
110
+ catch {
111
+ return;
112
+ }
113
+ const age = Math.abs(Date.now() - st.mtimeMs);
114
+ const seen = st.isFile() ? readSmall(lock) : null;
115
+ const holder = /^(\d+) /.exec(seen ?? "");
116
+ const stale = age > LOCK_STALE_MS || (holder ? !pidAlive(Number(holder[1])) && age > 50 : age > 1_000);
117
+ if (!stale)
118
+ return;
119
+ const aside = `${lock}.stale-${process.pid}-${rand()}`;
120
+ try {
121
+ renameSync(lock, aside);
122
+ }
123
+ catch {
124
+ return;
125
+ }
126
+ if (st.isFile() && readSmall(aside) !== seen) {
127
+ try {
128
+ linkSync(aside, lock);
129
+ }
130
+ catch { }
131
+ }
132
+ try {
133
+ rmSync(aside, { recursive: true, force: true });
134
+ }
135
+ catch { }
136
+ }
137
+ export function readProbation(m = managedLayout()) {
138
+ if (!m)
139
+ return null;
140
+ const p = readJson(fileIn(m, PROBATION_FILE));
141
+ if (!p || typeof p.to !== "string" || !isTime(p.at))
142
+ return null;
143
+ return p;
144
+ }
145
+ export function probationText(from, to, now) {
146
+ return JSON.stringify({ v: 1, ...(from ? { from } : {}), to, at: now, runs: [], fails: [] }, null, 2) + "\n";
147
+ }
148
+ const expired = (p, now) => now - p.at > PROBATION_MS || p.at - now > CLOCK_SLACK_MS;
149
+ export function onProbation(version, o = {}) {
150
+ const p = readProbation(o.m === undefined ? managedLayout() : o.m);
151
+ return !!p && p.to === version && !p.stuck && !expired(p, o.now ?? Date.now());
152
+ }
153
+ export function probationPassed(version, o = {}) {
154
+ const m = o.m === undefined ? managedLayout() : o.m;
155
+ if (!m)
156
+ return false;
157
+ return withMarkLock(m, () => {
158
+ const p = readProbation(m);
159
+ if (!p || p.to !== version)
160
+ return false;
161
+ try {
162
+ rmSync(fileIn(m, PROBATION_FILE), { force: true });
163
+ return true;
164
+ }
165
+ catch {
166
+ return false;
167
+ }
168
+ });
169
+ }
170
+ function changeProbation(m, version, fn) {
171
+ return withMarkLock(m, () => {
172
+ const p = readProbation(m);
173
+ if (!p || (version !== null && p.to !== version))
174
+ return false;
175
+ fn(p);
176
+ try {
177
+ atomicWrite(fileIn(m, PROBATION_FILE), JSON.stringify(p, null, 2) + "\n");
178
+ return true;
179
+ }
180
+ catch {
181
+ return false;
182
+ }
183
+ });
184
+ }
185
+ export function markNeverOnline(version, o = {}) {
186
+ const m = o.m === undefined ? managedLayout() : o.m;
187
+ if (!m)
188
+ return false;
189
+ return changeProbation(m, version, (p) => { p.never_online = o.now ?? Date.now(); });
190
+ }
191
+ export function probationStopExpected(o = {}) {
192
+ const m = o.m === undefined ? managedLayout() : o.m;
193
+ if (!m || !readProbation(m))
194
+ return;
195
+ changeProbation(m, null, (p) => { p.stop_expected_at = o.now ?? Date.now(); });
196
+ }
197
+ export function replaceProbation(m, write) {
198
+ withMarkLock(m, write);
199
+ }
200
+ export function readRolledBack(m = managedLayout()) {
201
+ if (!m)
202
+ return null;
203
+ const h = readJson(fileIn(m, HELD_FILE));
204
+ if (!h || typeof h.version !== "string" || typeof h.back_to !== "string")
205
+ return null;
206
+ return { version: h.version, back_to: h.back_to, at: isTime(h.at) ? h.at : 0, why: typeof h.why === "string" ? h.why : "", ...(isTime(h.told_at) ? { told_at: h.told_at } : {}) };
207
+ }
208
+ export function markRolledBackTold(o = {}) {
209
+ const m = o.m === undefined ? managedLayout() : o.m;
210
+ if (!m)
211
+ return false;
212
+ return withMarkLock(m, () => {
213
+ const h = readRolledBack(m);
214
+ if (!h || h.told_at)
215
+ return false;
216
+ try {
217
+ atomicWrite(fileIn(m, HELD_FILE), JSON.stringify({ v: 1, ...h, told_at: o.now ?? Date.now() }, null, 2) + "\n");
218
+ return true;
219
+ }
220
+ catch {
221
+ return false;
222
+ }
223
+ });
224
+ }
225
+ export function heldBack(pkg, o = {}) {
226
+ if (!pkg)
227
+ return null;
228
+ const h = readRolledBack(o.m === undefined ? managedLayout() : o.m);
229
+ return h && h.version === pkg ? h : null;
230
+ }
231
+ const whyWords = (h) => (h.why === "never_online" ? "could not reach your team" : "kept stopping");
232
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
233
+ export function heldWhen(h) {
234
+ if (!isTime(h.at))
235
+ return "";
236
+ const d = new Date(h.at);
237
+ return `${d.getDate()} ${MONTHS[d.getMonth()]} at ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
238
+ }
239
+ export function rolledBackSentence(h) {
240
+ return `Pantheon ${h.version} ${whyWords(h)} on this computer, so it went back to ${h.back_to} by itself. Nothing to do: it updates again when a newer release is out.`;
241
+ }
242
+ export function heldUpgradeSentence(h) {
243
+ const when = heldWhen(h);
244
+ return `Pantheon ${h.version} ${whyWords(h)} on this computer and was put back to ${h.back_to}${when ? ` on ${when}` : ""}, so it is not installed again by itself. To try it again on purpose: pantheon upgrade ${h.version}`;
245
+ }
246
+ export function watchNeverOnline(o) {
247
+ const mo = o.m === undefined ? {} : { m: o.m };
248
+ const now = o.now ?? Date.now;
249
+ if (!onProbation(o.version, { ...mo, now: now() }))
250
+ return null;
251
+ const after = o.afterMs ?? NEVER_ONLINE_MS, every = o.everyMs ?? NEVER_ONLINE_CHECK_MS, checks = o.checks ?? NEVER_ONLINE_CHECKS;
252
+ let last = now(), trying = 0, answered = 0, over = false, busy = false;
253
+ let timer = null;
254
+ const stop = () => { over = true; if (timer)
255
+ clearInterval(timer); timer = null; };
256
+ const tick = async () => {
257
+ if (over)
258
+ return "over";
259
+ if (busy)
260
+ return "watching";
261
+ busy = true;
262
+ try {
263
+ const t = now(), step = t - last;
264
+ last = t;
265
+ const awake = step > 0 && step <= every * 3;
266
+ if (!awake)
267
+ answered = 0;
268
+ if (o.reached() || !onProbation(o.version, { ...mo, now: t })) {
269
+ stop();
270
+ return "over";
271
+ }
272
+ if (!o.tried())
273
+ return "watching";
274
+ if (awake)
275
+ trying += step;
276
+ if (trying < after)
277
+ return "watching";
278
+ let up = false;
279
+ try {
280
+ up = await o.relayAnswers();
281
+ }
282
+ catch {
283
+ up = false;
284
+ }
285
+ if (over)
286
+ return "over";
287
+ if (o.reached()) {
288
+ stop();
289
+ return "over";
290
+ }
291
+ if (!up) {
292
+ answered = 0;
293
+ return "watching";
294
+ }
295
+ if (++answered < checks)
296
+ return "watching";
297
+ stop();
298
+ if (!markNeverOnline(o.version, { ...mo, now: now() }))
299
+ return "over";
300
+ o.log?.(`! pantheon ${o.version} has had no reply from the team's relay in ${Math.round(trying / 60_000)} minutes of trying, though the relay answers — going back to the previous version`);
301
+ o.exit();
302
+ return "marked";
303
+ }
304
+ finally {
305
+ busy = false;
306
+ }
307
+ };
308
+ if (!o.manual) {
309
+ timer = setInterval(() => { void tick().catch(() => { }); }, every);
310
+ timer.unref?.();
311
+ }
312
+ return { tick, stop };
313
+ }
314
+ //# sourceMappingURL=upgrade-probation.js.map
package/dist/upgrade.js CHANGED
@@ -8,6 +8,7 @@ import { proxyEnvFor } from "./network.js";
8
8
  import { relayProc, workerProc, notifierProc, menubarProc } from "./machine.js";
9
9
  import { load } from "./config.js";
10
10
  import { compareVersions, INSTALLER_MIN_CLI, isVersion } from "./installer.js";
11
+ import { HELD_FILE, PROBATION_FILE, heldUpgradeSentence, probationText, readRolledBack, replaceProbation } from "./upgrade-probation.js";
11
12
  export const WINDOWS_PROFILE_ROOT_MIN = "0.33.1-0";
12
13
  import { childNodeFlags, installerLineHere, launcherWithRepair, managedLayout, nodeSatisfies, nodeTooOldSentence, runtimeNodeVersion } from "./managed.js";
13
14
  export function repoRoot() {
@@ -88,7 +89,7 @@ export function defaultDeps() {
88
89
  return up;
89
90
  },
90
91
  npmUpgrade: (version) => npm(npmInstallArgs(version), { stdio: ["ignore", "pipe", "pipe"] }),
91
- stagedUpgrade: (m, spec) => { stagedManagedUpgrade(m, spec); },
92
+ stagedUpgrade: (m, spec, o) => { stagedManagedUpgrade(m, spec, undefined, o); },
92
93
  npmLatest: () => {
93
94
  try {
94
95
  return npm(["view", `${PKG_NAME}`, "version"], { stdio: ["ignore", "pipe", "ignore"], timeout: 4000 }).trim() || null;
@@ -137,14 +138,33 @@ export function upgrade(deps = defaultDeps(), opts = {}) {
137
138
  return { ...stop("node", why), needsPerson: why };
138
139
  }
139
140
  }
141
+ const hold = managed && !opts.exact ? (() => { try {
142
+ return deps.held ? deps.held() : readRolledBack(managed);
143
+ }
144
+ catch {
145
+ return null;
146
+ } })() : null;
147
+ const heldReport = (h) => ({ root, from, to: from, steps: [...steps, { name: "check", ok: true, detail: heldUpgradeSentence(h) }], ok: true, alreadyCurrent: true, restart: [], heldBack: h });
148
+ if (hold) {
149
+ const target = spec === "latest" ? (() => { try {
150
+ return deps.npmLatest();
151
+ }
152
+ catch {
153
+ return null;
154
+ } })() : spec;
155
+ if (target === hold.version)
156
+ return heldReport(hold);
157
+ }
140
158
  try {
141
159
  if (managed && deps.stagedUpgrade)
142
- deps.stagedUpgrade(managed, spec);
160
+ deps.stagedUpgrade(managed, spec, hold ? { refuse: hold.version } : {});
143
161
  else
144
162
  deps.npmUpgrade(spec === "latest" ? undefined : spec);
145
163
  steps.push({ name: "npm", ok: true, detail: `installed ${PKG_NAME}@${spec}` });
146
164
  }
147
165
  catch (e) {
166
+ if (e instanceof UpgradeHeld && hold)
167
+ return heldReport(hold);
148
168
  if (e instanceof UpgradeBusy) {
149
169
  return { root, from, to: from, steps: [...steps, { name: "npm", ok: true, detail: e.message }], ok: true, alreadyCurrent: true, restart: [] };
150
170
  }
@@ -256,6 +276,7 @@ const realSwapIo = (m) => ({
256
276
  catch { }
257
277
  },
258
278
  alive: (pid) => pidAlive(pid),
279
+ markLock: (fn) => replaceProbation(m, fn),
259
280
  holdSignals: () => {
260
281
  const hold = () => { };
261
282
  const sigs = ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"].filter((x) => x !== "SIGBREAK" || process.platform === "win32");
@@ -305,7 +326,14 @@ export const realSwapIoForTest = realSwapIo;
305
326
  export class UpgradeBusy extends Error {
306
327
  constructor() { super("another pantheon upgrade is running on this machine; nothing was changed, and the next check tries again"); }
307
328
  }
308
- export function stagedManagedUpgrade(m, spec, io = realSwapIo(m)) {
329
+ export class UpgradeHeld extends Error {
330
+ version;
331
+ constructor(version) {
332
+ super(`pantheon ${version} was put back on this machine after it failed here; nothing was changed`);
333
+ this.version = version;
334
+ }
335
+ }
336
+ export function stagedManagedUpgrade(m, spec, io = realSwapIo(m), o = {}) {
309
337
  const win = /\.exe$/i.test(m.node);
310
338
  const P = win ? win32 : posix;
311
339
  const runtime = P.dirname(m.nodeDir);
@@ -397,9 +425,16 @@ export function stagedManagedUpgrade(m, spec, io = realSwapIo(m)) {
397
425
  catch { }
398
426
  if (!version || (spec !== "latest" && version !== spec))
399
427
  throw new Error(`npm installed ${version || "nothing readable"} into the staging folder, not ${spec}; nothing was changed`);
428
+ if (o.refuse && version === o.refuse)
429
+ throw new UpgradeHeld(version);
400
430
  const staged = startsAs(P.join(stagedPkg, "bin", "pantheon.js"));
401
431
  if (staged !== version)
402
432
  throw new Error(`the new pantheon ${version} did not start (it answered ${staged ?? "nothing"}); the working version was kept`);
433
+ let from = null;
434
+ try {
435
+ from = JSON.parse(io.read(P.join(m.pkgDir, "package.json"))).version ?? null;
436
+ }
437
+ catch { }
403
438
  if (!rename(stagedPkg, ready))
404
439
  throw new Error("the new pantheon's files are still held by another program (a virus scan); nothing was changed, and the next check tries again");
405
440
  if (!inPlace())
@@ -431,6 +466,18 @@ export function stagedManagedUpgrade(m, spec, io = realSwapIo(m)) {
431
466
  ? `pantheon ${version} did not start once in place (it answered ${placed ?? "nothing"}); the previous version was put back`
432
467
  : `pantheon ${version} did not start once in place, and the previous version could not be put back yet. ${inPlace() ? `It is kept at ${prev}; the next upgrade puts it back, or run the installer again` : repairHint()}`);
433
468
  }
469
+ const mark = P.join(runtime, PROBATION_FILE);
470
+ const up = !!from && from !== version && (!isVersion(from) || !isVersion(version) || compareVersions(from, version) < 0);
471
+ try {
472
+ (io.markLock ?? ((fn) => fn()))(() => {
473
+ if (up && whole(prev))
474
+ io.write(mark, probationText(from, version, Date.now()));
475
+ else
476
+ io.remove(mark);
477
+ });
478
+ }
479
+ catch { }
480
+ tidy(P.join(runtime, HELD_FILE));
434
481
  return { version };
435
482
  }
436
483
  finally {
@@ -5,6 +5,7 @@ import { atomicWrite, isNewer, ASK_EXPIRY_MS } from "./worker-policy.js";
5
5
  import { installedVersion } from "./mcp-supervisor.js";
6
6
  import { VERSION } from "./version.js";
7
7
  import { BUDGET } from "./notice.js";
8
+ import { readRolledBack } from "./upgrade-probation.js";
8
9
  export const BEHIND_ALERT_AFTER_MS = 24 * 3_600_000;
9
10
  export const GRANTED_STUCK_AFTER_MS = 72 * 3_600_000;
10
11
  export const RELAY_PKG_REFRESH_MS = 60 * 60_000;
@@ -155,6 +156,8 @@ export function behindVerdict(seen, o) {
155
156
  return { due: false, why: "current" };
156
157
  if (o.state.behind_alerted?.[seen.pkg])
157
158
  return { due: false, why: "said" };
159
+ if (o.rolledBack && o.rolledBack === seen.pkg)
160
+ return { due: false, why: "worker_said" };
158
161
  if (o.state.upgrade_failed?.[seen.pkg]?.alerted_at)
159
162
  return { due: false, why: "worker_said" };
160
163
  if (o.policy?.upgradeHeld?.version === seen.pkg)
@@ -209,11 +212,12 @@ export class VersionWatch {
209
212
  const quiet = [];
210
213
  let running;
211
214
  const workerRunning = () => (running ??= safe(() => false, () => this.o.workerRunning()));
215
+ const rolledBack = safe(() => null, () => (this.o.rolledBack ?? (() => readRolledBack()?.version ?? null))());
212
216
  for (const r of relays) {
213
217
  const seen = state.relays[r];
214
218
  if (!seen)
215
219
  continue;
216
- const v = behindVerdict(seen, { local, now: now(), state, policy, workerRunning });
220
+ const v = behindVerdict(seen, { local, now: now(), state, policy, workerRunning, rolledBack });
217
221
  if (v.due)
218
222
  due.push(seen.pkg);
219
223
  else if (v.why === "worker_said")
@@ -267,6 +271,9 @@ export function behindStatusLine(o) {
267
271
  if (!seen || !isNewer(seen.pkg, o.local))
268
272
  return null;
269
273
  const pkg = seen.pkg;
274
+ if (o.rolledBack && o.rolledBack === pkg) {
275
+ return `pantheon ${o.local} here, the team's relay ${pkg}: ${pkg} did not work on this computer, so Pantheon went back to ${o.local} by itself and updates again when a newer release is out — nothing to do unless your human asks.`;
276
+ }
270
277
  const held = o.policy?.upgradeHeld?.version === pkg ? o.policy.upgradeHeld : null;
271
278
  if (held) {
272
279
  return `PANTHEON IS OUT OF DATE HERE: this computer runs ${o.local}, the team's relay ${pkg}, and the update needs something only your human can do: ${held.why} ` +
package/dist/which.js CHANGED
@@ -190,7 +190,7 @@ catch {
190
190
  return { why: "was read but not recognised as a package manager's shim" };
191
191
  const target = resolve(dir, ...parts);
192
192
  if (!exists(target))
193
- return { why: `was read, but what it runs is not there (${target})` };
193
+ return { why: `was read, but what it runs is not there (${target})`, missing: target };
194
194
  if (/\.exe$/i.test(target))
195
195
  return { command: target, args: [] };
196
196
  if (/\.(?:cmd|bat)$/i.test(target)) {
package/dist/win-host.js CHANGED
@@ -530,6 +530,7 @@ export function realHostIo(o = {}) {
530
530
  const node = o.node ?? process.execPath;
531
531
  const flags = o.flags ?? [];
532
532
  const cli = o.cli ?? resolve(HERE, "cli.js");
533
+ const childEntry = o.cli ? cli : (() => { const b = resolve(HERE, "..", "bin", "pantheon.js"); return existsSync(b) ? b : cli; })();
533
534
  const pantheon = o.pantheonCommand ?? `"${node}" ${flags.join(" ")} "${cli}"`.replace(/\s+/g, " ");
534
535
  const session = o.session ?? hostSession();
535
536
  const parent = process.ppid;
@@ -617,7 +618,7 @@ export function realHostIo(o = {}) {
617
618
  const d = readDefinition(child, home);
618
619
  if (!d)
619
620
  throw new Error(`no ${child} definition`);
620
- argv = childArgv(child, d.args, node, flags, cli);
621
+ argv = childArgv(child, d.args, node, flags, childEntry);
621
622
  if (existsSync(d.cwd))
622
623
  cwd = d.cwd;
623
624
  }