@anhlp/alp-cli 0.0.1-beta.6 → 0.0.1-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/library.js CHANGED
@@ -4,15 +4,26 @@ import { parseArgs } from 'node:util';
4
4
  import { seedLibrary } from '@anhlp/alp-core/library';
5
5
  import { libraryEntries } from '@anhlp/alp-core/resolver';
6
6
  import { listTeams, resolveTeam } from '@anhlp/alp-core/teams';
7
- import { deleteEntry, duplicateEntry, getEntry, renameEntry, saveEntry } from '@anhlp/alp-core/library-edit';
7
+ import { deleteEntry, duplicateEntry, getEntry, listRetiredSkills, renameEntry, restoreSkill, saveEntry, withSkillName } from '@anhlp/alp-core/library-edit';
8
8
  import { testEntry } from '@anhlp/alp-client/library-test';
9
+ import { formatValidation, validateSkill } from '@anhlp/alp-core/skill-validate';
10
+ import { installPack, listPacks, packStatus } from '@anhlp/alp-core/packs';
9
11
  import { alpHome } from '@anhlp/alp-client/index';
10
12
  import { UsageError } from './usage.js';
11
13
  import { taskProject } from './tasks.js';
12
14
 
13
15
  async function libraryCommand(kind, args) {
14
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
16
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' }, ...(kind === 'skills' ? { retired: { type: 'boolean' } } : {}) } });
15
17
  if (positionals.length) throw new UsageError();
18
+ if (values.retired) {
19
+ if (values.project !== undefined) throw new UsageError();
20
+ const rows = await listRetiredSkills({ library: alpHome() });
21
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
22
+ if (!rows.length) { console.log(`No retired skills in ${path.join(alpHome(), 'retired-skills')}`); return; }
23
+ const width = Math.max(...rows.map(row => row.name.length));
24
+ for (const row of rows) console.log(`${row.name.padEnd(width)} ${row.retiredAt} ${row.roles === null ? 'roles not recorded' : `roles: ${row.roles.join(', ') || 'none'}`}${row.agent ? `; by ${row.agent}` : ''}${row.invalid ? `; warning: invalid retired metadata: ${row.invalid}` : ''} ${row.directory}`);
25
+ return;
26
+ }
16
27
  if (kind === 'providers') await seedLibrary(alpHome());
17
28
  // Outside a project only the built-ins and the library apply.
18
29
  const root = path.resolve(values.project ?? process.cwd());
@@ -57,12 +68,11 @@ const EDIT_OPTIONS = {
57
68
  'member-thinking': { type: 'string', multiple: true }, delegate: { type: 'string', multiple: true }, 'max-peers': { type: 'string' },
58
69
  supervisor: { type: 'string' }, 'supervisor-model': { type: 'string' }, 'supervisor-thinking': { type: 'string' }, 'no-supervisor': { type: 'boolean' }, rules: { type: 'string' },
59
70
  // skill, mcp, hook
60
- file: { type: 'string' }, command: { type: 'string' }, arg: { type: 'string', multiple: true }, env: { type: 'string', multiple: true }, cwd: { type: 'string' },
71
+ file: { type: 'string' }, roles: { type: 'string' }, 'no-roles': { type: 'boolean' }, command: { type: 'string' }, arg: { type: 'string', multiple: true }, env: { type: 'string', multiple: true }, cwd: { type: 'string' },
61
72
  url: { type: 'string' }, header: { type: 'string', multiple: true }, event: { type: 'string' }, blocking: { type: 'boolean' }, timeout: { type: 'string' },
62
- 'match-agent': { type: 'string' }, 'match-label': { type: 'string' },
73
+ 'match-agent': { type: 'string' }, 'match-label': { type: 'string' }, strict: { type: 'boolean' },
63
74
  // provider
64
75
  kind: { type: 'string' },
65
- 'read-only-mode': { type: 'string' },
66
76
  models: { type: 'string' },
67
77
  };
68
78
 
@@ -115,7 +125,7 @@ async function edited(kind, name, current, values) {
115
125
  if (values.rules !== undefined) content.houseRules = await readFile(values.rules, 'utf8');
116
126
  } else if (kind === 'skills') {
117
127
  if (values.file !== undefined) content.body = await readFile(values.file, 'utf8');
118
- content.body ??= `---\nname: ${name}\ndescription: When to use this skill.\n---\n\n# ${name}\n\nSteps and checks.\n`;
128
+ content.body ??= `---\nname: ${name}\ndescription: ${JSON.stringify(values.description ?? `What ${name} does. Use when the work it is for comes up.`)}\n---\n\n# ${name}\n\n## When to use\n\n## Workflow\n\n## Verification\n`;
119
129
  } else if (kind === 'mcp') {
120
130
  if (values.command !== undefined || values.url !== undefined) content.server = {};
121
131
  const server = content.server ?? {};
@@ -151,7 +161,7 @@ async function edited(kind, name, current, values) {
151
161
  set(provider, 'label', values.label);
152
162
  set(provider, 'description', values.description);
153
163
  set(provider, 'command', values.command);
154
- set(provider, 'readOnlyMode', values['read-only-mode']);
164
+ delete provider.readOnlyMode; // Drop the retired no-op setting when saving an existing definition.
155
165
  if (values.arg?.length) provider.args = values.arg;
156
166
  if (values.env?.length) provider.env = pairs(values.env, '--env');
157
167
  const models = names(values.models);
@@ -161,11 +171,50 @@ async function edited(kind, name, current, values) {
161
171
  return content;
162
172
  }
163
173
 
174
+ /**
175
+ * alp skill check [name|DIR] [--project [DIR]] [--strict] [--json]: validates skills (Agent Skills
176
+ * format, packages/core/src/skill-validate.js). Without a name, every skill the project and the
177
+ * library hold; a name, the one that applies; a path, that directory. Existing skills are checked in
178
+ * legacy mode (format problems are warnings) unless --strict. Reads only; exit 1 on an error.
179
+ */
180
+ async function checkSkills(name, positionals, values) {
181
+ if (positionals.length > 2) throw new UsageError();
182
+ const root = path.resolve(values.project ?? process.cwd());
183
+ const mode = values.strict ? 'strict' : 'legacy';
184
+ let targets;
185
+ if (name !== undefined && (name.includes('/') || name.includes(path.sep) || name.startsWith('.'))) targets = [path.resolve(name)];
186
+ else {
187
+ const rows = await libraryEntries('skills', root, { library: alpHome() });
188
+ const chosen = name === undefined ? rows : rows.filter(row => row.name === name);
189
+ if (name !== undefined && !chosen.length) throw new Error(`No skill '${name}' in ${path.join(root, '.alp', 'skills')} or ${path.join(alpHome(), 'skills')}`);
190
+ targets = chosen.map(row => path.dirname(row.path));
191
+ }
192
+ const reports = [];
193
+ for (const target of targets) reports.push(await validateSkill(target, { mode }));
194
+ if (values.json) console.log(JSON.stringify(reports));
195
+ else {
196
+ for (const report of reports) console.log(formatValidation(report));
197
+ const failed = reports.filter(report => !report.ok).length;
198
+ const warned = reports.filter(report => report.warnings.length).length;
199
+ console.log(`${reports.length} skill${reports.length === 1 ? '' : 's'} checked (${mode}): ${failed} with errors, ${warned} with warnings.${mode === 'legacy' && warned ? ' Warnings do not stop a skill from loading; fix them when you next edit it.' : ''}`);
200
+ }
201
+ if (reports.some(report => !report.ok)) process.exitCode = 1;
202
+ }
203
+
164
204
  /** alp agent|team|skill|mcp|hook: create, change, copy, rename, remove and test library entries. */
165
205
 
166
206
  async function editCommand(kind, args) {
207
+ if (kind === 'providers' && args.some(arg => arg === '--read-only-mode' || arg.startsWith('--read-only-mode='))) throw new Error('--read-only-mode was removed; delete readOnlyMode from provider JSON and choose the session --mode read-only, workspace-write or full-access. Existing native sessions keep their mode.');
167
208
  const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: EDIT_OPTIONS });
168
209
  const [action, name, target] = positionals;
210
+ if (kind === 'skills' && action === 'restore') {
211
+ if (!name || positionals.length > 2 || values.project !== undefined || (values.roles !== undefined && values['no-roles'])) throw new UsageError();
212
+ const roles = values['no-roles'] ? [] : names(values.roles);
213
+ const result = await restoreSkill(name, { library: alpHome(), from: values.from, roles });
214
+ console.log(values.json ? JSON.stringify(result) : `Restored ${name} to ${result.restored} from ${result.from}; ${result.roles.length ? `given to ${result.roles.join(', ')}` : 'given to no role'}.`);
215
+ return;
216
+ }
217
+ if (kind === 'skills' && action === 'check') { await checkSkills(name, positionals, values); return; }
169
218
  if (kind === 'providers' && action !== 'add') await seedLibrary(alpHome());
170
219
  const creates = { agents: 'new', teams: 'new', skills: 'new', mcp: 'add', hooks: 'add', providers: 'add' }[kind];
171
220
  if (!name || positionals.length > (['cp', 'mv'].includes(action) ? 3 : 2) || (['cp', 'mv'].includes(action) && !target)) throw new UsageError();
@@ -208,6 +257,8 @@ async function editCommand(kind, args) {
208
257
  let revision = null;
209
258
  if (action === creates) {
210
259
  if (values.from !== undefined) current = (await getEntry(kind, values.from, { root, library: alpHome() })).content;
260
+ // A skill made from another names itself, as its directory does.
261
+ if (kind === 'skills' && current?.body !== undefined) current = { ...current, body: withSkillName(current.body, name) };
211
262
  } else {
212
263
  // Editing an entry that only a lower layer has makes this scope's copy of it.
213
264
  const entry = await getEntry(kind, name, { root, library: alpHome() }).catch(error => { if (error.code === 'NOT_FOUND') throw new Error(`No ${kind} entry '${name}'; create it with alp ${kind.replace(/s$/, '')} ${creates}`); throw error; });
@@ -215,8 +266,15 @@ async function editCommand(kind, args) {
215
266
  current = (own ?? entry).content;
216
267
  revision = own ? own.revision : null;
217
268
  }
218
- const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision });
269
+ // A new skill meets the skill format strictly; an edit of an existing one is saved as before, and told what to fix.
270
+ const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision, strict: kind === 'skills' && action === creates });
219
271
  done(result, `${action === 'edit' ? 'Saved' : 'Created'} ${name} in ${where}.`);
