@codyswann/lisa 4.94.0 → 4.95.1

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 (85) hide show
  1. package/all/copy-overwrite/scripts/lisa-gates.mjs +2 -2
  2. package/all/copy-overwrite/scripts/lisa-run-gates.mjs +6 -6
  3. package/all/copy-overwrite/scripts/npm-updater-helper-graph.json +2 -2
  4. package/dist/core/lisa-owned-hash-ledger.d.ts.map +1 -1
  5. package/dist/core/lisa-owned-hash-ledger.js +6 -0
  6. package/dist/core/lisa-owned-hash-ledger.js.map +1 -1
  7. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  8. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  9. package/dist/core/upstream-evidence-manifest.js +18 -6
  10. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  11. package/package.json +7 -5
  12. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  13. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  14. package/plugins/lisa-agy/plugin.json +1 -1
  15. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  16. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  17. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  18. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  19. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  20. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  21. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  22. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  23. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  24. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  25. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  26. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  27. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  28. package/plugins/lisa-expo-agy/plugin.json +1 -1
  29. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  31. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  33. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  34. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  35. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  36. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  37. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  38. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  40. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  41. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  42. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  43. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  44. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  46. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  47. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  49. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  50. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  51. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  54. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  56. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  57. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  58. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  60. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  61. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  63. package/plugins/lisa-rails-agy/plugin.json +1 -1
  64. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  65. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  68. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  70. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  71. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  72. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  75. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  77. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  78. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  79. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  81. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  82. package/scripts/check-engine-floor.mjs +21 -4
  83. package/scripts/check-typecheck-tests.mjs +23 -6
  84. package/scripts/lib/dependency-tree.mjs +1 -1
  85. package/scripts/lisa-rollback-release.mjs +750 -0
