@aisac/cli 0.4.0-beta.18 → 0.4.0-beta.21

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/dist/state.mjs CHANGED
@@ -272,11 +272,22 @@ export async function readConfig(rootOverride) {
272
272
  * @param {unknown} value
273
273
  */
274
274
  export async function atomicJson(path, value) {
275
+ await atomicBytes(path, Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8'));
276
+ }
277
+
278
+ /**
279
+ * Replace one owned file with exact bytes (`0600`), atomically. The existing
280
+ * file is left intact if the temporary write fails. Used for documents whose
281
+ * bytes are signed and must be kept as received (the release manifest cache).
282
+ * @param {string} path
283
+ * @param {Uint8Array} bytes
284
+ */
285
+ export async function atomicBytes(path, bytes) {
275
286
  await assertSafePath(dirname(path), false);
276
287
  await assertSafePath(path);
277
288
  const temp = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
278
289
  try {
279
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
290
+ await writeFile(temp, bytes, { mode: 0o600, flag: 'wx' });
280
291
  await chmod(temp, 0o600);
281
292
  await rename(temp, path);
282
293
  } catch (error) {
@@ -285,6 +296,19 @@ export async function atomicJson(path, value) {
285
296
  }
286
297
  }
287
298
 
299
+ /**
300
+ * Create, or confirm, one private subdirectory (`0700`, owned, no symlinked
301
+ * ancestor) under an owned state root.
302
+ * @param {string} path
303
+ */
304
+ export async function ensurePrivateDirectory(path) {
305
+ await assertSafePath(path);
306
+ await mkdir(path, { recursive: true, mode: 0o700 });
307
+ await chmod(path, 0o700);
308
+ await assertSafePath(path, false);
309
+ return path;
310
+ }
311
+
288
312
  /** @param {string} token */
289
313
  export async function tokenDigest(token) {
290
314
  return createHash('sha256').update(token, 'utf8').digest('hex');
@@ -0,0 +1,442 @@
1
+ // @ts-check
2
+ /**
3
+ * Self-update actions (spec aisac-release-manifest FR6; ADR-0056 R3): the npm
4
+ * prefix that owns the running client, the writability probe, the private
5
+ * directory npm runs in, the update lock, the npm subprocesses (registry read,
6
+ * install), the installed-version read, the re-exec and the npm lookup. No
7
+ * decision lives here: `self-update.mjs` decides and calls these.
8
+ */
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { accessSync, constants, statSync } from 'node:fs';
11
+ import { link, lstat, open, rename, unlink, writeFile } from 'node:fs/promises';
12
+ import { constants as osConstants } from 'node:os';
13
+ import { basename, dirname, join, resolve } from 'node:path';
14
+ import { stdin } from 'node:process';
15
+ import { processAlive } from './engineering-pack.mjs';
16
+ import { resolveNative } from './platform.mjs';
17
+ import { ensurePrivateDirectory } from './state.mjs';
18
+ import { CLIENT_PACKAGES, RELEASE_STATE_DIRECTORY } from './release-manifest.mjs';
19
+
20
+ /** Set by the parent on re-exec; the child then skips the update step (FR6). */
21
+ export const REEXEC_ENV = 'AISAC_REEXEC';
22
+ /** `<state>/release/update.lock`: one installer at a time, no host launch under one (FR6). */
23
+ export const UPDATE_LOCK_FILE = 'update.lock';
24
+ /** `<state>/release/npm`: where every npm subprocess runs, never the user's directory (FR6). */
25
+ export const NPM_WORKING_DIRECTORY = 'npm';
26
+ /** How long a launch waits for another launcher's update before it refuses to start a host. */
27
+ export const LOCK_WAIT_MS = 2 * 60 * 1000;
28
+ /** A lock older than this is stale whatever its process says (pid reuse). */
29
+ const LOCK_TTL_MS = 15 * 60 * 1000;
30
+ const LOCK_POLL_MS = 250;
31
+ export const INSTALL_TIMEOUT_MS = 5 * 60 * 1000;
32
+ const VIEW_TIMEOUT_MS = 60_000;
33
+ const VERSION_TIMEOUT_MS = 15_000;
34
+ const MAX_RECORD_BYTES = 4 * 1024;
35
+ export const SRI_SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u;
36
+ const VERSION_OUTPUT = /^(?:aisac|aibrain) (\S+)$/u;
37
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/u;
38
+
39
+ /**
40
+ * @typedef {{ prefix: string, modulesDirectory: string, packageName: string, cliPath: string }} InstallPrefix
41
+ * @typedef {{ npm: string, prefix: InstallPrefix, packageName: string, version: string,
42
+ * env: NodeJS.ProcessEnv, cwd: string }} InstallInput
43
+ * @typedef {{ status: 'ok', integrity: string } | { status: 'unavailable' }} RegistryIntegrity
44
+ * @typedef {{ acquired: true, holder: number } | { acquired: false, holder: number | null }} UpdateLock
45
+ * @typedef {UpdateLock} FileLock
46
+ * @typedef {{ pid: number, at: string }} LockRecord
47
+ * @typedef {{ now?: () => Date, alive?: (pid: number) => boolean, sleep?: (ms: number) => Promise<void>,
48
+ * onWait?: (holder: number) => void, ttlMs?: number, waitMs?: number }} LockOptions
49
+ */
50
+
51
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
52
+ export function isRecord(value) {
53
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
54
+ }
55
+
56
+ /** @param {unknown} value @returns {value is string} */
57
+ export function isInstant(value) {
58
+ return typeof value === 'string' && ISO_INSTANT.test(value);
59
+ }
60
+
61
+ /**
62
+ * The environment a subprocess sees: never the provider keys or a token file.
63
+ * The account token is not in the environment to begin with. A deny-list, not an
64
+ * allow-list: the user's own `~/.npmrc` may expand `${NPM_TOKEN}` for a private
65
+ * registry, and npm fails outright when the variable is missing; the control
66
+ * against a hostile `.npmrc` is the working directory, never the user's.
67
+ * @param {NodeJS.ProcessEnv} env
68
+ */
69
+ export function safeEnvironment(env) {
70
+ /** @type {NodeJS.ProcessEnv} */
71
+ const copy = { ...env };
72
+ delete copy.JEV_API_KEY;
73
+ delete copy.TYPESAFE_API_KEY;
74
+ delete copy.AIBRAIN_TOKEN_FILE;
75
+ return copy;
76
+ }
77
+
78
+ /**
79
+ * The npm prefix that owns the running client, derived from the code's own
80
+ * path: `<prefix>/lib/node_modules/<package>/dist` (the Linux and macOS global
81
+ * layout, FR6). Anything else (a repository checkout, another layout) is
82
+ * unknown, and the client then only prints the command.
83
+ * @param {string} packageRoot The `dist` directory the running `cli.mjs` lives in.
84
+ * @returns {InstallPrefix | null}
85
+ */
86
+ export function installPrefix(packageRoot) {
87
+ const dist = resolve(packageRoot);
88
+ if (basename(dist) !== 'dist') return null;
89
+ let cursor = dirname(dist);
90
+ const segments = [basename(cursor)];
91
+ cursor = dirname(cursor);
92
+ if (basename(cursor).startsWith('@')) {
93
+ segments.unshift(basename(cursor));
94
+ cursor = dirname(cursor);
95
+ }
96
+ const packageName = segments.join('/');
97
+ if (!CLIENT_PACKAGES.includes(packageName)) return null;
98
+ if (basename(cursor) !== 'node_modules') return null;
99
+ const modulesDirectory = cursor;
100
+ cursor = dirname(cursor);
101
+ if (basename(cursor) !== 'lib') return null;
102
+ return { prefix: dirname(cursor), modulesDirectory, packageName, cliPath: join(dist, 'cli.mjs') };
103
+ }
104
+
105
+ /**
106
+ * Whether this user can write into the prefix: an exclusive temporary file in
107
+ * each directory npm writes (`lib/node_modules` for the package, `bin` for the
108
+ * executable link), removed at once. Never `sudo` (FR6).
109
+ * @param {string[]} directories
110
+ */
111
+ export async function prefixWritable(...directories) {
112
+ for (const directory of directories) if (!(await writableDirectory(directory))) return false;
113
+ return directories.length > 0;
114
+ }
115
+
116
+ /** @param {string} directory */
117
+ async function writableDirectory(directory) {
118
+ const probe = join(
119
+ directory,
120
+ `.aisac-update-probe-${process.pid}-${Math.random().toString(16).slice(2)}`,
121
+ );
122
+ /** @type {import('node:fs/promises').FileHandle | undefined} */
123
+ let handle;
124
+ try {
125
+ handle = await open(probe, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ } finally {
130
+ await handle?.close().catch(() => undefined);
131
+ await unlink(probe).catch(() => undefined);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * A private state document of bounded size: regular, owned, opened without
137
+ * following symlinks. Null when missing or not ours.
138
+ * @param {string} path @returns {Promise<unknown>}
139
+ */
140
+ export async function readOwnedJson(path) {
141
+ /** @type {import('node:fs/promises').FileHandle | undefined} */
142
+ let handle;
143
+ try {
144
+ const link = await lstat(path);
145
+ if (!link.isFile() || link.size > MAX_RECORD_BYTES) return null;
146
+ if (typeof process.getuid === 'function' && link.uid !== process.getuid()) return null;
147
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
148
+ return JSON.parse(await handle.readFile('utf8'));
149
+ } catch {
150
+ return null;
151
+ } finally {
152
+ await handle?.close().catch(() => undefined);
153
+ }
154
+ }
155
+
156
+ /** @param {string} root The private directory where npm runs (see `registryIntegrity`). */
157
+ export async function npmWorkingDirectory(root) {
158
+ return ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY, NPM_WORKING_DIRECTORY));
159
+ }
160
+
161
+ /** @param {unknown} value @returns {{ pid: number, at: string } | null} */
162
+ function lockRecord(value) {
163
+ if (!isRecord(value) || value.schemaVersion !== 1 || !isInstant(value.at)) return null;
164
+ if (!Number.isSafeInteger(value.pid) || /** @type {number} */ (value.pid) <= 0) return null;
165
+ return { pid: /** @type {number} */ (value.pid), at: value.at };
166
+ }
167
+
168
+ /**
169
+ * The update lock (FR6): one installer at a time, and no host launch while an
170
+ * install runs, since a launch has no marker of its own until its host starts.
171
+ * Created atomically (write, then `link`), it names its holder; a lock whose
172
+ * process is gone, or older than the TTL, is stale and removed. A live lock is
173
+ * waited on, up to `LOCK_WAIT_MS`. `acquired: false` with a holder means the
174
+ * wait ran out; with none, the lock could not be used at all and the caller
175
+ * goes on without it.
176
+ * @param {string} root @param {LockOptions} [options] @returns {Promise<UpdateLock>}
177
+ */
178
+ export async function acquireUpdateLock(root, options = {}) {
179
+ /** @type {string} */
180
+ let directory;
181
+ try {
182
+ directory = await ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY));
183
+ } catch {
184
+ return { acquired: false, holder: null };
185
+ }
186
+ return acquireFileLock(join(directory, UPDATE_LOCK_FILE), options);
187
+ }
188
+
189
+ /** Remove the update lock when this process holds it. Never throws. @param {string} root */
190
+ export async function releaseUpdateLock(root) {
191
+ await releaseFileLock(join(root, RELEASE_STATE_DIRECTORY, UPDATE_LOCK_FILE));
192
+ }
193
+
194
+ /**
195
+ * One exclusive lock file (the update lock above, the per-host install lock of
196
+ * R4): created atomically (write, then `link`), naming its holder; stale when
197
+ * its process is gone or it is older than `ttlMs`; waited on up to `waitMs`.
198
+ * @param {string} path @param {LockOptions} [options] @returns {Promise<FileLock>}
199
+ */
200
+ export async function acquireFileLock(path, options = {}) {
201
+ const now = options.now ?? (() => new Date());
202
+ const alive = options.alive ?? processAlive;
203
+ const ttl = options.ttlMs ?? LOCK_TTL_MS;
204
+ const wait = options.waitMs ?? LOCK_WAIT_MS;
205
+ const sleep =
206
+ options.sleep ??
207
+ /** @type {(ms: number) => Promise<void>} */ (
208
+ (ms) =>
209
+ new Promise((done) => {
210
+ setTimeout(() => done(), ms);
211
+ })
212
+ );
213
+ const started = now().getTime();
214
+ let waiting = false;
215
+ let broken = 0;
216
+ for (;;) {
217
+ const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}`;
218
+ try {
219
+ await writeFile(
220
+ temp,
221
+ `${JSON.stringify({ schemaVersion: 1, pid: process.pid, at: now().toISOString() })}\n`,
222
+ { mode: 0o600, flag: 'wx' },
223
+ );
224
+ await link(temp, path);
225
+ await unlink(temp).catch(() => undefined);
226
+ return { acquired: true, holder: process.pid };
227
+ } catch (error) {
228
+ await unlink(temp).catch(() => undefined);
229
+ if (!isRecord(error) || error.code !== 'EEXIST') return { acquired: false, holder: null };
230
+ }
231
+ const lock = lockRecord(await readOwnedJson(path));
232
+ if (lock === null || !alive(lock.pid) || now().getTime() - Date.parse(lock.at) > ttl) {
233
+ broken += 1;
234
+ if (broken > 3) return { acquired: false, holder: null };
235
+ await breakStaleLock(path, lock);
236
+ continue;
237
+ }
238
+ if (now().getTime() - started >= wait) return { acquired: false, holder: lock.pid };
239
+ if (!waiting) {
240
+ waiting = true;
241
+ options.onWait?.(lock.pid);
242
+ }
243
+ await sleep(LOCK_POLL_MS);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Remove a lock judged stale without removing one another waiter took in the
249
+ * meantime: the file is renamed aside (atomic), the record it holds is compared
250
+ * with the stale one, and a record that differs (a fresh holder) is put back under
251
+ * its name by `link`. Two waiters that read the same stale record can therefore not
252
+ * both end up holding the lock. Never throws.
253
+ * @param {string} path @param {LockRecord | null} stale
254
+ * @returns {Promise<boolean>} whether the stale lock was removed
255
+ */
256
+ export async function breakStaleLock(path, stale) {
257
+ const aside = `${path}.stale.${process.pid}.${Math.random().toString(16).slice(2)}`;
258
+ try {
259
+ await rename(path, aside);
260
+ } catch {
261
+ return false;
262
+ }
263
+ const current = lockRecord(await readOwnedJson(aside));
264
+ const same =
265
+ (current === null && stale === null) ||
266
+ (current !== null && stale !== null && current.pid === stale.pid && current.at === stale.at);
267
+ if (!same) {
268
+ // A holder that took the lock after our read: its lock goes back (EEXIST means a
269
+ // third process already created a new one; the moved record then goes, and that
270
+ // holder's release finds nothing of its own to remove).
271
+ await link(aside, path).catch(() => undefined);
272
+ }
273
+ await unlink(aside).catch(() => undefined);
274
+ return same;
275
+ }
276
+
277
+ /** Remove a lock file when this process holds it. Never throws. @param {string} path */
278
+ export async function releaseFileLock(path) {
279
+ const lock = lockRecord(await readOwnedJson(path));
280
+ if (lock !== null && lock.pid === process.pid) await unlink(path).catch(() => undefined);
281
+ }
282
+
283
+ /**
284
+ * `npm view <package>@<version> dist.integrity` with the same npm (FR6): `ok`
285
+ * with the SRI line, `unavailable` when npm fails or prints anything else.
286
+ * Every npm subprocess runs in `cwd`, the client's private `<state>/release/npm`:
287
+ * npm reads a project-level `.npmrc` from its working directory and expands
288
+ * `${VAR}` from the environment in it, so the user's own directory (a cloned
289
+ * repository, say) must never be where npm runs.
290
+ * @param {string} npm @param {string} packageName @param {string} version
291
+ * @param {NodeJS.ProcessEnv} env @param {string} cwd
292
+ * @returns {RegistryIntegrity}
293
+ */
294
+ export function registryIntegrity(npm, packageName, version, env, cwd) {
295
+ const result = spawnSync(npm, ['view', `${packageName}@${version}`, 'dist.integrity'], {
296
+ cwd,
297
+ env: safeEnvironment(env),
298
+ encoding: 'utf8',
299
+ stdio: ['ignore', 'pipe', 'pipe'],
300
+ timeout: VIEW_TIMEOUT_MS,
301
+ });
302
+ if (result.error || result.status !== 0) return { status: 'unavailable' };
303
+ const line =
304
+ String(result.stdout ?? '')
305
+ .trim()
306
+ .split(/\r?\n/u)[0]
307
+ ?.trim() ?? '';
308
+ return SRI_SHA512.test(line) ? { status: 'ok', integrity: line } : { status: 'unavailable' };
309
+ }
310
+
311
+ /**
312
+ * `npm install -g --prefix <prefix> --ignore-scripts … <package>@<version>`:
313
+ * the user's own prefix, scripts off, no audit or progress noise (FR6).
314
+ * @param {InstallInput} input @returns {Promise<boolean>}
315
+ */
316
+ export function installClient(input) {
317
+ return new Promise((resolvePromise) => {
318
+ const child = spawn(
319
+ input.npm,
320
+ [
321
+ 'install',
322
+ '-g',
323
+ '--prefix',
324
+ input.prefix.prefix,
325
+ '--ignore-scripts',
326
+ '--no-audit',
327
+ '--no-fund',
328
+ '--no-progress',
329
+ `${input.packageName}@${input.version}`,
330
+ ],
331
+ { cwd: input.cwd, env: safeEnvironment(input.env), stdio: 'ignore' },
332
+ );
333
+ // Own timer, unreferenced: spawn's `timeout` only clears on `exit`, which a
334
+ // failed spawn (npm missing) never emits, and it would then hold the process.
335
+ const timer = setTimeout(() => {
336
+ if (child.exitCode === null) child.kill('SIGTERM');
337
+ }, INSTALL_TIMEOUT_MS);
338
+ timer.unref();
339
+ let settled = false;
340
+ /** @param {boolean} ok */
341
+ const finish = (ok) => {
342
+ if (settled) return;
343
+ settled = true;
344
+ clearTimeout(timer);
345
+ resolvePromise(ok);
346
+ };
347
+ child.once('error', () => finish(false));
348
+ child.once('close', (code, signal) => finish(signal === null && code === 0));
349
+ });
350
+ }
351
+
352
+ /**
353
+ * The version an installed `cli.mjs` reports, through this node (FR6 verify).
354
+ * @param {string} cliPath @param {NodeJS.ProcessEnv} env
355
+ */
356
+ export function installedVersionAt(cliPath, env) {
357
+ const result = spawnSync(process.execPath, [cliPath, '--version'], {
358
+ env: safeEnvironment(env),
359
+ encoding: 'utf8',
360
+ stdio: ['ignore', 'pipe', 'pipe'],
361
+ timeout: VERSION_TIMEOUT_MS,
362
+ });
363
+ if (result.error || result.status !== 0) return null;
364
+ const match = VERSION_OUTPUT.exec(String(result.stdout ?? '').trim());
365
+ return match === null ? null : (match[1] ?? null);
366
+ }
367
+
368
+ /**
369
+ * Run the freshly installed client with the original arguments and
370
+ * `AISAC_REEXEC=<version>`, forwarding the terminal and the signals (FR6).
371
+ * @param {{ cliPath: string, args: string[], version: string, env: NodeJS.ProcessEnv,
372
+ * stdio?: 'inherit' | 'pipe' }} input
373
+ * @returns {Promise<{ code: number, stdout: string }>}
374
+ */
375
+ export function reexecClient(input) {
376
+ return new Promise((resolvePromise) => {
377
+ const stdio = input.stdio ?? 'inherit';
378
+ const child = spawn(process.execPath, [input.cliPath, ...input.args], {
379
+ env: { ...input.env, [REEXEC_ENV]: input.version },
380
+ stdio,
381
+ });
382
+ let stdout = '';
383
+ child.stdout?.on('data', (chunk) => {
384
+ stdout += chunk;
385
+ });
386
+ /** @type {NodeJS.Signals[]} */
387
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
388
+ // In a terminal the foreground process group already delivers SIGINT and
389
+ // SIGHUP to the child; forwarding them would double every Ctrl-C. SIGTERM is
390
+ // addressed to this process alone, so it is passed on. The listeners also
391
+ // keep this process alive until the child exits.
392
+ const terminal = stdin.isTTY === true;
393
+ /** @type {Map<NodeJS.Signals, () => void>} */
394
+ const handlers = new Map(
395
+ signals.map((signal) => [
396
+ signal,
397
+ () => {
398
+ if (child.exitCode === null && (signal === 'SIGTERM' || !terminal)) child.kill(signal);
399
+ },
400
+ ]),
401
+ );
402
+ for (const [signal, handler] of handlers) process.on(signal, handler);
403
+ let settled = false;
404
+ /** @param {number} code */
405
+ const finish = (code) => {
406
+ if (settled) return;
407
+ settled = true;
408
+ for (const [signal, handler] of handlers) process.removeListener(signal, handler);
409
+ resolvePromise({ code, stdout });
410
+ };
411
+ child.once('error', () => finish(1));
412
+ child.once('close', (code, signal) =>
413
+ finish(signal === null ? (code ?? 1) : 128 + (osConstants.signals[signal] ?? 0)),
414
+ );
415
+ });
416
+ }
417
+
418
+ /**
419
+ * The npm that owns the installation (FR6 "the same npm"): the prefix's own
420
+ * `bin/npm` (a version manager's node, say), else the one beside this node,
421
+ * else the first on PATH.
422
+ * @param {NodeJS.ProcessEnv} env @param {InstallPrefix | null} prefix
423
+ */
424
+ export function findNpm(env, prefix) {
425
+ const candidates = [
426
+ prefix === null ? null : join(prefix.prefix, 'bin', 'npm'),
427
+ join(dirname(process.execPath), 'npm'),
428
+ ];
429
+ for (const candidate of candidates)
430
+ if (candidate !== null && isExecutable(candidate)) return candidate;
431
+ return resolveNative('npm', env);
432
+ }
433
+
434
+ /** @param {string} path */
435
+ function isExecutable(path) {
436
+ try {
437
+ accessSync(path, constants.X_OK);
438
+ return statSync(path).isFile();
439
+ } catch {
440
+ return false;
441
+ }
442
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aisac/cli",
3
- "version": "0.4.0-beta.18",
3
+ "version": "0.4.0-beta.21",
4
4
  "private": false,
5
5
  "description": "AISAC client for Claude Code and Codex: AI Brain memory, context management and AISAC Engineering",
6
6
  "license": "UNLICENSED",