272
+ if (kind === 'skills' && !values.json) {
273
+ const directory = path.join(scope === 'project' ? path.join(root, '.alp') : alpHome(), 'skills', name);
274
+ const report = await validateSkill(directory);
275
+ const notes = [...(result.warnings ?? []), ...report.errors.map(finding => finding.message), ...report.warnings.map(finding => finding.message)];
276
+ for (const note of [...new Set(notes)]) console.log(`note: ${note}`);
277
+ }
220
278
  }
221
279
 
222
280
  /** alp trust: the workspaces whose hooks run without asking (ALPD §45). */
@@ -240,4 +298,45 @@ async function teamsCommand(args) {
240
298
  }
241
299
  }
242
300
 
243
- export { libraryCommand, projectFlag, pairs, names, EDIT_OPTIONS, edited, editCommand, teamsCommand };
301
+ /**
302
+ * alp packs [--project DIR] [--json]: the optional packs ALP ships, and whether the library or the
303
+ * project has them. alp pack install <id> [--project [DIR]] [--assign] [--json]: copies a pack's
304
+ * skills, agents and teams into the library (or the project's .alp/), keeping any entry already
305
+ * there; --assign (library) gives its suggested skills to roles in role-skills.json.
306
+ */
307
+ async function packsCommand(args) {
308
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
309
+ if (positionals.length) throw new UsageError();
310
+ const root = path.resolve(values.project ?? process.cwd());
311
+ const rows = [];
312
+ for (const pack of await listPacks()) rows.push({ ...pack, installed: await packStatus(pack, { root, library: alpHome() }) });
313
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
314
+ const width = Math.max(...rows.map(row => row.id.length));
315
+ for (const row of rows) {
316
+ const contents = [row.skills.length ? `skills: ${row.skills.join(', ')}` : '', row.agents.length ? `agents: ${row.agents.join(', ')}` : '', row.teams.length ? `teams: ${row.teams.join(', ')}` : ''].filter(Boolean).join('; ');
317
+ const where = [row.installed.library ? 'library' : '', row.installed.project ? 'project' : ''].filter(Boolean).join(', ');
318
+ console.log(`${row.id.padEnd(width)} ${row.description}\n${' '.repeat(width)} ${contents}${where ? ` [installed: ${where}]` : ''}`);
319
+ }
320
+ console.log('Install one with: alp pack install <id> [--project] [--assign]');
321
+ }
322
+
323
+ async function packCommand(args) {
324
+ const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' }, assign: { type: 'boolean' } } });
325
+ const [action, id] = positionals;
326
+ if (action !== 'install' || !id || positionals.length > 2) throw new UsageError();
327
+ const scope = values.project !== undefined ? 'project' : 'library';
328
+ const root = values.project !== undefined ? path.resolve(values.project) : undefined;
329
+ if (scope === 'project') await taskProject(root);
330
+ const result = await installPack(id, { scope, root, library: alpHome(), assign: values.assign });
331
+ if (values.json) { console.log(JSON.stringify(result)); return; }
332
+ const where = scope === 'project' ? `the project ${root}` : `your library ${alpHome()}`;
333
+ for (const entry of result.installed) console.log(`installed ${entry.kind.replace(/s$/, '')} ${entry.name} ${entry.path}`);
334
+ for (const entry of result.kept) console.log(`kept ${entry.kind.replace(/s$/, '')} ${entry.name}: one already exists, and stays as it is (${entry.path})`);
335
+ for (const line of result.permissions.set) console.log(`permission ${line} (agent capped by its permission profile)`);
336
+ for (const line of result.permissions.conflicts) console.log(`warning: ${line}`);
337
+ if (result.assigned.length) console.log(`assigned ${result.assigned.join(', ')} in role-skills.json`);
338
+ else if (!values.assign && scope === 'library' && result.installed.some(entry => entry.kind === 'skills')) console.log('No role has these skills yet: rerun with --assign for the pack\'s suggestion, or alp agent edit <agent> --skills a,b.');
339
+ console.log(`Pack ${id} in ${where}. Start a new session (or close and resume) for agents to see it.`);
340
+ }
341
+
342
+ export { libraryCommand, projectFlag, pairs, names, EDIT_OPTIONS, edited, editCommand, teamsCommand, packsCommand, packCommand };
package/src/paths.js CHANGED
@@ -14,5 +14,5 @@ export function distributionEntry(name) {
14
14
  return candidates.find(candidate => existsSync(candidate)) ?? candidates[0];
15
15
  }
