@futurelastic/colab-handbook 1.12.0-rc.40 → 1.12.0-rc.42

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.
package/package.json CHANGED
@@ -27,5 +27,5 @@
27
27
  "engines": {
28
28
  "node": ">=18"
29
29
  },
30
- "version": "1.12.0-rc.40"
30
+ "version": "1.12.0-rc.42"
31
31
  }
@@ -23,7 +23,7 @@ Starting points you **copy into your own repo**. That is the entire model.
23
23
  | `release-auto.yml` | `.github/workflows/release-auto.yml` | A repo whose release tags land on `main` (`trunk: main`, `deploy: tag` or `none`) and whose §6 release route cuts candidates | Runs `colab release cut --auto` after CI goes green on main and `colab release finalize --auto` daily, from a handbook ref (`HANDBOOK_REF` — the `stable` channel by default, `next` for the fast channel, or an exact tag to freeze; #445) — the handbook's own copy runs its checkout's CLI instead, since it ships the CLI it releases with (#428). **Publishes the Release in the same run** — a tag pushed with `GITHUB_TOKEN` triggers no other workflow, so `release-tag.yml` would never fire for it. A refusal is a warning, not a red run. Reads and creates tags, and fast-forwards the release channels `next` / `stable` (branches naming the newest candidate / final, #445); never pushes a commit. The audit recognises any workflow running `release cut/finalize --auto` and warns when the route leaves candidates off, when it tags without publishing while a tag-push workflow waits, or when it commits. |
24
24
  | `dist-refs.yml` | `.github/workflows/dist-refs.yml` | A **private** repo shipping a **compiled** tool, installed as `npx github:<org>/<repo>#vX.Y.Z` ([CONVENTIONS §6, *Distribution*](../CONVENTIONS.md#distribution--one-install-surface-npx-442)) | `workflow_call`, called from the same run that cut the release tag (a tag pushed with `GITHUB_TOKEN` triggers nothing else). Takes one build artifact per `<os>-<arch>` and pushes each as an orphan commit at `refs/tags/dist/vX.Y.Z/<os>-<arch>` with a `SHA256SUMS`. Refuses a public or unreadable repository (a public compiled tool ships npm platform packages instead), a version that is not an existing tag, and a missing platform — before pushing any. Never moves a dist ref that exists. |
25
25
  | `npx-launcher.mjs` | anywhere in-repo (e.g. `bin/launch.mjs`), named by the root `package.json`'s `bin` | Pairs with `dist-refs.yml` | Node ≥ 18, zero dependencies, needs `git`. Reads the `#vX.Y.Z` npx installed, fetches that one dist ref with the same URL and credentials npx cloned with, verifies `SHA256SUMS`, installs to a stable per-user path (`$XDG_DATA_HOME`/`%LOCALAPPDATA%`), and execs it; `--print-path` prints that path. A **channel** committish (`#stable`, `#next`, #465) is resolved to the release tag on the commit npx installed, then installed as that version; any other branch is refused. Also the library `npx-service.mjs` imports. `*.mjs`, so `colab template npx-launcher.mjs --dest <path>` copies it stamped, `--dest` required. One edit point: `BIN` (defaults to the package name without its scope). |
26
- | `npx-service.mjs` | the same directory as your `npx-launcher.mjs` copy (e.g. `bin/service.mjs`), named by the root `package.json`'s `bin` | A tool that runs as a **per-machine service** (a dashboard, a daemon, a JS app a launch agent serves), installed with npx ([CONVENTIONS §6, *Services over npx*](../CONVENTIONS.md#services-over-npx--init-update-rollback-465)) | `npx github:<org>/<repo>#vX.Y.Z init`, then `<tool> update [--check] [--version vX.Y.Z] [--channel next\|stable]`, `<tool> rollback`, `<tool> status`; anything else runs the current version's payload. Versions side by side under `$XDG_DATA_HOME/<tool>/` with `current`/`previous` links the unit and the `~/.local/bin` shim go through; update installs beside, switches, restarts, health-checks, and **switches back** on failure. Config/secrets under `$XDG_CONFIG_HOME/<tool>/`, state and logs under `$XDG_STATE_HOME/<tool>/` — the unit carries their locations, never a value. launchd agent on macOS, systemd user unit on Linux, Windows refused; `<TOOL>_SERVICE_MANAGER=none` skips the manager. Node ≥ 18, zero dependencies; needs `git`, and `npm` for `update`. **Imports `./npx-launcher.mjs`** — copy both, or edit the import. Edit points: `KIND` (`binary` = a compiled tool from dist refs, `package` = a JS app run with node), `LABEL`, `SERVICE_ARGS`, `ENTRY`, `HEALTH_URL`, `KEEP`, `VERBS`. The package's `files` must include both copies (and a `package` app's built output). `colab template npx-service.mjs --dest <path>`, `--dest` required. |
26
+ | `npx-service.mjs` | the same directory as your `npx-launcher.mjs` copy (e.g. `bin/service.mjs`), named by the root `package.json`'s `bin` | A tool that runs as a **per-machine service** (a dashboard, a daemon, a JS app a launch agent serves), installed with npx ([CONVENTIONS §6, *Services over npx*](../CONVENTIONS.md#services-over-npx--init-update-rollback-465)) | `npx github:<org>/<repo>#vX.Y.Z init [--auto-update 6h \| --no-auto-update]`, then `<tool> update [--check] [--version vX.Y.Z] [--channel next\|stable]`, `<tool> rollback`, `<tool> status`, `<tool> uninstall [--purge]` (#472: unit, timer, shim and every version go; config and state stay unless `--purge`); anything else runs the current version's payload. Versions side by side under `$XDG_DATA_HOME/<tool>/` with `current`/`previous` links the unit and the `~/.local/bin` shim go through; update installs beside, switches, restarts, health-checks, and **switches back** on failure. Config/secrets under `$XDG_CONFIG_HOME/<tool>/`, state and logs under `$XDG_STATE_HOME/<tool>/` — the unit carries their locations, never a value. launchd agent on macOS, systemd user unit on Linux, Windows refused; `<TOOL>_SERVICE_MANAGER=none` skips the manager. `--auto-update` (#471) adds a timer (launchd `StartInterval` agent / systemd user `.timer`) that runs the same `update`. Node ≥ 18, zero dependencies; needs `git`, `npm` for `update`, `tar` for `dist`. **Imports `./npx-launcher.mjs`** — copy both, or edit the import. Edit points: `KIND` (`binary` = a compiled tool from dist refs, `package` = a JS app run with node, `dist` = a prebuilt JS app unpacked from one verified tarball in the `dist/vX.Y.Z/any` ref, #470), `LABEL`, `SERVICE_ARGS`, `ENTRY`, `DIST_FILE`, `HEALTH_URL`, `KEEP`, `AUTO_UPDATE`, `VERBS`. The package's `files` must include both copies (and a `package` app's built output). `colab template npx-service.mjs --dest <path>`, `--dest` required. |
27
27
  | `deploy-xserver.yml` | `.github/workflows/deploy-xserver.yml` | PHP-framework + Vite apps shipped to **shared hosting over SSH** (no root, no Docker): build on a runner, rsync, migrate on the server | Derived from three independently-written copies. Resolves Node the same way the CI templates do — all three hardcoded it, and one shipped on a different major than its CI built on. Migrates **production**; keeps a **mandatory** smoke test. Does **not** change your tier. |
28
28
  | `deploy-container.yml` | `.github/workflows/deploy-container.yml` | A **container** app on a host whose platform has an API (Portainer today), `deploy: tag` ([CONVENTIONS §6, *A container deploy*](../CONVENTIONS.md#6-releases), #452) | One contract on every host: build each listed image **once** per final tag (`vX.Y.Z` + commit sha), run the pre-deploy hook, have the platform run exactly that tag (all images, one call), green only on a **verified running version** (stack settled, commit and container images checked, then `release.health-url` reporting `X.Y.Z`), roll back to the previous final on a failure after the platform accepted. **Two jobs (#460):** `publish` builds and pushes on **every** final, ungated — so a repo not yet cut over still gets each final's image in the registry; `deploy` `needs:` it, never builds (a missing image fails before the platform is touched), and is the one job you gate on "is the platform switched on". Images and build args sit in the workflow-level `env`, written once for both jobs. Triggers: a final tag push (route `deploy-tag`), `workflow_dispatch` with a tag (a manual deploy or rollback), and `workflow_call` — route `deploy-tag-fast` reaches it from `release-auto.yml`'s commented `deploy` job, like `dist-refs.yml` from its release run. Needs its two scripts below. One required secret: `PORTAINER_API_KEY`, a non-admin key owning only this app's stack; optional `HEALTH_AUTH_HEADER` (`Name: value`) or `HEALTH_BASIC_AUTH` (`user:password`) when the version URL sits behind auth — masked, never printed. **Every redeploy recreates the containers.** Does **not** change your exposure. |
29
29
  | `deploy-container-run.mjs` | `.github/deploy/deploy-container-run.mjs` | Pairs with `deploy-container.yml` | The driver: builds, runs the hook, calls the adapter, verifies, rolls back, records. `--publish-only` = build and push only (no platform config, no version URL needed); `--deploy-only` = everything after, refusing a tag whose image is not in the registry. **Build args:** `DEPLOY_BUILD_ARGS`, one per line — `KEY=VALUE` for every image or `<image-ref> KEY=VALUE` for one; `${TAG}` (`vX.Y.Z`), `${VERSION}` (`X.Y.Z`) and `${SHA}` are filled in by the driver, so a static site can bake public config and its version into a served file. They end up in the image — public values only, never a secret. Node ≥ 18, zero dependencies; shells out to `git`, `docker`, `gh`. `colab template deploy-container-run.mjs --dest <path>`, `--dest` required, stamped on line 2. |
@@ -25,6 +25,12 @@
25
25
  # <os>-<arch> is Node's own `${process.platform}-${process.arch}` (darwin-arm64, linux-x64,
26
26
  # win32-x64, …) — the same names npm's `os`/`cpu` fields use, and what the launcher computes.
27
27
  #
28
+ # A PREBUILT JS APP (one whose build cannot run on the target, #470) uses the same workflow with
29
+ # the platform-neutral name `any`: `platforms: any`, `bin: <tool>.tgz`, and an artifact
30
+ # `<artifact-prefix>any` holding that one tarball (`tar -czf <tool>.tgz -C <build-output> .`).
31
+ # templates/npx-service.mjs with KIND 'dist' fetches refs/tags/dist/vX.Y.Z/any, verifies the
32
+ # tarball against its SHA256SUMS and unpacks it beside the running version.
33
+ #
28
34
  # HOW TO CALL IT — from the SAME run that cut the release tag. A tag pushed with GITHUB_TOKEN
29
35
  # triggers no other workflow, so "build on the tag push" silently never runs for a tag your
30
36
  # release workflow made (CONVENTIONS.md §6). Build every platform in that run, upload one
@@ -50,7 +50,7 @@ import {
50
50
  chmodSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync,
51
51
  } from 'node:fs';
52
52
  import { homedir, tmpdir } from 'node:os';
53
- import { dirname, join, resolve } from 'node:path';
53
+ import { basename, dirname, join, resolve } from 'node:path';
54
54
  import { fileURLToPath } from 'node:url';
55
55
 
56
56
  // EDIT: the binary's name inside each dist ref (dist-refs.yml's `bin` input). null = this
@@ -223,10 +223,12 @@ function git(args, opts = {}) {
223
223
  }
224
224
 
225
225
  /**
226
- * Fetch the dist ref into a throwaway repo, verify, install atomically. Returns the binary path.
227
- * Throws on any refusal (main() turns that into a message + exit 1; the service template reports it).
226
+ * Fetch ONE file out of the dist ref `refs/tags/dist/<version>/<plat>` into a throwaway repo,
227
+ * verify it against that ref's SHA256SUMS, and move it into place at `dest` atomically. Returns
228
+ * `dest`. Throws on any refusal. `plat` is `<os>-<arch>` for a binary, or `any` for a
229
+ * platform-neutral artifact (a prebuilt JS app's tarball — templates/npx-service.mjs KIND 'dist').
228
230
  */
229
- export function install({ origin, version, plat, exe, dir }) {
231
+ export function fetchDistFile({ origin, version, plat, file, dest, mode = 0o755 }) {
230
232
  const ref = `refs/tags/dist/${version}/${plat}`;
231
233
  const fail = (msg) => { throw new Error(msg); };
232
234
  const tmp = mkdtempSync(join(tmpdir(), 'npx-launcher-'));
@@ -237,28 +239,38 @@ export function install({ origin, version, plat, exe, dir }) {
237
239
  fail(`could not fetch ${ref} from ${origin} — is ${version} released for ${plat}?\n${(f.stderr || '').trim()}`);
238
240
  }
239
241
  const sums = git(['-C', tmp, 'cat-file', 'blob', `FETCH_HEAD:SHA256SUMS`]);
240
- if (sums.status !== 0) fail(`${ref} carries no SHA256SUMS — refusing an unverifiable binary`);
241
- const want = expectedSum(sums.stdout, exe);
242
- if (!want) fail(`${ref}'s SHA256SUMS has no line for ${exe}`);
242
+ if (sums.status !== 0) fail(`${ref} carries no SHA256SUMS — refusing an unverifiable download`);
243
+ const want = expectedSum(sums.stdout, file);
244
+ if (!want) fail(`${ref}'s SHA256SUMS has no line for ${file}`);
243
245
 
246
+ const dir = dirname(dest);
244
247
  mkdirSync(dir, { recursive: true });
245
- const part = join(dir, `.${exe}.part-${process.pid}`);
248
+ const part = join(dir, `.${basename(dest)}.part-${process.pid}`);
246
249
  const fd = openSync(part, 'w');
247
250
  let r;
248
251
  try {
249
- r = spawnSync('git', ['-C', tmp, 'cat-file', 'blob', `FETCH_HEAD:${exe}`], { stdio: ['ignore', fd, 'pipe'] });
252
+ r = spawnSync('git', ['-C', tmp, 'cat-file', 'blob', `FETCH_HEAD:${file}`], { stdio: ['ignore', fd, 'pipe'] });
250
253
  } finally { closeSync(fd); }
251
- if (r.error || r.status !== 0) { rmSync(part, { force: true }); fail(`${ref} has no ${exe}`); }
254
+ if (r.error || r.status !== 0) { rmSync(part, { force: true }); fail(`${ref} has no ${file}`); }
252
255
  const got = sha256(part);
253
- if (got !== want) { rmSync(part, { force: true }); fail(`checksum mismatch for ${exe} in ${ref}: expected ${want}, got ${got}`); }
254
- chmodSync(part, 0o755);
255
- renameSync(part, join(dir, exe));
256
- return join(dir, exe);
256
+ if (got !== want) { rmSync(part, { force: true }); fail(`checksum mismatch for ${file} in ${ref}: expected ${want}, got ${got}`); }
257
+ chmodSync(part, mode);
258
+ renameSync(part, dest);
259
+ return dest;
257
260
  } finally {
258
261
  rmSync(tmp, { recursive: true, force: true });
259
262
  }
260
263
  }
261
264
 
265
+ /**
266
+ * Fetch the platform's binary from its dist ref, verify, install atomically. Returns the binary
267
+ * path. Throws on any refusal (main() turns that into a message + exit 1; the service template
268
+ * reports it).
269
+ */
270
+ export function install({ origin, version, plat, exe, dir }) {
271
+ return fetchDistFile({ origin, version, plat, file: exe, dest: join(dir, exe) });
272
+ }
273
+
262
274
  export function main(argv, start = here) {
263
275
  const pkgDir = packageRoot(start);
264
276
  const pkg = (pkgDir && readJson(join(pkgDir, 'package.json'))) || die('cannot find this package\'s package.json');
@@ -9,9 +9,11 @@
9
9
  // through three verbs, and never runs from npx's cache:
10
10
  //
11
11
  // npx github:<org>/<repo>#vX.Y.Z init [--channel next|stable] [--health-url URL]
12
+ // [--auto-update <interval> | --no-auto-update]
12
13
  // <tool> update [--check] [--version vX.Y.Z] [--channel next|stable]
13
14
  // <tool> rollback
14
15
  // <tool> status
16
+ // <tool> uninstall [--purge]
15
17
  //
16
18
  // Anything else on the command line is the tool's own: it runs the CURRENT version's payload.
17
19
  //
@@ -20,6 +22,7 @@
20
22
  // $XDG_DATA_HOME/<tool>/ (default ~/.local/share/<tool>, macOS too — no spaces in a plist)
21
23
  // vX.Y.Z/pkg/ the package at that version (an npm prefix: node_modules/<name>/…)
22
24
  // vX.Y.Z/<os>-<arch>/<tool> KIND 'binary' only — exactly where npx-launcher.mjs installs it
25
+ // vX.Y.Z/app/ KIND 'dist' only — the prebuilt app, unpacked from its tarball
23
26
  // current -> vX.Y.Z the launch agent and the shim go THROUGH this link, so an update
24
27
  // previous -> vW.Y.Z or a rollback is one atomic rename, never a rewritten unit
25
28
  // $XDG_CONFIG_HOME/<tool>/ (0700) install.json {origin, channel, healthUrl?} + YOUR config
@@ -43,13 +46,35 @@
43
46
  // until a 2xx body reports the version just switched to. Without one: the service manager must
44
47
  // report the service running after a settle period. <TOOL>_HEALTH_TIMEOUT_MS overrides the wait.
45
48
  //
49
+ // THREE KINDS. 'binary': a compiled tool; the service runs the binary from the platform's dist ref.
50
+ // 'package': a JS app that runs from its package (built by `prepare` if it needs building).
51
+ // 'dist': a JS app whose build cannot run on the target (#470) — the release ships its output
52
+ // prebuilt as ONE tarball (DIST_FILE) in the platform-neutral dist ref refs/tags/dist/vX.Y.Z/any
53
+ // (templates/dist-refs.yml with `platforms: any`, `bin: <DIST_FILE>`). It is fetched and verified
54
+ // against that ref's SHA256SUMS exactly as the launcher fetches a binary, then unpacked into
55
+ // vX.Y.Z/app/, and the service runs app/ENTRY with node. The package itself is still installed
56
+ // beside it (vX.Y.Z/pkg/) because this manager lives there. Build the tarball with its files at
57
+ // the top level: `tar -czf <DIST_FILE> -C <build-output-dir> .` — an absolute or `..` entry is
58
+ // refused before anything is unpacked.
59
+ //
60
+ // AUTO-UPDATE (#471) is a timer that runs the same `update`, never a second mechanism. Opt in with
61
+ // `init --auto-update 6h` (seconds, or a number with s/m/h/d; at least 60s), opt out with
62
+ // `init --no-auto-update`; AUTO_UPDATE below sets the default for a first init. macOS: a second
63
+ // launchd agent (<label>.update) with StartInterval. Linux: a systemd user <unit>-update.service
64
+ // (oneshot) plus <unit>-update.timer. Its output goes to update.out.log / update.err.log in the
65
+ // state dir. A pinned install's timer runs and changes nothing ("pinned"), as `update` does.
66
+ //
67
+ // UNINSTALL (#472) unloads the timer and the service, deletes their unit files, the shim (only if
68
+ // this template wrote it) and the whole data dir — every installed version. The config and state
69
+ // dirs stay, so a later init picks up the same config; `--purge` deletes them too.
70
+ //
46
71
  // SERVICE MANAGERS. macOS: a launchd agent in ~/Library/LaunchAgents (bootstrap, kickstart -k).
47
72
  // Linux: a systemd user unit in $XDG_CONFIG_HOME/systemd/user (enable --now, restart). A Linux
48
73
  // service that must outlive the login session needs `loginctl enable-linger` — `init` prints it,
49
74
  // never runs it. <TOOL>_SERVICE_MANAGER=none skips the manager entirely (a container, a unit you
50
75
  // manage yourself). Windows is refused.
51
76
  //
52
- // Node >= 18, zero dependencies; needs `git` (and `npm` for `update`). The unit carries only the
77
+ // Node >= 18, zero dependencies; needs `git` (and `npm` for `update`; `tar` for KIND 'dist'). The unit carries only the
53
78
  // LOCATIONS of config and state (<TOOL>_CONFIG_DIR, <TOOL>_STATE_DIR) — never a secret value.
54
79
 
55
80
  import { spawnSync } from 'node:child_process';
@@ -66,23 +91,33 @@ import * as launcher from './npx-launcher.mjs';
66
91
  // ---- EDIT POINTS ----------------------------------------------------------------------------
67
92
  // 'binary': a compiled tool shipped as dist refs (templates/dist-refs.yml); the service runs the
68
93
  // binary npx-launcher.mjs installs. 'package': a JS app; the service runs ENTRY with node.
94
+ // 'dist': a prebuilt JS app shipped as ONE tarball in the dist ref `dist/vX.Y.Z/any`; the
95
+ // service runs app/ENTRY with node (THREE KINDS, above).
69
96
  const KIND = 'binary';
70
97
  // The launchd label / systemd unit name. null = `local.<tool>` (launchd) and `<tool>` (systemd).
71
98
  const LABEL = null;
72
99
  // Arguments the service is started with (KIND 'binary': the binary's; 'package': ENTRY's).
73
100
  const SERVICE_ARGS = ['serve'];
74
- // KIND 'package': the file node runs, relative to the package root.
101
+ // KIND 'package': the file node runs, relative to the package root. KIND 'dist': relative to the
102
+ // unpacked tarball's root.
75
103
  const ENTRY = 'server.mjs';
104
+ // KIND 'dist': the tarball's name inside the `any` dist ref. null = `<tool>.tgz`.
105
+ const DIST_FILE = null;
106
+ // The auto-update interval a FIRST init uses when no --auto-update/--no-auto-update is given
107
+ // (e.g. '6h'), or null for none. Re-running init keeps whatever the install already records.
108
+ const AUTO_UPDATE = null;
76
109
  // A URL reporting the running version (e.g. http://127.0.0.1:8080/version), or null.
77
110
  const HEALTH_URL = null;
78
111
  // How many versions to keep side by side (current and previous are never pruned).
79
112
  const KEEP = 3;
80
113
  // The verbs this file owns. They shadow the tool's own subcommands of the same names — rename
81
114
  // them here (e.g. 'self-update') if your tool already has an `update`.
82
- const VERBS = { init: 'init', update: 'update', rollback: 'rollback', status: 'status' };
115
+ const VERBS = { init: 'init', update: 'update', rollback: 'rollback', status: 'status', uninstall: 'uninstall' };
83
116
  // ----------------------------------------------------------------------------------------------
84
117
 
85
118
  const here = dirname(fileURLToPath(import.meta.url));
119
+ const DIST_PLAT = 'any';
120
+ const SHIM_MARK = 'npx-service.mjs, #465';
86
121
 
87
122
  /** Every per-user location, from the environment. Pure. */
88
123
  export function paths({ env, home, tool }) {
@@ -109,16 +144,31 @@ export function parseArgs(argv) {
109
144
  const rest = [];
110
145
  for (let i = 0; i < argv.length; i++) {
111
146
  const a = argv[i];
112
- const m = a.match(/^--(check|version|channel|health-url)(?:=(.*))?$/);
147
+ const m = a.match(/^--(check|purge|no-auto-update|version|channel|health-url|auto-update)(?:=(.*))?$/);
113
148
  if (!m) { rest.push(a); continue; }
114
- if (m[1] === 'check') { flags.check = true; continue; }
149
+ const key = m[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());
150
+ if (['check', 'purge', 'noAutoUpdate'].includes(key)) { flags[key] = true; continue; }
115
151
  const v = m[2] !== undefined ? m[2] : argv[++i];
116
152
  if (v === undefined) return { error: `--${m[1]} needs a value` };
117
- flags[m[1] === 'health-url' ? 'healthUrl' : m[1]] = v;
153
+ flags[key] = v;
118
154
  }
119
155
  return { flags, rest };
120
156
  }
121
157
 
158
+ /** `6h` / `30m` / `1d` / `900s` / `900` → seconds; anything else, or under 60s, → null. Pure. */
159
+ export function parseInterval(s) {
160
+ const m = String(s ?? '').trim().match(/^(\d+)\s*([smhd]?)$/i);
161
+ if (!m) return null;
162
+ const n = Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2].toLowerCase()];
163
+ return n >= 60 ? n : null;
164
+ }
165
+
166
+ /** Seconds → the shortest exact `Nd` / `Nh` / `Nm` / `Ns`. Pure. */
167
+ export function formatInterval(sec) {
168
+ for (const [u, n] of [['d', 86400], ['h', 3600], ['m', 60]]) if (sec % n === 0) return `${sec / n}${u}`;
169
+ return `${sec}s`;
170
+ }
171
+
122
172
  /** A git URL npm will install from. */
123
173
  export function npmSpec(origin, version) {
124
174
  let o = origin;
@@ -146,7 +196,9 @@ export function unitSpec({ kind = KIND, tool, name, root, state, config, execPat
146
196
  const cur = join(root, 'current');
147
197
  const programArgs = kind === 'binary'
148
198
  ? [join(cur, plat, tool), ...args]
149
- : [execPath, join(cur, 'pkg', 'node_modules', name, entry), ...args];
199
+ : kind === 'dist'
200
+ ? [execPath, join(cur, 'app', entry), ...args]
201
+ : [execPath, join(cur, 'pkg', 'node_modules', name, entry), ...args];
150
202
  const P = envPrefix(tool);
151
203
  return {
152
204
  label: label || `local.${tool}`,
@@ -175,10 +227,13 @@ ${args}
175
227
  <dict>
176
228
  ${env}
177
229
  </dict>
230
+ ${spec.startInterval ? ` <key>StartInterval</key>
231
+ <integer>${Number(spec.startInterval)}</integer>
178
232
  <key>RunAtLoad</key>
233
+ <false/>` : ` <key>RunAtLoad</key>
179
234
  <true/>
180
235
  <key>KeepAlive</key>
181
- <true/>
236
+ <true/>`}
182
237
  <key>StandardOutPath</key>
183
238
  <string>${xml(spec.logOut)}</string>
184
239
  <key>StandardErrorPath</key>
@@ -206,6 +261,68 @@ WantedBy=default.target
206
261
  `;
207
262
  }
208
263
 
264
+ /** The auto-update timer's oneshot service: runs `update` once, then exits. Pure. */
265
+ export function renderSystemdOneshot(spec) {
266
+ return renderSystemd(spec)
267
+ .replace(/^Restart=on-failure\n/m, '')
268
+ .replace(/^\[Service\]$/m, '[Service]\nType=oneshot')
269
+ .replace(/\n\[Install\]\nWantedBy=default\.target\n$/, '\n');
270
+ }
271
+
272
+ export function renderSystemdTimer(spec) {
273
+ return `[Unit]
274
+ Description=${spec.label} (timer)
275
+
276
+ [Timer]
277
+ OnBootSec=${spec.startInterval}s
278
+ OnUnitActiveSec=${spec.startInterval}s
279
+ Unit=${spec.unitName}
280
+
281
+ [Install]
282
+ WantedBy=timers.target
283
+ `;
284
+ }
285
+
286
+ /**
287
+ * The auto-update timer's spec: `<this manager at current> update`, every `interval` seconds,
288
+ * with the same XDG bases the install was made under (a launchd/systemd job does not inherit the
289
+ * shell's), so the update it runs finds the same install. Pure.
290
+ */
291
+ export function timerSpec({ spec, tool, name, p, execPath, serviceRel, interval, verbs = VERBS }) {
292
+ const base = spec.unitName.replace(/\.service$/, '');
293
+ return {
294
+ label: `${spec.label}.update`,
295
+ unitName: `${base}-update.service`,
296
+ timerName: `${base}-update.timer`,
297
+ startInterval: interval,
298
+ programArgs: [execPath, join(p.root, 'current', 'pkg', 'node_modules', name, serviceRel), verbs.update],
299
+ env: {
300
+ ...spec.env,
301
+ XDG_DATA_HOME: dirname(p.root), XDG_CONFIG_HOME: dirname(p.config), XDG_STATE_HOME: dirname(p.state),
302
+ },
303
+ logOut: join(p.state, 'update.out.log'),
304
+ logErr: join(p.state, 'update.err.log'),
305
+ };
306
+ }
307
+
308
+ /** The timer's unit files and the manager's argv to load / unload it. Pure. */
309
+ export function timerCommands(platform, { uid, tspec, p }) {
310
+ if (platform === 'darwin') {
311
+ const unitPath = join(p.launchAgents, `${tspec.label}.plist`);
312
+ const target = `gui/${uid}/${tspec.label}`;
313
+ return {
314
+ files: [[unitPath, renderLaunchd(tspec)]],
315
+ load: [['launchctl', 'bootout', target, '?'], ['launchctl', 'bootstrap', `gui/${uid}`, unitPath]],
316
+ unload: [['launchctl', 'bootout', target, '?']],
317
+ };
318
+ }
319
+ return {
320
+ files: [[join(p.systemdDir, tspec.unitName), renderSystemdOneshot(tspec)], [join(p.systemdDir, tspec.timerName), renderSystemdTimer(tspec)]],
321
+ load: [['systemctl', '--user', 'daemon-reload'], ['systemctl', '--user', 'enable', '--now', tspec.timerName]],
322
+ unload: [['systemctl', '--user', 'disable', '--now', tspec.timerName, '?']],
323
+ };
324
+ }
325
+
209
326
  /** The unit file's path and the manager's argv for each step. Pure. */
210
327
  export function managerCommands(platform, { uid, spec, p }) {
211
328
  if (platform === 'darwin') {
@@ -216,6 +333,7 @@ export function managerCommands(platform, { uid, spec, p }) {
216
333
  render: renderLaunchd,
217
334
  load: [['launchctl', 'bootout', target, '?'], ['launchctl', 'bootstrap', `gui/${uid}`, unitPath]],
218
335
  unload: [['launchctl', 'bootout', target, '?']],
336
+ forget: [],
219
337
  restart: [['launchctl', 'kickstart', '-k', target]],
220
338
  status: ['launchctl', 'print', target],
221
339
  running: (r) => r.status === 0 && /\bstate = running\b/.test(r.stdout || ''),
@@ -227,6 +345,7 @@ export function managerCommands(platform, { uid, spec, p }) {
227
345
  render: renderSystemd,
228
346
  load: [['systemctl', '--user', 'daemon-reload'], ['systemctl', '--user', 'enable', '--now', spec.unitName]],
229
347
  unload: [['systemctl', '--user', 'disable', '--now', spec.unitName, '?']],
348
+ forget: [['systemctl', '--user', 'daemon-reload', '?']],
230
349
  restart: [['systemctl', '--user', 'restart', spec.unitName]],
231
350
  status: ['systemctl', '--user', 'is-active', spec.unitName],
232
351
  running: (r) => r.status === 0,
@@ -239,9 +358,11 @@ export function renderShim({ kind = KIND, root, tool, name, plat, execPath, entr
239
358
  const manager = `${cur}/pkg/node_modules/${name}/${serviceRel}`;
240
359
  const payload = kind === 'binary'
241
360
  ? `exec ${cur}/${plat}/${tool} "$@"`
242
- : `exec ${shq(execPath)} ${cur}/pkg/node_modules/${name}/${entry} "$@"`;
361
+ : kind === 'dist'
362
+ ? `exec ${shq(execPath)} ${cur}/app/${entry} "$@"`
363
+ : `exec ${shq(execPath)} ${cur}/pkg/node_modules/${name}/${entry} "$@"`;
243
364
  return `#!/bin/sh
244
- # Written by \`${tool} ${verbs.init}\` (npx-service.mjs, #465). Re-run init to rewrite it.
365
+ # Written by \`${tool} ${verbs.init}\` (${SHIM_MARK}). Re-run init to rewrite it.
245
366
  ROOT=${shq(root)}
246
367
  case "\${1:-}" in
247
368
  ${Object.values(verbs).join('|')}) exec ${shq(execPath)} ${manager} "$@" ;;
@@ -365,18 +486,42 @@ export async function switchTo({ to, root, mgr, url, io }) {
365
486
  }
366
487
 
367
488
  /** Is `root/version` a complete install for this kind? */
368
- function complete({ root, version, kind, name, tool, plat }) {
489
+ function complete({ root, version, kind, name, tool, plat, entry = ENTRY }) {
369
490
  const v = join(root, version);
370
491
  if (!existsSync(join(v, 'pkg', 'node_modules', name, 'package.json'))) return false;
492
+ if (kind === 'dist') return existsSync(join(v, 'app', entry));
371
493
  return kind !== 'binary' || existsSync(join(v, plat, tool));
372
494
  }
373
495
 
496
+ /** A tarball listing → the first entry that would land outside its target dir, or null. Pure. */
497
+ export function unsafeEntry(listing) {
498
+ for (const e of String(listing || '').split('\n').map((l) => l.trim()).filter(Boolean)) {
499
+ if (e.startsWith('/') || e.split('/').includes('..')) return e;
500
+ }
501
+ return null;
502
+ }
503
+
504
+ /** KIND 'dist': fetch + verify the tarball from `dist/<version>/any`, unpack it into `dir`. */
505
+ export function installDist({ origin, version, dir, file, entry = ENTRY, io }) {
506
+ const tgz = launcher.fetchDistFile({ origin, version, plat: DIST_PLAT, file, dest: join(dirname(dir), `.${file}`), mode: 0o644 });
507
+ try {
508
+ const ls = io.run('tar', ['-tzf', tgz]);
509
+ if (ls.status !== 0) throw new Error(`${file} in dist/${version}/${DIST_PLAT} is not a gzip tarball: ${(ls.stderr || '').trim()}`);
510
+ const bad = unsafeEntry(ls.stdout);
511
+ if (bad) throw new Error(`${file} in dist/${version}/${DIST_PLAT} has an entry outside its root (${bad}) — refusing to unpack it`);
512
+ mkdirSync(dir, { recursive: true });
513
+ const x = io.run('tar', ['-xzf', tgz, '-C', dir]);
514
+ if (x.status !== 0) throw new Error(`could not unpack ${file}: ${(x.stderr || '').trim()}`);
515
+ } finally { rmSync(tgz, { force: true }); }
516
+ if (!existsSync(join(dir, entry))) throw new Error(`${version}: ${file} has no ${entry} at its top level`);
517
+ }
518
+
374
519
  /**
375
520
  * Install `version` side by side, into a temp dir renamed into place — a failure leaves nothing
376
521
  * behind. `fromPkg` (init) copies the package npx already unpacked; otherwise npm fetches it.
377
522
  */
378
- export function installVersion({ kind = KIND, version, origin, root, name, tool, plat, fromPkg, io }) {
379
- if (complete({ root, version, kind, name, tool, plat })) return join(root, version);
523
+ export function installVersion({ kind = KIND, version, origin, root, name, tool, plat, fromPkg, entry = ENTRY, distFile, io }) {
524
+ if (complete({ root, version, kind, name, tool, plat, entry })) return join(root, version);
380
525
  mkdirSync(root, { recursive: true });
381
526
  const tmp = join(root, `.install-${version}-${process.pid}`);
382
527
  rmSync(tmp, { recursive: true, force: true });
@@ -393,6 +538,9 @@ export function installVersion({ kind = KIND, version, origin, root, name, tool,
393
538
  if (kind === 'binary') {
394
539
  launcher.install({ origin, version, plat, exe: tool, dir: join(tmp, plat) });
395
540
  }
541
+ if (kind === 'dist') {
542
+ installDist({ origin, version, dir: join(tmp, 'app'), file: distFile || `${tool}.tgz`, entry, io });
543
+ }
396
544
  rmSync(join(root, version), { recursive: true, force: true });
397
545
  renameSync(tmp, join(root, version));
398
546
  return join(root, version);
@@ -413,27 +561,55 @@ function context(opts, io) {
413
561
  });
414
562
  const managed = io.env[`${P}_SERVICE_MANAGER`] !== 'none';
415
563
  const mgr = managed ? managerCommands(io.platform, { uid: io.uid, spec, p }) : null;
416
- return { tool, p, P, plat, spec, mgr };
564
+ // The timer's unit files are known whatever the interval (uninstall and opt-out remove them).
565
+ const tspec = timerSpec({ spec, tool, name: opts.name, p, execPath: io.execPath, serviceRel: opts.serviceRel || 'service.mjs', interval: 0 });
566
+ const timer = managed ? timerCommands(io.platform, { uid: io.uid, tspec, p }) : null;
567
+ return { tool, p, P, plat, spec, mgr, timer, tspec };
417
568
  }
418
569
 
419
570
  function healthUrl(rec, P, io, flags = {}) {
420
571
  return flags.healthUrl || io.env[`${P}_HEALTH_URL`] || (rec && rec.healthUrl) || HEALTH_URL;
421
572
  }
422
573
 
423
- function writeUnit(c, io) {
574
+ function readText(f) {
575
+ try { return readFileSync(f, 'utf8'); } catch { return null; }
576
+ }
577
+
578
+ function writeUnit(c, io, rec) {
424
579
  if (!c.mgr) return false;
425
580
  const text = c.mgr.render(c.spec);
426
- let old = null;
427
- try { old = readFileSync(c.mgr.unitPath, 'utf8'); } catch { /* none yet */ }
428
- if (old === text) return false;
429
- mkdirSync(dirname(c.mgr.unitPath), { recursive: true });
430
- writeFileSync(c.mgr.unitPath, text);
431
- ctl(io, c.mgr.load);
581
+ if (readText(c.mgr.unitPath) !== text) {
582
+ mkdirSync(dirname(c.mgr.unitPath), { recursive: true });
583
+ writeFileSync(c.mgr.unitPath, text);
584
+ ctl(io, c.mgr.load);
585
+ }
586
+ writeTimer(c, io, rec && rec.autoUpdate);
432
587
  return true;
433
588
  }
434
589
 
590
+ /** Write (and load) the auto-update timer for `interval` seconds — or remove it when falsy. */
591
+ function writeTimer(c, io, interval) {
592
+ if (!c.timer) return;
593
+ if (!interval) { removeTimer(c, io); return; }
594
+ const t = timerCommands(io.platform, { uid: io.uid, tspec: { ...c.tspec, startInterval: interval }, p: c.p });
595
+ if (t.files.every(([f, text]) => readText(f) === text)) return;
596
+ for (const [f, text] of t.files) { mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, text); }
597
+ ctl(io, t.load);
598
+ }
599
+
600
+ /** Unload the timer and delete its unit files, if any are there. Returns the files removed. */
601
+ function removeTimer(c, io) {
602
+ if (!c.timer) return [];
603
+ const present = c.timer.files.map(([f]) => f).filter((f) => existsSync(f));
604
+ if (!present.length) return [];
605
+ ctl(io, c.timer.unload);
606
+ for (const f of present) rmSync(f, { force: true });
607
+ ctl(io, c.mgr.forget);
608
+ return present;
609
+ }
610
+
435
611
  /**
436
- * One verb. opts: { tool, name, kind, pkgDir, serviceRel, label, args, entry }. Returns an exit code.
612
+ * One verb. opts: { tool, name, kind, pkgDir, serviceRel, label, args, entry, distFile }. Returns an exit code.
437
613
  * Every refusal happens before anything is written.
438
614
  */
439
615
  export async function run(verb, argv, opts, io) {
@@ -452,9 +628,12 @@ async function runVerb(verb, argv, opts, io) {
452
628
  const { flags } = a;
453
629
  if (flags.channel && !launcher.CHANNELS.includes(flags.channel)) { io.err(`--channel must be one of ${launcher.CHANNELS.join(', ')}`); return 1; }
454
630
  if (flags.version && !launcher.VERSION_RE.test(flags.version)) { io.err(`--version must be vX.Y.Z or vX.Y.Z-rc.N (got ${flags.version})`); return 1; }
631
+ if (flags.autoUpdate !== undefined && !parseInterval(flags.autoUpdate)) { io.err(`--auto-update must be seconds, or a number with s/m/h/d, at least 60s (got ${flags.autoUpdate})`); return 1; }
632
+ if (flags.autoUpdate !== undefined && flags.noAutoUpdate) { io.err('--auto-update and --no-auto-update contradict each other'); return 1; }
455
633
  const kind = opts.kind || KIND;
456
634
  const c = context({ ...opts, kind }, io);
457
635
  const rec = readInstall(c.p);
636
+ const inst = { kind, name: opts.name, tool: c.tool, plat: c.plat, entry: opts.entry, distFile: opts.distFile, io };
458
637
 
459
638
  if (verb === VERBS.status) {
460
639
  if (!rec) { io.err(`not installed — run \`npx <origin>#vX.Y.Z ${VERBS.init}\``); return 1; }
@@ -465,11 +644,14 @@ async function runVerb(verb, argv, opts, io) {
465
644
  `origin: ${rec.origin}`,
466
645
  `versions: ${installedVersions(c.p.root).join(' ') || '—'}`,
467
646
  `unit: ${c.mgr ? c.mgr.unitPath : '(no service manager)'}`,
647
+ `auto-update: ${rec.autoUpdate ? `every ${formatInterval(rec.autoUpdate)}` : 'off'}`,
468
648
  `node: ${io.execPath}`,
469
649
  ].join('\n'));
470
650
  return 0;
471
651
  }
472
652
 
653
+ if (verb === VERBS.uninstall) return uninstall(c, flags, io);
654
+
473
655
  if (verb === VERBS.init) {
474
656
  const pkg = readJson(join(opts.pkgDir, 'package.json')) || {};
475
657
  const t = launcher.resolveTarget({ env: io.env, pkgDir: opts.pkgDir, pkg });
@@ -482,10 +664,13 @@ async function runVerb(verb, argv, opts, io) {
482
664
  const npxRoot = launcher.installerRoot(opts.pkgDir, opts.name);
483
665
  if (!npxRoot) { io.err(`run init through npx: \`npx <origin>#${t.version} ${VERBS.init}\` (no installing project above ${opts.pkgDir})`); return 1; }
484
666
  return withLock(c.p.state, async () => {
485
- installVersion({ kind, version: t.version, origin: t.origin, root: c.p.root, name: opts.name, tool: c.tool, plat: c.plat, fromPkg: npxRoot, io });
667
+ installVersion({ ...inst, version: t.version, origin: t.origin, root: c.p.root, fromPkg: npxRoot });
486
668
  const record = rec || { origin: t.origin, channel: flags.channel || t.channel || 'stable' };
487
669
  if (flags.channel) record.channel = flags.channel;
488
670
  if (flags.healthUrl) record.healthUrl = flags.healthUrl;
671
+ if (!rec && AUTO_UPDATE && parseInterval(AUTO_UPDATE)) record.autoUpdate = parseInterval(AUTO_UPDATE);
672
+ if (flags.autoUpdate !== undefined) record.autoUpdate = parseInterval(flags.autoUpdate);
673
+ if (flags.noAutoUpdate) delete record.autoUpdate;
489
674
  writeInstall(c.p, record);
490
675
  mkdirSync(c.p.state, { recursive: true, mode: 0o700 });
491
676
  mkdirSync(dirname(c.p.shim), { recursive: true });
@@ -493,16 +678,17 @@ async function runVerb(verb, argv, opts, io) {
493
678
  chmodSync(c.p.shim, 0o755);
494
679
  const first = !readLink(c.p.root, 'current');
495
680
  if (first) pointTo(c.p.root, 'current', t.version); // the unit must find something at load
496
- writeUnit(c, io);
681
+ writeUnit(c, io, record);
497
682
  const s = first
498
683
  ? { ok: await healthy({ version: t.version, url: healthUrl(record, c.P, io), mgr: c.mgr, io }), to: t.version }
499
684
  : await switchTo({ to: t.version, root: c.p.root, mgr: c.mgr, url: healthUrl(record, c.P, io), io });
500
685
  if (!s.ok) {
501
- if (first && c.mgr) ctl(io, c.mgr.unload);
686
+ if (first && c.mgr) { removeTimer(c, io); ctl(io, c.mgr.unload); }
502
687
  io.err(first ? `${t.version} installed but not healthy — service unloaded; see ${c.p.state}` : `${t.version} not healthy — switched back to ${s.from}`);
503
688
  return 1;
504
689
  }
505
690
  io.out(`${c.tool} ${t.version} installed and running (channel ${record.channel}); shim ${c.p.shim}`);
691
+ if (record.autoUpdate) io.out(c.timer ? `auto-update: \`${VERBS.update}\` every ${formatInterval(record.autoUpdate)}; log ${c.tspec.logOut}` : 'auto-update recorded, but no service manager is in use — no timer written');
506
692
  if (io.platform === 'linux' && c.mgr) io.out(`to keep it running after logout: loginctl enable-linger ${io.env.USER || '$USER'}`);
507
693
  return 0;
508
694
  });
@@ -542,9 +728,9 @@ async function runVerb(verb, argv, opts, io) {
542
728
  if (channel !== rec.channel) writeInstall(c.p, { ...rec, channel });
543
729
  if (target === cur) { io.out(`up to date: ${cur}`); return 0; }
544
730
  try {
545
- installVersion({ kind, version: target, origin: rec.origin, root: c.p.root, name: opts.name, tool: c.tool, plat: c.plat, io });
731
+ installVersion({ ...inst, version: target, origin: rec.origin, root: c.p.root });
546
732
  } catch (e) { io.err(`${e.message}\nnothing switched — still on ${cur}`); return 1; }
547
- writeUnit(c, io);
733
+ writeUnit(c, io, rec);
548
734
  const s = await switchTo({ to: target, root: c.p.root, mgr: c.mgr, url, io });
549
735
  if (!s.ok) { io.err(`${target} not healthy — switched back to ${s.from}${s.backHealthy ? '' : ' (which is not reporting healthy either)'}`); return 1; }
550
736
  const gone = prune(c.p.root);
@@ -553,6 +739,44 @@ async function runVerb(verb, argv, opts, io) {
553
739
  });
554
740
  }
555
741
 
742
+ /**
743
+ * Unload and delete the timer and the service unit, the shim (only one this template wrote) and
744
+ * the data dir. Config and state stay unless `--purge`. Safe to re-run: what is gone is skipped.
745
+ */
746
+ function uninstall(c, flags, io) {
747
+ const shimText = readText(c.p.shim);
748
+ const ours = shimText !== null && shimText.includes(SHIM_MARK);
749
+ const unit = c.mgr && existsSync(c.mgr.unitPath);
750
+ const timerFiles = c.timer ? c.timer.files.map(([f]) => f).filter((f) => existsSync(f)) : [];
751
+ const data = existsSync(c.p.root);
752
+ const keep = [c.p.config, c.p.state].filter((d) => existsSync(d));
753
+ if (!ours && !unit && !timerFiles.length && !data && !(flags.purge && keep.length)) {
754
+ io.out(`nothing to uninstall — no ${c.tool} install found`);
755
+ return 0;
756
+ }
757
+ const removed = [];
758
+ const work = () => {
759
+ removed.push(...removeTimer(c, io));
760
+ if (unit) {
761
+ ctl(io, c.mgr.unload);
762
+ rmSync(c.mgr.unitPath, { force: true });
763
+ ctl(io, c.mgr.forget);
764
+ removed.push(c.mgr.unitPath);
765
+ }
766
+ if (ours) { rmSync(c.p.shim, { force: true }); removed.push(c.p.shim); }
767
+ if (data) { rmSync(c.p.root, { recursive: true, force: true }); removed.push(c.p.root); }
768
+ };
769
+ // Under the update lock, so a timer-started update cannot install into what is being deleted.
770
+ if (existsSync(c.p.state)) withLock(c.p.state, work); else work();
771
+ if (flags.purge) {
772
+ for (const d of keep) { rmSync(d, { recursive: true, force: true }); removed.push(d); }
773
+ }
774
+ io.out(`${c.tool} uninstalled. removed:\n${removed.map((r) => ` ${r}`).join('\n')}`);
775
+ if (shimText !== null && !ours) io.out(`left ${c.p.shim} in place — this template did not write it`);
776
+ if (!flags.purge && keep.length) io.out(`kept (config and state; \`${VERBS.uninstall} --purge\` deletes them):\n${keep.map((d) => ` ${d}`).join('\n')}`);
777
+ return 0;
778
+ }
779
+
556
780
  export function defaultIo(env = process.env) {
557
781
  return {
558
782
  env,
@@ -581,13 +805,19 @@ async function main(argv) {
581
805
  if (!Object.values(VERBS).includes(verb)) {
582
806
  // Not ours: the tool's own command line, run from the CURRENT install — never from npx's cache.
583
807
  if (KIND === 'binary') return launcher.main(argv, here);
584
- const r = spawnSync(process.execPath, [join(pkgDir, ENTRY), ...argv], { stdio: 'inherit' });
808
+ let entry = join(pkgDir, ENTRY);
809
+ if (KIND === 'dist') {
810
+ // The prebuilt app is not in the package — it exists only in an install.
811
+ entry = join(paths({ env: process.env, home: process.env.HOME || homedir(), tool }).root, 'current', 'app', ENTRY);
812
+ if (!existsSync(entry)) { process.stderr.write(`npx-service: ${tool} is not installed — run \`npx <origin>#vX.Y.Z ${VERBS.init}\` first\n`); return 1; }
813
+ }
814
+ const r = spawnSync(process.execPath, [entry, ...argv], { stdio: 'inherit' });
585
815
  return r.status ?? 1;
586
816
  }
587
817
  const io = defaultIo(process.env);
588
818
  const ms = Number(process.env[`${envPrefix(tool)}_HEALTH_TIMEOUT_MS`]);
589
819
  if (ms) io.timing.timeoutMs = ms;
590
- return run(verb, argv.slice(1), { tool, name, kind: KIND, pkgDir, serviceRel: relative(pkgDir, fileURLToPath(import.meta.url)) }, io);
820
+ return run(verb, argv.slice(1), { tool, name, kind: KIND, pkgDir, distFile: DIST_FILE, serviceRel: relative(pkgDir, fileURLToPath(import.meta.url)) }, io);
591
821
  }
592
822
 
593
823
  function isEntry() {
package/tools/colab CHANGED
@@ -9738,7 +9738,9 @@ Options:
9738
9738
  warning). --dry prints "Machine trailer: …" saying which way it will go.
9739
9739
  --refs <N[,M]> reference these claimed issues (Refs #N) instead of closing them — for a
9740
9740
  long-lived memory/tracking issue the branch touched but did not complete.
9741
- Comma-separated; each must be a claimed issue on the branch. An issue carrying
9741
+ Comma-separated, and repeatable: --refs A --refs B is --refs A,B (#479 —
9742
+ every other value flag to ship refuses a repeat). Each must be a claimed
9743
+ issue on the branch. An issue carrying
9742
9744
  the "tracking" label is treated this way automatically, no flag needed. The
9743
9745
  claim is still released either way — only Closes→Refs changes.
9744
9746
  #385: a --refs'd issue whose body still has an unticked "- [ ]" box (under
@@ -11513,6 +11515,8 @@ function cmdShipDirect(opts) {
11513
11515
  print(preOk ? '→ READY: preconditions pass. Re-run without --dry to close.' : '→ NOT READY: fix the ✗ rows above.');
11514
11516
  print(' Plan: no merge, no commit, no push · post evidence comment + CLOSE each issue · release the claims (and the checkout hold)');
11515
11517
  print(' Gate: every closing issue must already carry an evidence comment — checked at run time.');
11518
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
11519
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
11516
11520
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
11517
11521
  return preOk ? 0 : 1;
11518
11522
  }
@@ -11736,7 +11740,13 @@ function shipRefFor(repoAbs, branch) {
11736
11740
 
11737
11741
  function cmdShip(argv) {
11738
11742
  const opts = parseArgs(argv, {
11739
- values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--refs': 'refs', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
11743
+ values: { '--repo': 'repo', '--worktree': 'worktree', '--branch': 'branch', '--message': 'message', '--session': 'session', '--session-name': 'sessionName', '--batch': 'batch' },
11744
+ // #479: a repeated --refs used to keep only its LAST value, and every dropped issue then became a
11745
+ // `Closes` line on trunk — an issue meant to stay open, auto-closed by the push. --refs now
11746
+ // accumulates (a repeat is the same as one comma list); every OTHER value flag to ship refuses a
11747
+ // repeat (`once`), checked here before any git or GitHub call.
11748
+ lists: { '--refs': 'refs' },
11749
+ once: true,
11740
11750
  flags: { '--keep-worktree': 'keepWorktree', '--delete-branch': 'deleteBranch', '--keep-branch': 'keepBranch', '--dry': 'dry', '--json': 'json', '--direct': 'direct', '--adopt': 'adopt', '-h': 'help', '--help': 'help' },
11741
11751
  });
11742
11752
  if (opts.help) return print(HELP_SHIP);
@@ -12180,6 +12190,8 @@ function cmdShip(argv) {
12180
12190
  print(` ✗ "${c.keyword} #${c.num}" would close #${c.num} on merge — kept open by --refs; reword the commit before shipping.`);
12181
12191
  }
12182
12192
  }
12193
+ // #479: show BOTH halves of the split, so a wrong one is visible before the push.
12194
+ if (closeIssues.length) print(` Closes (closed by this ship): ${closeIssues.map((n) => '#' + n).join(' ')}`);
12183
12195
  if (refsIssues.length) print(` Refs (kept open, NOT closed): ${refsIssues.map((n) => '#' + n).join(' ')}`);
12184
12196
  return dryOk ? 0 : 1;
12185
12197
  }
package/tools/lib/util.js CHANGED
@@ -51,12 +51,19 @@ function humanAge(iso) {
51
51
  * spec.flags : { '--json': 'json', '--force': 'force' } boolean flags
52
52
  * spec.values : { '--repo': 'repo', '--count': 'count' } flags that take a value
53
53
  * spec.aliases : { '--issue': '--issues' } map an alias to its canonical flag
54
+ * spec.lists : { '--refs': 'refs' } value flags that ACCUMULATE: a repeat is
55
+ * joined onto the earlier value(s) with ',' — the same as one comma list (#479)
56
+ * spec.once : true a repeated `values` flag is a usage error
57
+ * instead of last-one-wins (#479). Off by default: most commands keep the old
58
+ * overwrite, where a dropped value is harmless; turn it on where it is not.
54
59
  * Positionals collected into result._ .
55
60
  */
56
61
  function parseArgs(argv, spec = {}) {
57
62
  const flags = spec.flags || {};
58
63
  const values = spec.values || {};
59
64
  const aliases = spec.aliases || {};
65
+ const lists = spec.lists || {};
66
+ const seen = new Set();
60
67
  const out = { _: [] };
61
68
  for (let i = 0; i < argv.length; i++) {
62
69
  let a = argv[i];
@@ -66,9 +73,18 @@ function parseArgs(argv, spec = {}) {
66
73
  const eq = a.indexOf('=');
67
74
  if (a.startsWith('--') && eq !== -1) { inlineVal = a.slice(eq + 1); a = a.slice(0, eq); }
68
75
  if (flags[a]) { out[flags[a]] = true; }
69
- else if (values[a]) {
76
+ else if (lists[a]) {
70
77
  const v = inlineVal !== null ? inlineVal : argv[++i];
71
78
  if (v === undefined) throw new UserError(`Option ${a} needs a value`);
79
+ const k = lists[a];
80
+ out[k] = out[k] === undefined ? v : `${out[k]},${v}`;
81
+ } else if (values[a]) {
82
+ const v = inlineVal !== null ? inlineVal : argv[++i];
83
+ if (v === undefined) throw new UserError(`Option ${a} needs a value`);
84
+ if (spec.once && seen.has(values[a])) {
85
+ throw new UserError(`Option ${a} given more than once — only one value is accepted; pass it once`);
86
+ }
87
+ seen.add(values[a]);
72
88
  out[values[a]] = v;
73
89
  } else if (a.startsWith('-') && a !== '-') {
74
90
  throw new UserError(`Unknown option: ${a}`);