@@ -0,0 +1,750 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Roll back a bad `@codyswann/lisa` release with one command
4
+ * (CodySwannGT/lisa#4605).
5
+ *
6
+ * Fixing forward is how a bad release is recovered. This command is what
7
+ * CONTAINS it while the fix is prepared: it stops new installs from picking up
8
+ * the bad version, and it says so where people look. Without it, the same
9
+ * containment is four hand-typed npm and GitHub commands run under pressure,
10
+ * in the right order, by whoever is on hand — which is exactly when a version
11
+ * gets mistyped or a step gets skipped.
12
+ *
13
+ * ## What it does, in order
14
+ *
15
+ * 1. `npm deprecate <pkg>@<bad> "<reason>"` — anyone installing the bad
16
+ * version sees the reason.
17
+ * 2. `npm dist-tag add <pkg>@<good> latest` — a plain install gets the good
18
+ * version again.
19
+ * 3. Prepends a deprecation notice to the GitHub release notes of `v<bad>`.
20
+ * 4. Reads the registry back and exits non-zero unless BOTH registry facts
21
+ * hold. The exit codes of steps 1 and 2 are not trusted on their own: a
22
+ * publish that "succeeded" and never reached the registry is a measured
23
+ * incident here (CodySwannGT/lisa#3684), and a rollback that reports success
24
+ * without having happened is worse than none.
25
+ *
26
+ * ## Why the read-back uses `?write=true`
27
+ *
28
+ * `npm view`, the plain packument and `/-/package/<pkg>/dist-tags` were all
29
+ * measured serving a version two behind for ~13 minutes after a write
30
+ * (CodySwannGT/lisa#3685), while `?write=true` told the truth. A verification
31
+ * fed a cached answer would fail a rollback that worked, or — worse — pass one
32
+ * that did not. Same endpoint `release.yml` uses for its version guard.
33
+ *
34
+ * ## Credentials
35
+ *
36
+ * CI publishes through npm OIDC trusted publishing, which authorizes
37
+ * `npm publish` only, so a rollback runs under the release owner's own
38
+ * `npm login` and `gh auth login`. Both are checked before the first write and
39
+ * a missing one is named in plain English. The command never reads, prints or
40
+ * stores a token: it only asks `npm whoami` and `gh auth status` whether one
41
+ * works, and discards their output.
42
+ *
43
+ * ## The dry run needs no credentials
44
+ *
45
+ * `--dry-run` reads the public packument to resolve the good version, prints
46
+ * the exact commands, and changes nothing. That is the step an operator runs
47
+ * first, so it must work for someone who has not signed in yet.
48
+ * @module scripts/lisa-rollback-release
49
+ */
50
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
51
+ import os from "node:os";
52
+ import path from "node:path";
53
+ import process from "node:process";
54
+
55
+ import semver from "semver";
56
+
57
+ import { boundedSpawnSync, isChildTimeout } from "./lib/bounded-spawn.mjs";
58
+ import { invokedAsScript } from "./lib/invoked-as-script.mjs";
59
+
60
+ /** Public npm registry, the default for every Lisa release. */
61
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org";
62
+
63
+ /** The package this command rolls back. */
64
+ const DEFAULT_PACKAGE = "@codyswann/lisa";
65
+
66
+ /** The repository whose GitHub release notes carry the notice. */
67
+ const DEFAULT_REPO = "CodySwannGT/lisa";
68
+
69
+ /** How long one npm or gh call may run before it is killed. */
70
+ const COMMAND_BUDGET_MS = 120_000;
71
+
72
+ /** Read-back attempts, and the pause between them. */
73
+ const VERIFY_ATTEMPTS = 5;
74
+ const VERIFY_DELAY_MS = 3_000;
75
+
76
+ /** The registry flag, passed through to every npm call. */
77
+ const REGISTRY_FLAG = "--registry";
78
+
79
+ /**
80
+ * npm's one-time 2FA code flag. An account with 2FA on writes refuses a write
81
+ * without it (EOTP), and with piped stdio npm cannot prompt for one.
82
+ */
83
+ const OTP_FLAG = "--otp";
84
+
85
+ /** How long one registry read may take before it is abandoned. */
86
+ const FETCH_TIMEOUT_MS = 30_000;
87
+
88
+ /** Flags that take a value, mapped to the option they set. */
89
+ const VALUE_FLAGS = new Map([
90
+ ["--bad", "bad"],
91
+ ["--to", "to"],
92
+ ["--reason", "reason"],
93
+ [REGISTRY_FLAG, "registry"],
94
+ ["--package", "packageName"],
95
+ ["--repo", "repo"],
96
+ [OTP_FLAG, "otp"],
97
+ ]);
98
+
99
+ /** Shown on any usage error, so the fix is on the same screen. */
100
+ const USAGE =
101
+ 'Usage: node scripts/lisa-rollback-release.mjs --bad <version> --reason "<text>" [--to <version>] [--otp <code>] [--dry-run] [--registry <url>]';
102
+
103
+ /**
104
+ * Read the command line into options.
105
+ *
106
+ * Unknown flags are refused rather than ignored: a mistyped `--dryrun` that is
107
+ * silently dropped turns a rehearsal into a real rollback.
108
+ * @param {string[]} argv - Arguments after the script path.
109
+ * @param {Record<string, string | undefined>} env - Environment to read
110
+ * `LISA_NPM_REGISTRY` from.
111
+ * @returns {{bad: string, to?: string, reason: string, dryRun: boolean,
112
+ * registry: string, packageName: string, repo: string, otp?: string}} Parsed options.
113
+ * @throws {Error} On a missing, malformed or unknown argument.
114
+ */
115
+ export function parseArgs(argv, env) {
116
+ const values = {};
117
+ let dryRun = false;
118
+ for (let index = 0; index < argv.length; index += 1) {
119
+ const flag = argv[index];
120
+ if (flag === "--dry-run") {
121
+ dryRun = true;
122
+ continue;
123
+ }
124
+ const key = VALUE_FLAGS.get(flag);
125
+ const value = argv[index + 1];
126
+ if (key === undefined) throw new Error(`Unknown argument ${flag}`);
127
+ // Only a real flag counts as a missing value: free text such as a
128
+ // `--reason` that happens to begin with `--` is a legitimate operand.
129
+ if (
130
+ value === undefined ||
131
+ value === "--dry-run" ||
132
+ VALUE_FLAGS.has(value)
133
+ ) {
134
+ throw new Error(`${flag} needs a value`);
135
+ }
136
+ values[key] = value;
137
+ index += 1;
138
+ }
139
+ return validated(values, dryRun, env);
140
+ }
141
+
142
+ /**
143
+ * Require a version spelled exactly as npm records it. `semver.valid` alone
144
+ * accepts `v4.90.1` and returns `4.90.1`, which npm would not find under that
145
+ * spelling — so the input must equal its own normalised form.
146
+ * @param {string} flag - The flag being checked, for the message.
147
+ * @param {string} value - What was passed.
148
+ * @param {string} example - An example version for the message.
149
+ * @returns {void}
150
+ * @throws {Error} When the value is not an exact version.
151
+ */
152
+ function exactVersion(flag, value, example) {
153
+ const normalised = semver.valid(value);
154
+ if (normalised === value) return;
155
+ throw new Error(
156
+ normalised !== null && value.startsWith("v")
157
+ ? `${flag} takes the bare version number: use ${normalised}, not ${value}`
158
+ : `${flag} must be an exact published version, e.g. ${example}`
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Apply defaults and check the parsed values.
164
+ * @param {Record<string, string>} values - Flag values by option name.
165
+ * @param {boolean} dryRun - Whether `--dry-run` was given.
166
+ * @param {Record<string, string | undefined>} env - Environment.
167
+ * @returns {ReturnType<typeof parseArgs>} Complete options.
168
+ */
169
+ function validated(values, dryRun, env) {
170
+ exactVersion("--bad", values.bad ?? "", "4.90.1");
171
+ if (values.to !== undefined) exactVersion("--to", values.to, "4.90.0");
172
+ // npm treats an empty deprecation message as "un-deprecate", so a blank
173
+ // reason would silently do the opposite of what was asked.
174
+ if ((values.reason ?? "").trim() === "") {
175
+ throw new Error('--reason is required, e.g. --reason "breaks lisa apply"');
176
+ }
177
+ return {
178
+ bad: values.bad,
179
+ ...(values.to === undefined ? {} : { to: values.to }),
180
+ reason: values.reason,
181
+ dryRun,
182
+ registry: values.registry ?? env.LISA_NPM_REGISTRY ?? DEFAULT_REGISTRY,
183
+ packageName: values.packageName ?? DEFAULT_PACKAGE,
184
+ repo: values.repo ?? DEFAULT_REPO,
185
+ ...(values.otp === undefined ? {} : { otp: values.otp }),
186
+ };
187
+ }
188
+
189
+ /**
190
+ * The uncached packument URL — see the module docblock for why only this one.
191
+ * @param {string} registry - Registry origin.
192
+ * @param {string} packageName - Package name, scope included.
193
+ * @returns {string} `<registry>/<scope>%2f<name>?write=true`.
194
+ */
195
+ export function packumentUrl(registry, packageName) {
196
+ let origin = registry;
197
+ while (origin.endsWith("/")) origin = origin.slice(0, -1);
198
+ return `${origin}/${packageName.replace("/", "%2f")}?write=true`;
199
+ }
200
+
201
+ /**
202
+ * Fetch the uncached packument.
203
+ * @param {{registry: string, packageName: string, fetchImpl: typeof fetch}} input
204
+ * Where to read and how.
205
+ * @returns {Promise<object>} The packument.
206
+ * @throws {Error} When the registry does not answer with one.
207
+ */
208
+ async function readPackument({ registry, packageName, fetchImpl }) {
209
+ const url = packumentUrl(registry, packageName);
210
+ const response = await fetchImpl(url, {
211
+ headers: { accept: "application/json" },
212
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
213
+ }).catch(error => {
214
+ throw new Error(
215
+ `Could not reach ${registry} to read ${packageName} (${error.cause?.code ?? error.message}).`
216
+ );
217
+ });
218
+ if (!response.ok) {
219
+ throw new Error(
220
+ `Could not read ${packageName} from ${registry} (HTTP ${response.status}).`
221
+ );
222
+ }
223
+ return response.json();
224
+ }
225
+
226
+ /**
227
+ * Choose the version `latest` should point to.
228
+ *
229
+ * Default: the highest published version below `bad` that is neither
230
+ * deprecated nor a prerelease — a prerelease or another deprecated version
231
+ * would trade one bad install for another. An explicit `to` may be a
232
+ * prerelease, because then somebody chose it, but it must be published, not
233
+ * deprecated, and not the bad version itself.
234
+ * @param {{versions?: Record<string, {deprecated?: string}>}} packument - The packument.
235
+ * @param {string} bad - The version being rolled back.
236
+ * @param {string} [to] - An explicit target.
237
+ * @returns {string} The good version.
238
+ * @throws {Error} When no acceptable version exists.
239
+ */
240
+ export function resolveGoodVersion(packument, bad, to) {
241
+ const versions = packument.versions ?? {};
242
+ if (!(bad in versions)) throw new Error(`${bad} is not published.`);
243
+ if (to !== undefined) return checkedTarget(versions, bad, to);
244
+ const candidates = Object.keys(versions)
245
+ .filter(version => semver.valid(version) && !semver.prerelease(version))
246
+ .filter(version => semver.lt(version, bad) && !versions[version].deprecated)
247
+ .sort(semver.rcompare);
248
+ if (candidates.length === 0) {
249
+ throw new Error(
250
+ `No published, non-deprecated version below ${bad} to point latest at. Pass --to <version> to choose one.`
251
+ );
252
+ }
253
+ return candidates[0];
254
+ }
255
+
256
+ /**
257
+ * Check an explicit `--to`.
258
+ * @param {Record<string, {deprecated?: string}>} versions - Published versions.
259
+ * @param {string} bad - The version being rolled back.
260
+ * @param {string} to - The requested target.
261
+ * @returns {string} The target, when acceptable.
262
+ */
263
+ function checkedTarget(versions, bad, to) {
264
+ if (to === bad) throw new Error("--to is the same version as --bad.");
265
+ if (!(to in versions)) throw new Error(`--to ${to} is not published.`);
266
+ if (versions[to].deprecated) {
267
+ throw new Error(`--to ${to} is itself deprecated; choose another version.`);
268
+ }
269
+ return to;
270
+ }
271
+
272
+ /**
273
+ * Refuse to move `latest` backward past a release that is not the bad one.
274
+ *
275
+ * Rolling back an OLDER version than `latest` would otherwise point `latest`
276
+ * below a newer, good release. Allowed without `--to` only when `latest` is
277
+ * the bad version, or already the good one (a re-run finishing a partial
278
+ * rollback); an explicit `--to` is a deliberate choice and is honoured.
279
+ * @param {{"dist-tags"?: {latest?: string}}} packument - The packument.
280
+ * @param {{bad: string, to?: string}} options - Run options.
281
+ * @param {string} good - Resolved good version.
282
+ * @returns {void}
283
+ * @throws {Error} When the move would go backward unasked.
284
+ */
285
+ function refuseBackwardMove(packument, { bad, to }, good) {
286
+ const latest = packument["dist-tags"]?.latest;
287
+ if (to !== undefined || latest === bad || latest === good) return;
288
+ throw new Error(
289
+ `latest is ${String(latest)}, not ${bad}; pass --to <version> to move latest anyway.`
290
+ );
291
+ }
292
+
293
+ /**
294
+ * The notice prepended to the bad release's GitHub notes.
295
+ * @param {string} reason - Why the release was rolled back.
296
+ * @param {string} good - Where `latest` now points.
297
+ * @returns {string} Markdown notice.
298
+ */
299
+ export function deprecationNotice(reason, good) {
300
+ return `> **This release is deprecated:** ${reason}\n>\n> npm latest now points to ${good}.\n`;
301
+ }
302
+
303
+ /**
304
+ * The three writes, in the order they must run.
305
+ * @param {{bad: string, good: string, reason: string, registry: string,
306
+ * packageName: string, repo: string, notesFile: string, otp?: string}} input
307
+ * What to write. `otp` is a one-time npm 2FA code, added to both npm writes.
308
+ * @returns {{command: string, args: string[]}[]} Commands as argv arrays.
309
+ */
310
+ export function planCommands({
311
+ bad,
312
+ good,
313
+ reason,
314
+ registry,
315
+ packageName,
316
+ repo,
317
+ notesFile,
318
+ otp,
319
+ }) {
320
+ const otpArgs = otp === undefined ? [] : [OTP_FLAG, otp];
321
+ return [
322
+ {
323
+ command: "npm",
324
+ args: [
325
+ "deprecate",
326
+ REGISTRY_FLAG,
327
+ registry,
328
+ ...otpArgs,
329
+ // `--` ends npm's option parsing, so a reason that starts with `-`
330
+ // reaches npm as the message rather than being read as a flag.
331
+ "--",
332
+ `${packageName}@${bad}`,
333
+ reason,
334
+ ],
335
+ },
336
+ {
337
+ command: "npm",
338
+ args: [
339
+ "dist-tag",
340
+ "add",
341
+ `${packageName}@${good}`,
342
+ "latest",
343
+ REGISTRY_FLAG,
344
+ registry,
345
+ ...otpArgs,
346
+ ],
347
+ },
348
+ {
349
+ command: "gh",
350
+ args: [
351
+ "release",
352
+ "edit",
353
+ `v${bad}`,
354
+ "--repo",
355
+ repo,
356
+ "--notes-file",
357
+ notesFile,
358
+ ],
359
+ },
360
+ ];
361
+ }
362
+
363
+ /**
364
+ * Render a command for a human to read or copy. Display only — nothing is
365
+ * ever run through a shell.
366
+ * @param {{command: string, args: string[]}} step - The command.
367
+ * @returns {string} A shell-quoted line.
368
+ */
369
+ export function formatCommand({ command, args }) {
370
+ const escapedQuote = "'\\''";
371
+ const quote = arg =>
372
+ /^[\w@%+=:,./-]+$/.test(arg)
373
+ ? arg
374
+ : `'${arg.replaceAll("'", escapedQuote)}'`;
375
+ // The 2FA code is a credential for its validity window: never echo it.
376
+ const shown = args.map((arg, index) =>
377
+ args[index - 1] === OTP_FLAG ? "<redacted>" : quote(arg)
378
+ );
379
+ return [command, ...shown].join(" ");
380
+ }
381
+
382
+ /**
383
+ * Run a command with no shell, capturing its output.
384
+ * @param {string} command - Executable on PATH.
385
+ * @param {string[]} args - Arguments.
386
+ * @returns {{status: number | null, stdout: string, stderr: string}} Outcome.
387
+ */
388
+ function defaultRun(command, args) {
389
+ const result = boundedSpawnSync(command, args, {
390
+ encoding: "utf8",
391
+ timeout: COMMAND_BUDGET_MS,
392
+ });
393
+ return {
394
+ status: result.error ? null : result.status,
395
+ stdout: result.stdout ?? "",
396
+ stderr: result.stderr ?? result.error?.message ?? "",
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Which sign-ins are missing. Output is discarded so nothing about a
402
+ * credential is ever echoed.
403
+ * @param {{registry: string, packageName: string}} options - Run options.
404
+ * @param {typeof defaultRun} run - Command runner.
405
+ * @returns {string[]} Plain-English descriptions of each missing sign-in.
406
+ */
407
+ function missingCredentials({ registry, packageName }, run) {
408
+ const missing = [];
409
+ if (run("npm", ["whoami", REGISTRY_FLAG, registry]).status !== 0) {
410
+ missing.push(
411
+ `You are not signed in to npm for ${registry} (\`npm whoami\` failed). Run \`npm login --registry ${registry}\` with an account that can publish ${packageName}.`
412
+ );
413
+ }
414
+ if (run("gh", ["auth", "status"]).status !== 0) {
415
+ missing.push(
416
+ "The GitHub CLI is not signed in (`gh auth status` failed). Run `gh auth login` with an account that can edit this repository's releases."
417
+ );
418
+ }
419
+ return missing;
420
+ }
421
+
422
+ /**
423
+ * Run one write; throw with its output when it fails.
424
+ * @param {{command: string, args: string[]}} step - The write.
425
+ * @param {typeof defaultRun} run - Command runner.
426
+ * @param {(line: string) => void} log - Progress output.
427
+ * @returns {void}
428
+ */
429
+ function runStep(step, run, log) {
430
+ log(`$ ${formatCommand(step)}`);
431
+ const result = run(step.command, step.args);
432
+ if (result.status !== 0) {
433
+ throw new Error(
434
+ `This step failed (exit ${String(result.status)}):\n ${formatCommand(step)}\n${result.stderr}${result.stdout}`
435
+ );
436
+ }
437
+ }
438
+
439
+ /**
440
+ * The bad release's notes with the notice on top. Already-noticed notes are
441
+ * left alone, so a re-run does not stack notices.
442
+ * @param {{bad: string, repo: string}} options - Run options.
443
+ * @param {string} notice - The notice to prepend.
444
+ * @param {typeof defaultRun} run - Command runner.
445
+ * @returns {string | null} New notes, or null when no edit is needed.
446
+ */
447
+ function noticedNotes({ bad, repo }, notice, run) {
448
+ const view = run("gh", [
449
+ "release",
450
+ "view",
451
+ `v${bad}`,
452
+ "--repo",
453
+ repo,
454
+ "--json",
455
+ "body",
456
+ ]);
457
+ if (view.status !== 0) {
458
+ throw new Error(
459
+ `Could not read the GitHub release v${bad}:\n${view.stderr}`
460
+ );
461
+ }
462
+ const body = JSON.parse(view.stdout).body ?? "";
463
+ // GitHub strips trailing newlines, so a body that is ONLY the notice comes
464
+ // back without the notice's last newline. Compare without it.
465
+ return body.startsWith(notice.trimEnd()) ? null : `${notice}\n${body}`;
466
+ }
467
+
468
+ /**
469
+ * Problems with the registry state after a rollback, or none.
470
+ * @param {{"dist-tags"?: {latest?: string}, versions?: Record<string, {deprecated?: string}>}} packument
471
+ * The uncached packument.
472
+ * @param {string} bad - The rolled-back version.
473
+ * @param {string} good - Where `latest` should point.
474
+ * @returns {string[]} What does not hold yet.
475
+ */
476
+ function verificationProblems(packument, bad, good) {
477
+ const problems = [];
478
+ const latest = packument["dist-tags"]?.latest;
479
+ if (latest !== good)
480
+ problems.push(`latest is ${String(latest)}, not ${good}`);
481
+ if (!packument.versions?.[bad]?.deprecated) {
482
+ problems.push(`${bad} is not deprecated`);
483
+ }
484
+ return problems;
485
+ }
486
+
487
+ /**
488
+ * Read the registry back until both facts hold, or give up.
489
+ * @param {object} options - Run options.
490
+ * @param {string} good - Where `latest` should point.
491
+ * @param {object} deps - Injected seams.
492
+ * @returns {Promise<string[]>} Problems remaining after the last attempt.
493
+ */
494
+ async function verify(options, good, deps) {
495
+ let problems = [];
496
+ for (let attempt = 1; attempt <= VERIFY_ATTEMPTS; attempt += 1) {
497
+ // The writes have already happened, so a failed read is "not verified",
498
+ // never "stopped": the operator must still learn the writes went out.
499
+ problems = await readPackument({ ...options, fetchImpl: deps.fetchImpl })
500
+ .then(packument => verificationProblems(packument, options.bad, good))
501
+ .catch(error => [
502
+ `the registry could not be read back: ${error.message}`,
503
+ ]);
504
+ if (problems.length === 0 || attempt === VERIFY_ATTEMPTS) break;
505
+ await deps.sleep(VERIFY_DELAY_MS);
506
+ }
507
+ return problems;
508
+ }
509
+
510
+ /**
511
+ * Print what a real run would do.
512
+ * @param {object} options - Run options.
513
+ * @param {string} good - Resolved good version.
514
+ * @param {(line: string) => void} log - Output.
515
+ * @returns {number} Exit code.
516
+ */
517
+ function printDryRun(options, good, log) {
518
+ const plan = planCommands({ ...options, good, notesFile: "<notes-file>" });
519
+ log("Dry run: nothing will be changed.");
520
+ log(
521
+ `Rolling back ${options.packageName}@${options.bad}; latest would point to ${good}.`
522
+ );
523
+ log(
524
+ "A real run would check `npm whoami` and `gh auth status`, then run, in order:"
525
+ );
526
+ plan.forEach((step, index) => log(` ${index + 1}. ${formatCommand(step)}`));
527
+ log(
528
+ `<notes-file> is the current v${options.bad} notes with this notice on top:`
529
+ );
530
+ log(deprecationNotice(options.reason, good));
531
+ log(
532
+ `Then it reads ${packumentUrl(options.registry, options.packageName)} and exits 0 only if latest is ${good} and ${options.bad} is deprecated.`
533
+ );
534
+ return 0;
535
+ }
536
+
537
+ /**
538
+ * What a partial run changed, for the person who has to finish it.
539
+ *
540
+ * A step whose child was killed at its deadline is "not confirmed", not "not
541
+ * done": the write may have reached the registry before the kill.
542
+ * @param {string[]} labels - Every step, in order.
543
+ * @param {number} doneCount - How many completed.
544
+ * @param {unknown} error - Why the next one stopped.
545
+ * @returns {string} The report.
546
+ */
547
+ function progressReport(labels, doneCount, error) {
548
+ const timedOut = isChildTimeout(error);
549
+ const notDone = labels.slice(doneCount + (timedOut ? 1 : 0));
550
+ return [
551
+ doneCount > 0
552
+ ? `Already done: ${labels.slice(0, doneCount).join("; ")}.`
553
+ : "",
554
+ timedOut ? `Not confirmed (timed out): ${labels[doneCount]}.` : "",
555
+ notDone.length > 0 ? `Not done: ${notDone.join("; ")}.` : "",
556
+ "Re-running the same command is safe and will finish the rest.",
557
+ ]
558
+ .filter(Boolean)
559
+ .join(" ");
560
+ }
561
+
562
+ /**
563
+ * Run the three writes in order, recording each one that completes.
564
+ *
565
+ * A failure partway through leaves the registry half-changed, and the person
566
+ * running this needs to know which half. A failed npm write is re-raised with
567
+ * that report. A failed notes step is RETURNED instead, so the caller still
568
+ * verifies the npm containment — which is the part that protects installs —
569
+ * before reporting that only the notice is missing.
570
+ * @param {object} options - Run options.
571
+ * @param {string} good - Resolved good version.
572
+ * @param {RollbackDeps} deps - Injected seams.
573
+ * @param {string} notesFile - Where the edited notes are written.
574
+ * @returns {string | null} The notes-step failure report, or null.
575
+ */
576
+ function applyWrites(options, good, deps, notesFile) {
577
+ const [deprecate, distTag, editNotes] = planCommands({
578
+ ...options,
579
+ good,
580
+ notesFile,
581
+ });
582
+ const labels = [
583
+ `deprecated ${options.bad}`,
584
+ `moved latest to ${good}`,
585
+ `added the deprecation notice to the v${options.bad} release notes`,
586
+ ];
587
+ let done = 0;
588
+ try {
589
+ runStep(deprecate, deps.run, deps.log);
590
+ done = 1;
591
+ runStep(distTag, deps.run, deps.log);
592
+ done = 2;
593
+ } catch (error) {
594
+ if (done === 0 && !isChildTimeout(error)) throw error;
595
+ throw new Error(`${error.message}\n${progressReport(labels, done, error)}`);
596
+ }
597
+ try {
598
+ writeNotes(options, good, deps, editNotes);
599
+ return null;
600
+ } catch (error) {
601
+ return `The deprecation notice was NOT added to GitHub release v${options.bad} in ${options.repo}: ${error.message}\n${progressReport(labels, done, error)}`;
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Prepend the notice to the bad release's notes, unless it is already there.
607
+ * @param {object} options - Run options.
608
+ * @param {string} good - Resolved good version.
609
+ * @param {RollbackDeps} deps - Injected seams.
610
+ * @param {{command: string, args: string[]}} editNotes - The edit command.
611
+ * @returns {void}
612
+ */
613
+ function writeNotes(options, good, deps, editNotes) {
614
+ const notes = noticedNotes(
615
+ options,
616
+ deprecationNotice(options.reason, good),
617
+ deps.run
618
+ );
619
+ if (notes === null) {
620
+ deps.log(`v${options.bad} notes already carry the notice.`);
621
+ return;
622
+ }
623
+ const notesFile = editNotes.args[editNotes.args.indexOf("--notes-file") + 1];
624
+ deps.writeFile(notesFile, notes);
625
+ runStep(editNotes, deps.run, deps.log);
626
+ }
627
+
628
+ /**
629
+ * Do the writes, then verify.
630
+ * @param {object} options - Run options.
631
+ * @param {string} good - Resolved good version.
632
+ * @param {object} deps - Injected seams.
633
+ * @returns {Promise<number>} Exit code.
634
+ */
635
+ async function realRun(options, good, deps) {
636
+ const missing = missingCredentials(options, deps.run);
637
+ if (missing.length > 0) {
638
+ deps.error(
639
+ `Refusing to roll back. ${missing.join(" ")} Nothing was changed.`
640
+ );
641
+ return 1;
642
+ }
643
+ if (options.registry !== DEFAULT_REGISTRY) {
644
+ deps.log(
645
+ `Warning: the npm writes go to ${options.registry}, while the GitHub notes edit goes to ${options.repo}.`
646
+ );
647
+ }
648
+ const dir = deps.makeTempDir();
649
+ let notesFailure;
650
+ try {
651
+ notesFailure = applyWrites(
652
+ options,
653
+ good,
654
+ deps,
655
+ path.join(dir, `v${options.bad}-notes.md`)
656
+ );
657
+ } finally {
658
+ deps.removeDir(dir);
659
+ }
660
+ const problems = await verify(options, good, deps);
661
+ if (problems.length > 0) {
662
+ deps.error(
663
+ `Rollback NOT verified on ${options.registry}: ${problems.join("; ")}. The npm writes were applied.`
664
+ );
665
+ } else {
666
+ deps.log(
667
+ `Verified: ${options.bad} is deprecated and latest is ${good}. Now prepare the fix-forward release.`
668
+ );
669
+ }
670
+ if (notesFailure !== null) deps.error(notesFailure);
671
+ return problems.length > 0 || notesFailure !== null ? 1 : 0;
672
+ }
673
+
674
+ /**
675
+ * Injected seams for {@link rollback}.
676
+ * @typedef {object} RollbackDeps
677
+ * @property {(command: string, args: string[]) => {status: number | null, stdout: string, stderr: string}} run
678
+ * Runs one command with no shell.
679
+ * @property {typeof fetch} fetchImpl - Reads the registry.
680
+ * @property {(file: string, text: string) => unknown} writeFile - Writes the notes file.
681
+ * @property {() => string} makeTempDir - Creates a private scratch directory.
682
+ * @property {(dir: string) => unknown} removeDir - Removes that directory.
683
+ * @property {(ms: number) => Promise<unknown>} sleep - Waits between read-backs.
684
+ * @property {(line: string) => unknown} log - Progress output.
685
+ * @property {(line: string) => unknown} error - Failure output.
686
+ */
687
+
688
+ /** @type {RollbackDeps} Injected seams, with real defaults. */
689
+ const DEFAULT_DEPS = {
690
+ run: defaultRun,
691
+ fetchImpl: (...args) => fetch(...args),
692
+ writeFile: (file, text) => writeFileSync(file, text, "utf8"),
693
+ makeTempDir: () => mkdtempSync(path.join(os.tmpdir(), "lisa-rollback-")),
694
+ removeDir: dir => rmSync(dir, { recursive: true, force: true }),
695
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
696
+ log: line => process.stdout.write(`${line}\n`),
697
+ error: line => process.stderr.write(`${line}\n`),
698
+ };
699
+
700
+ /**
701
+ * Resolve the good version, then dry-run or roll back.
702
+ * @param {ReturnType<typeof parseArgs>} options - Parsed options.
703
+ * @param {Partial<typeof DEFAULT_DEPS>} [injected] - Test seams.
704
+ * @returns {Promise<number>} Exit code.
705
+ */
706
+ export async function rollback(options, injected = {}) {
707
+ const deps = { ...DEFAULT_DEPS, ...injected };
708
+ try {
709
+ const packument = await readPackument({
710
+ ...options,
711
+ fetchImpl: deps.fetchImpl,
712
+ });
713
+ const good = resolveGoodVersion(packument, options.bad, options.to);
714
+ refuseBackwardMove(packument, options, good);
715
+ return options.dryRun
716
+ ? printDryRun(options, good, deps.log)
717
+ : await realRun(options, good, deps);
718
+ } catch (error) {
719
+ deps.error(`Rollback stopped: ${error.message}`);
720
+ return 1;
721
+ }
722
+ }
723
+
724
+ /**
725
+ * CLI entry: parse, then roll back.
726
+ * @param {string[]} argv - Arguments after the script path.
727
+ * @param {Partial<typeof DEFAULT_DEPS> & {env?: Record<string, string | undefined>}} [injected]
728
+ * Test seams.
729
+ * @returns {Promise<number>} Exit code.
730
+ */
731
+ export async function main(argv, injected = {}) {
732
+ const { env = process.env, ...deps } = injected;
733
+ const error = deps.error ?? DEFAULT_DEPS.error;
734
+ let options;
735
+ try {
736
+ options = parseArgs(argv, env);
737
+ } catch (usageError) {
738
+ error(`${usageError.message}\n${USAGE}`);
739
+ return 1;
740
+ }
741
+ return rollback(options, deps);
742
+ }
743
+
744
+ /* c8 ignore start -- CLI wiring, exercised through main() in tests */
745
+ if (invokedAsScript(import.meta.url)) {
746
+ main(process.argv.slice(2)).then(code => {
747
+ process.exitCode = code;
748
+ });
749
+ }
750
+ /* c8 ignore stop */