16
16
 
17
- /** What starts alpd: alpd.js under Node, or the ALP executable itself (`alp daemon run`). */
17
+ /** What starts alpd: alpd.js under Node (named through app/current in the ALP bundle). */
18
18
  export const DAEMON_ENTRY = selfEntry(fileURLToPath(distributionEntry('alpd.js')));
package/src/projects.js CHANGED
@@ -22,8 +22,10 @@ async function project(command, args) {
22
22
  try {
23
23
  const result = await (command === 'upgrade' ? upgradeProject : initProject)(args[0] ?? process.cwd(), { library: alpHome() });
24
24
  console.log(`ALP initialized: ${result.created.length} files created, ${result.preserved.length} existing files preserved.`);
25
- const library = await seedLibrary(alpHome());
25
+ // On upgrade an edited role-skills.json is offered the built-in role skills it never was (t-de1a).
26
+ const library = await seedLibrary(alpHome(), { offerRoleSkills: command === 'upgrade' });
26
27
  if (library.created.length || library.updated.length) console.log(`Skill library ${alpHome()}: ${library.created.length} files added, ${library.updated.length} unchanged files updated.`);
28
+ if (library.offered?.length) console.log(`New built-in skills given to roles in your edited role-skills.json: ${library.offered.join(', ')} (remove any you do not want; ALP will not add it again).`);
27
29
  if (command === 'init' && result.updated?.length) console.log(`Template model profiles refreshed: ${result.updated.join(', ')}`);
28
30
  if (command === 'upgrade') {
29
31
  console.log(`ALP upgraded: ${result.updated.length} files updated.${result.backup ? ` Backup: ${result.backup}` : ''}`);
package/src/roles.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { runBridge } from '@anhlp/alp-core/bridges';
3
- import { packagedInfo } from '@anhlp/alp-core/packaged';
4
3
  import { UsageError } from './usage.js';
5
4
 
6
5
  /**
7
6
  * The role subcommands (t-1e02): `alp daemon run`, `alp web serve` and `alp bridge acp|antigravity`
8
- * run alpd, alp-web and the MCP bridges in this process. The ALP executable starts its own roles
9
- * this way, since it cannot run a script path; under Node they import the same scripts that
10
- * `node alpd.js` and `node alp-web.js` run.
7
+ * run alpd, alp-web and the MCP bridges in this process: they import the same scripts that
8
+ * `node alpd.js` and `node alp-web.js` run. Services and MCP entries written by the single-file
9
+ * executable of 0.0.1-beta.5/6 still name them.
11
10
  *
12
11
  * The role's module reads its options from process.argv as when run directly, so argv is rewritten
13
12
  * to `[runtime, entry, ...args]` before the module loads.
@@ -17,8 +16,7 @@ import { UsageError } from './usage.js';
17
16
  */
18
17
  export async function runRole(role, file, args) {
19
18
  process.argv = [process.argv[0], file, ...args];
20
- const load = packagedInfo()?.roles?.[role];
21
- return load ? load() : import(pathToFileURL(file).href);
19
+ return import(pathToFileURL(file).href);
22
20
  }
23
21
 
24
22
  /** alp bridge acp|antigravity: the stdio MCP bridge an agent CLI starts to reach alpd's tools. @param {string[]} args */
@@ -6,12 +6,13 @@ import path from 'node:path';
6
6
  import { createInterface } from 'node:readline/promises';
7
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  import { parseArgs } from 'node:util';
9
- import { executablePath } from '@anhlp/alp-core/packaged';
9
+ import { bundleInfo, samePath } from '@anhlp/alp-core/packaged';
10
10
 
11
11
  /**
12
- * `alp update` (t-1e02 P3): replaces the ALP executable with a release from GitHub Releases, after
13
- * checking the archive against the release's SHA256SUMS and, when `gh` is installed, its build
14
- * provenance. The project template upgrade that `alp update` used to run is `alp update-template`.
12
+ * `alp update` (t-1807): installs a release of the ALP bundle from GitHub Releases beside the running
13
+ * one (<app>/<version>, see @anhlp/alp-core/packaged) and points <app>/current at it, after checking
14
+ * the archive against the release's SHA256SUMS and, when `gh` is installed, its build provenance.
15
+ * The project template upgrade that `alp update` used to run is `alp update-template`.
15
16
  *
16
17
  * Everything that touches the network, the filesystem or child processes comes in through `deps`
17
18
  * so the tests can drive each step.
@@ -20,12 +21,12 @@ import { executablePath } from '@anhlp/alp-core/packaged';
20
21
  export const DEFAULT_REPO = 'phucanh08/alp';
21
22
  export const SIGNER_WORKFLOW = '.github/workflows/release-binaries.yml';
22
23
  export const NPM_PACKAGE = '@anhlp/alp';
23
- const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates the ALP executable; the project template upgrade is `alp update-template [directory]`)';
24
+ const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates ALP itself; the project template upgrade is `alp update-template [directory]`)';
24
25
 
25
26
  const OPTIONS = { check: { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, version: { type: 'string' }, 'base-url': { type: 'string' }, help: { type: 'boolean', short: 'h' } };
26
27
 
27
28
  export const UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
28
- Replaces this ALP executable with the latest release (or release X) from GitHub Releases, after checking
29
+ Installs the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, after checking
29
30
  it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
30
31
  ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
31
32
  The project template upgrade is \`alp update-template [directory]\`.`;
@@ -34,7 +35,7 @@ The project template upgrade is \`alp update-template [directory]\`.`;
34
35
  export function releasePlatform(platform = process.platform, arch = process.arch) {
35
36
  const osName = { darwin: 'darwin', linux: 'linux', win32: 'windows' }[platform];
36
37
  const archName = { x64: 'x64', arm64: 'arm64' }[arch];
37
- if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no executable for ${platform}-${arch}`);
38
+ if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no build for ${platform}-${arch}`);
38
39
  return `${osName}-${archName}`;
39
40
  }
40
41
 
@@ -62,7 +63,7 @@ export function parseSums(text) {
62
63
  export function selectAsset(sumsText, platform, version) {
63
64
  const suffix = `-${platform}${archiveExtension(platform)}`;
64
65
  const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
65
- if (matches.length === 0) throw new Error(`This release has no ALP executable for ${platform}${version ? ` at version ${version}` : ''}`);
66
+ if (matches.length === 0) throw new Error(`This release has no ALP build for ${platform}${version ? ` at version ${version}` : ''}`);
66
67
  if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map(m => m.name).join(', ')}`);
67
68
  const [match] = matches;
68
69
  if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
@@ -109,7 +110,7 @@ export function releaseBaseUrl({ repo, version, baseUrl }) {
109
110
  return base;
110
111
  }
111
112
 
112
- /** The largest file alp update downloads: the executable is about 100 MB. */
113
+ /** The largest file alp update downloads: an archive of the bundle is about 70 MB. */
113
114
  export const MAX_DOWNLOAD = 512 * 1024 * 1024;
114
115
 
115
116
  const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
@@ -188,18 +189,12 @@ export function verifyProvenance(file, { repo, env = process.env, run = spawnSyn
188
189
  return 'verified';
189
190
  }
190
191
 
191
- /** The previous executable Windows keeps beside the new one until the next start. @param {string} target @param {string} [platform] */
192
- export const oldPath = (target, platform = process.platform) => {
193
- const p = platform === 'win32' ? path.win32 : path;
194
- return p.join(p.dirname(target), `${p.basename(target, p.extname(target))}.old${p.extname(target) || '.exe'}`);
195
- };
196
-
197
- const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES']);
192
+ const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY']);
198
193
  const pause = (/** @type {number} */ ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
199
194
 
200
195
  /**
201
196
  * Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
202
- * executable it just saw run (the staged file's --version) for a moment. About 6 s in all.
197
+ * executable it just saw run (the staged bundle's --version) for a moment. About 8 s in all.
203
198
  * @template T @param {() => T} action @param {(ms: number) => void} [sleep]
204
199
  */
205
200
  export function retryBusy(action, sleep = pause, attempts = 25) {
@@ -211,64 +206,7 @@ export function retryBusy(action, sleep = pause, attempts = 25) {
211
206
  }
212
207
  }
213
208
 
214
- /**
215
- * Puts `staged` in place of `target`. Unix: rename over the running file. Windows: the running
216
- * alp.exe cannot be overwritten but can be renamed, so it becomes alp.old.exe (deleted on the next
217
- * start) and the new file takes its name; a failure puts the old one back.
218
- * @param {string} staged @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'renameSync' | 'rmSync' | 'existsSync'>, unique?: () => string, sleep?: (ms: number) => void }} [options]
219
- */
220
- export function replaceExecutable(staged, target, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(4).toString('hex'), sleep = pause } = {}) {
221
- if (platform !== 'win32') { fs.renameSync(staged, target); return { old: undefined }; }
222
- const old = oldPath(target, platform);
223
- if (fs.existsSync(old)) {
224
- // A process started from the previous update's file (an alpd not restarted yet) keeps it locked:
225
- // it cannot be deleted, but it can be moved aside for a later start to delete.
226
- try { fs.rmSync(old, { force: true }); } catch {
227
- const aside = old.replace(/\.exe$/i, `.${unique()}.exe`);
228
- try { fs.renameSync(old, aside); } catch (error) {
229
- throw new Error(`${old} is in use and could not be moved (${error.code ?? error.message}); stop the ALP processes started from it (alp daemon stop) and run alp update again`);
230
- }
231
- }
232
- }
233
- retryBusy(() => fs.renameSync(target, old), sleep);
234
- try {
235
- retryBusy(() => fs.renameSync(staged, target), sleep);
236
- } catch (error) {
237
- try { retryBusy(() => fs.renameSync(old, target), sleep); } catch (restore) {
238
- throw new Error(`Could not put the new executable at ${target} (${error.code ?? error.message}), and could not move the previous one back (${restore.code ?? restore.message}): rename ${old} to ${target} yourself`);
239
- }
240
- throw error;
241
- }
242
- return { old };
243
- }
244
-
245
- /** Deletes the alp.old.exe (and alp.old.<hex>.exe) a Windows update left behind; called on every packaged start. @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'rmSync' | 'readdirSync'> }} [options] */
246
- export function cleanupOldExecutable(target, { platform = process.platform, fs = nodeFs } = {}) {
247
- if (platform !== 'win32') return false;
248
- const old = path.win32.basename(oldPath(target, platform));
249
- const stem = old.slice(0, -'.exe'.length).toLowerCase();
250
- let names;
251
- try { names = fs.readdirSync(path.win32.dirname(target)); } catch { return false; }
252
- let removed = false;
253
- // alp.old.exe, and the alp.old.<hex>.exe a locked one was moved aside to.
254
- for (const name of names) {
255
- const lower = name.toLowerCase();
256
- if (lower !== `${stem}.exe` && !(lower.startsWith(`${stem}.`) && /^[0-9a-f]+\.exe$/.test(lower.slice(stem.length + 1)))) continue;
257
- try { fs.rmSync(path.win32.join(path.win32.dirname(target), name), { force: true }); removed = true; } catch {}
258
- }
259
- return removed;
260
- }
261
-
262
- /**
263
- * Whether the executable is the one npm installed for @anhlp/alp (t-cd7f): it lives in a platform
264
- * package, node_modules/@anhlp/alp-<os>-<arch>/bin/. npm owns that file; updating it in place would
265
- * leave npm's records behind, so npm updates it. @param {string} execPath
266
- */
267
- export function isNpmExecutable(execPath) {
268
- return /[\\/]node_modules[\\/]@anhlp[\\/]alp-(?:darwin|linux|win32)-(?:arm64|x64)[\\/]bin[\\/]alp(?:\.exe)?$/i.test(execPath ?? '');
269
- }
270
-
271
- /** What to say outside the executable (an npm install). @param {string[]} positionals */
209
+ /** What to say outside the ALP bundle (an npm install). @param {string[]} positionals */
272
210
  export function npmMessage(positionals = []) {
273
211
  const lines = [];
274
212
  if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
@@ -276,18 +214,81 @@ export function npmMessage(positionals = []) {
276
214
  return lines.join('\n');
277
215
  }
278
216
 
279
- /** Extracts the archive and returns the executable inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
217
+ /** Why this bundle cannot update itself: it was not installed by install.sh / install.ps1. @param {string} root */
218
+ export const notInstalledMessage = root => `alp: ${root} is not an installed ALP (no app/current points at it); install the release with install.sh (Windows: install.ps1), which alp update can then keep up to date:\n curl -fsSL https://github.com/${DEFAULT_REPO}/releases/latest/download/install.sh | sh`;
219
+
220
+ /**
221
+ * tar, as this platform must start it. On Windows it is the system's own bsdtar
222
+ * (%SystemRoot%\System32\tar.exe), never whatever comes first on PATH: under Git Bash that is Git's
223
+ * GNU tar, which reads a drive-letter path such as `D:\a\…\alp.zip` as a remote `host:file`
224
+ * archive and cannot read or write a zip at all. `--force-local` is not an answer: bsdtar rejects it.
225
+ *
226
+ * DUPLICATE, deliberately (t-ffe4.6): `windowsTar` in scripts/spawn-command.mjs is the same
227
+ * knowledge for the repository's own scripts. This package is published, so it cannot import from
228
+ * scripts/, and scripts/ must keep working before anything is built. Change one and change the
229
+ * other; test/integration/spawn-command.test.js asserts the two agree, and refuses any third copy.
230
+ * @param {string} platform @param {Record<string, string | undefined>} env
231
+ */
232
+ export const systemTar = (platform = process.platform, env = process.env) =>
233
+ platform === 'win32' ? path.win32.join(env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
234
+
235
+ /** Extracts the archive into `directory` and returns the bundle inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
280
236
  function extract(archive, directory, asset, platform, run = spawnSync) {
281
237
  const windows = platform.startsWith('windows-');
282
238
  // tar reads both: GNU/bsd tar for .tar.gz, Windows' bsdtar (tar.exe) for .zip.
283
239
  // On Windows, Git's GNU tar (which reads no zip) may come first on PATH: use the system's bsdtar.
284
- const tar = process.platform === 'win32' ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
285
- const result = run(tar, [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
240
+ const result = run(systemTar(), [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
286
241
  if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || '').trim()}`);
287
- const name = asset.name.slice(0, -archiveExtension(platform).length);
288
- const binary = path.join(directory, name, windows ? 'alp.exe' : 'alp');
289
- if (!nodeFs.existsSync(binary)) throw new Error(`${asset.name} does not contain ${name}/${windows ? 'alp.exe' : 'alp'}`);
290
- return binary;
242
+ const root = path.join(directory, asset.name.slice(0, -archiveExtension(platform).length));
243
+ if (!nodeFs.existsSync(path.join(root, 'alp-bundle.json'))) throw new Error(`${asset.name} does not contain an ALP bundle (${path.basename(root)}/alp-bundle.json)`);
244
+ return root;
245
+ }
246
+
247
+ /** The bundle's own Node and CLI: run without its launcher, so Windows needs no shell for alp.cmd. @param {string} root @param {string} platform */
248
+ export function bundleCommand(root, platform = process.platform) {
249
+ const node = platform === 'win32' ? path.join(root, 'node', 'node.exe') : path.join(root, 'node', 'bin', 'node');
250
+ return { command: node, args: [path.join(root, 'lib', 'node_modules', '@anhlp', 'alp-cli', 'dist', 'cli.js')] };
251
+ }
252
+
253
+ /**
254
+ * Points `<app>/current` at `<app>/<version>`. Unix: a relative symlink renamed over the old one, in
255
+ * one step. Windows: the junction is replaced (removed, then made again; put back on failure).
256
+ * @param {string} app @param {string} version @param {{ platform?: string, fs?: typeof nodeFs, unique?: () => string }} [options]
257
+ */
258
+ export function switchCurrent(app, version, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(6).toString('hex') } = {}) {
259
+ const p = platform === 'win32' ? path.win32 : path;
260
+ const current = p.join(app, 'current');
261
+ if (platform !== 'win32') {
262
+ const link = p.join(app, `.current-${unique()}`);
263
+ fs.symlinkSync(version, link);
264
+ try { fs.renameSync(link, current); } catch (error) { try { fs.unlinkSync(link); } catch {} throw error; }
265
+ return;
266
+ }
267
+ let previous;
268
+ try { previous = fs.readlinkSync(current); } catch {}
269
+ if (previous !== undefined) retryBusy(() => fs.unlinkSync(current));
270
+ try { fs.symlinkSync(p.join(app, version), current, 'junction'); } catch (error) {
271
+ if (previous !== undefined) try { fs.symlinkSync(previous, current, 'junction'); } catch {}
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Removes what earlier updates left in `<app>`: versions other than `keep`, and staging directories.
278
+ * A failure (a file still in use on Windows) leaves that entry for the next update. keepAside keeps
279
+ * the copies earlier reinstalls moved aside, which a running alpd may still run from.
280
+ * @param {string} app @param {string[]} keep
281
+ */
282
+ export function pruneVersions(app, keep, fs = nodeFs, { keepAside = false } = {}) {
283
+ let names;
284
+ try { names = fs.readdirSync(app); } catch { return []; }
285
+ const removed = [];
286
+ for (const name of names) {
287
+ if (name === 'current' || keep.includes(name) || (keepAside && name.startsWith('.alp-old-'))) continue;
288
+ if (!/^[0-9][0-9A-Za-z.+-]*$/.test(name) && !/^\.alp-(update|old)-[0-9A-Za-z]+$/.test(name) && !/^\.current-[0-9a-f]+$/.test(name)) continue;
289
+ try { fs.rmSync(path.join(app, name), { recursive: true, force: true }); removed.push(name); } catch {}
290
+ }
291
+ return removed;
291
292
  }
292
293
 
293
294
  /** Asks a yes/no question on the terminal. @param {string} question */
@@ -298,12 +299,12 @@ async function confirm(question) {
298
299
 
299
300
  /**
300
301
  * @typedef {{
301
- * packaged: boolean, version: string, execPath: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
302
+ * bundle: import('@anhlp/alp-core/packaged').BundleInfo | undefined, version: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
302
303
  * log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
303
304
  * fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
304
305
  * provenance: (file: string, repo: string) => string, extract: typeof extract,
305
- * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (binary: string) => number,
306
- * runVersion: (binary: string) => string,
306
+ * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (root: string) => number,
307
+ * runVersion: (root: string) => string,
307
308
  * }} UpdateDeps
308
309
  */
309
310
 
@@ -311,26 +312,29 @@ async function confirm(question) {
311
312
  export async function selfUpdate(args, overrides = {}) {
312
313
  /** @type {UpdateDeps} */
313
314
  const deps = {
314
- packaged: false, version: '0.0.0', execPath: executablePath() ?? '', env: process.env, platform: process.platform, arch: process.arch,
315
+ bundle: bundleInfo(), version: '0.0.0', env: process.env, platform: process.platform, arch: process.arch,
315
316
  log: line => console.log(line), warn: line => console.error(line), interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
316
317
  fetchBytes, confirm, extract,
317
318
  provenance: (file, repo) => verifyProvenance(file, { repo }),
318
- daemon: async () => undefined, restartDaemon: binary => spawnSync(binary, ['daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1,
319
- runVersion: binary => spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? '',
319
+ daemon: async () => undefined,
320
+ restartDaemon: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, 'daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1; },
321
+ runVersion: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, '--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? ''; },
320
322
  ...overrides,
321
323
  };
324
+ const { bundle } = deps;
322
325
  let parsed;
323
326
  try {
324
327
  parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
325
328
  } catch (error) {
326
329
  deps.warn(`alp: ${error.message}`);
327
330
  deps.warn(`alp: ${TEMPLATE_HINT}`);
328
- return deps.packaged ? 1 : 0;
331
+ return bundle ? 1 : 0;
329
332
  }
330
333
  const { values, positionals } = parsed;
331
334
  if (values.help) { deps.log(UPDATE_USAGE); return 0; }
332
- if (!deps.packaged || isNpmExecutable(deps.execPath)) { deps.log(npmMessage(positionals)); return 0; }
335
+ if (!bundle) { deps.log(npmMessage(positionals)); return 0; }
333
336
  if (positionals.length) { deps.warn(`alp: ${TEMPLATE_HINT}`); return 1; }
337
+ if (!bundle.current) { deps.warn(notInstalledMessage(bundle.root)); return 1; }
334
338
 
335
339
  const wanted = values.version?.replace(/^v/, '');
336
340
  if (wanted !== undefined && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
@@ -352,18 +356,26 @@ export async function selfUpdate(args, overrides = {}) {
352
356
  if (order === 0 && !wanted) { deps.log(`alp ${deps.version} is up to date (${platform})`); return 0; }
353
357
  if (order < 0 && !wanted) { deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`); return 0; }
354
358
 
355
- let target;
356
- try { target = nodeFs.realpathSync(deps.execPath); } catch { target = deps.execPath; }
357
- const dir = path.dirname(target);
358
- try { nodeFs.accessSync(dir, nodeFs.constants.W_OK); } catch { throw new Error(`${dir} is not writable; run alp update with the permissions that installed ${target}`); }
359
+ const { app, current } = bundle;
360
+ // A reinstall of the running version moves its directory aside instead of replacing it in place,
361
+ // on Windows too: Windows renames a directory that holds a running executable. Only a process
362
+ // whose working directory is inside the tree, or a handle opened without delete sharing, refuses
363
+ // the move (t-5294.7, board finding p-bcd9c956) — that failure is reported below, not predicted.
364
+ // The version a running alpd uses keeps its files, like the one this process runs.
365
+ const running = await deps.daemon().catch(() => undefined);
366
+ try { nodeFs.accessSync(app, nodeFs.constants.W_OK); } catch { throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`); }
367
+ const target = path.join(app, asset.version);
359
368
 
360
369
  if (!values.yes) {
361
- if (!deps.interactive) throw new Error(`alp update would replace ${target} (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
362
- if (!await deps.confirm(`Replace ${target} (${deps.version} → ${asset.version})?`)) { deps.log('Not updated.'); return 1; }
370
+ if (!deps.interactive) throw new Error(`alp update would install ${target} and switch ${current} to it (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
371
+ if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) { deps.log('Not updated.'); return 1; }
363
372
  }
364
373
 
365
374
  const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'alp-update-'));
366
- let staged;
375
+ // Unpacked beside the versions, so moving it into place stays on one filesystem.
376
+ const staging = path.join(app, `.alp-update-${randomBytes(6).toString('hex')}`);
377
+ /** @type {string | undefined} the running version, moved aside by a reinstall */
378
+ let aside;
367
379
  try {
368
380
  deps.log(`Downloading ${asset.name} from ${base}`);
369
381
  const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
@@ -374,25 +386,42 @@ export async function selfUpdate(args, overrides = {}) {
374
386
  const provenance = deps.provenance(archive, repo);
375
387
  if (provenance === 'verified') deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
376
388
  else deps.warn('alp: warning: gh is not available, so only the SHA256SUMS checksum was verified, not the build provenance (install gh to verify it)');
377
- const unpacked = path.join(work, 'x');
378
- nodeFs.mkdirSync(unpacked);
379
- const binary = deps.extract(archive, unpacked, asset, platform);
380
- // Stage beside the target so the rename stays on one filesystem; no half-written file is ever alp.
381
- staged = path.join(dir, `.alp.update.${randomBytes(6).toString('hex')}${deps.platform === 'win32' ? '.exe' : ''}`);
382
- nodeFs.copyFileSync(binary, staged);
383
- if (deps.platform !== 'win32') nodeFs.chmodSync(staged, 0o755);
384
- const reported = deps.runVersion(staged);
385
- if (reported !== asset.version) throw new Error(`The downloaded executable reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was replaced`);
386
- replaceExecutable(staged, target, { platform: deps.platform });
387
- staged = undefined;
389
+ nodeFs.mkdirSync(staging);
390
+ const unpacked = deps.extract(archive, staging, asset, platform);
391
+ const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, 'alp-bundle.json'), 'utf8'));
392
+ if (manifest.version !== asset.version || (manifest.platform && manifest.platform !== platform)) throw new Error(`${asset.name} holds ALP ${manifest.version} for ${manifest.platform}, not ${asset.version} for ${platform}; nothing was changed`);
393
+ const reported = deps.runVersion(unpacked);
394
+ if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
395
+ if (nodeFs.existsSync(target)) {
396
+ // A reinstall of the running version moves it aside (its processes keep their files); any other copy is stale.
397
+ if (samePath(target, bundle.root) || running?.version === asset.version) {
398
+ const moved = `.alp-old-${randomBytes(6).toString('hex')}`;
399
+ try { retryBusy(() => nodeFs.renameSync(target, path.join(app, moved))); } catch (error) {
400
+ // Nothing has been replaced yet. Say what really holds the directory, so nobody looks for
401
+ // a Windows rule that does not exist (t-5294.7).
402
+ throw new Error(`Could not move ${target} aside to reinstall ALP ${asset.version}: ${error.message}. Something holds that directory: a process whose working directory is inside it, or a file handle opened without delete sharing. Stop alpd (alp daemon stop), leave that directory in any shell, and run alp update again`, { cause: error });
403
+ }
404
+ aside = moved;
405
+ }
406
+ else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
407
+ }
408
+ try { retryBusy(() => nodeFs.renameSync(unpacked, target)); } catch (error) {
409
+ // The running version goes back where it was, so app/current still points at files (t-1f14).
410
+ if (aside && !nodeFs.existsSync(target)) {
411
+ try { nodeFs.renameSync(path.join(app, aside), target); aside = undefined; } catch { throw new Error(`${error.message}; the running ALP ${asset.version} is in ${path.join(app, aside)}: move it back to ${target}`, { cause: error }); }
412
+ }
413
+ throw error;
414
+ }
415
+ switchCurrent(app, asset.version, { platform: deps.platform });
388
416
  } finally {
389
- // A cleanup failure must not hide why the update failed; a leftover .alp.update.* is harmless.
390
- if (staged) try { nodeFs.rmSync(staged, { force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
417
+ // A cleanup failure must not hide why the update failed; a leftover staging directory goes with the next update.
418
+ try { nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
391
419
  try { nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
392
420
  }
393
- deps.log(`Updated ${target}: ${deps.version} → ${asset.version}`);
421
+ // The version this process (and maybe alpd) runs stays until the next update.
422
+ pruneVersions(app, [asset.version, path.basename(bundle.root), ...(running?.version ? [running.version] : []), ...(aside ? [aside] : [])], nodeFs, { keepAside: Boolean(running) });
423
+ deps.log(`Updated ALP ${deps.version} → ${asset.version} (${current} → ${target})`);
394
424
 
395
- const running = await deps.daemon().catch(() => undefined);
396
425
  if (running && running.version !== asset.version) {
397
426
  const sessions = running.sessions;
398
427
  const known = Number.isSafeInteger(sessions);