@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +146 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +846 -14
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +641 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +276 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +390 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +1557 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +403 -47
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/manager/bus.mjs +1921 -0
  35. package/dist/manager/delegation.mjs +354 -0
  36. package/dist/manager/hooks.mjs +918 -0
  37. package/dist/manager/launch-role.mjs +476 -0
  38. package/dist/manager/mcp-stdio.mjs +463 -0
  39. package/dist/manager/messages.mjs +791 -0
  40. package/dist/manager/reserve.mjs +2166 -0
  41. package/dist/manager/room.mjs +106 -0
  42. package/dist/manager/server.mjs +1792 -0
  43. package/dist/manager/status.mjs +118 -0
  44. package/dist/manager/watch.mjs +87 -0
  45. package/dist/manager/worker.mjs +2793 -0
  46. package/dist/manager/workers-cli.mjs +1403 -0
  47. package/dist/mcp-servers.mjs +192 -0
  48. package/dist/mcp.mjs +10 -2
  49. package/dist/monitor.mjs +76 -1
  50. package/dist/package.json +1 -1
  51. package/dist/platform.mjs +78 -29
  52. package/dist/release-manifest-public-keys.json +10 -0
  53. package/dist/release-manifest.json +328 -0
  54. package/dist/release-manifest.mjs +817 -0
  55. package/dist/release-settings.mjs +210 -0
  56. package/dist/self-update.mjs +1036 -0
  57. package/dist/state.mjs +25 -1
  58. package/dist/token-guide.mjs +132 -0
  59. package/dist/update-actions.mjs +442 -0
  60. package/package.json +1 -1
@@ -0,0 +1,1036 @@
1
+ // @ts-check
2
+ /**
3
+ * Client self-update (spec aisac-release-manifest FR6, FR8, FR10; ADR-0056 R3).
4
+ *
5
+ * The decision is a pure function of the running version, the resolved
6
+ * manifest, the settings, the environment, the attempt record and the state of
7
+ * the npm prefix, so every row of the FR6 table is a test. The actions
8
+ * (`update-actions.mjs`) touch
9
+ * only the prefix that owns the running client (with the same `npm`, scripts
10
+ * off, never with privileges) and the client's own state directory. An update
11
+ * never runs under a live session: the installed package is loaded by absolute
12
+ * path by the hooks, the Codex terminal and the monitor. It moves only upward,
13
+ * only to the version the signed manifest lists for the user's channel, and
14
+ * only when the registry serves that version with the manifest's integrity.
15
+ */
16
+ import { join } from 'node:path';
17
+ import { stdin, stdout } from 'node:process';
18
+ import { createInterface } from 'node:readline/promises';
19
+ import { liveLaunchCount, readStoredLocale, resolvePackLocale } from './engineering-pack.mjs';
20
+ import { atomicJson, ensurePrivateDirectory } from './state.mjs';
21
+ import {
22
+ RELEASE_STATE_DIRECTORY,
23
+ SEMVER,
24
+ compareVersions,
25
+ resolveReleaseManifest,
26
+ } from './release-manifest.mjs';
27
+ import {
28
+ CONSENT_VERSION,
29
+ NO_SELF_UPDATE_ENV,
30
+ effectiveUpdateMode,
31
+ installedPackageName,
32
+ readReleaseSettings,
33
+ updateCommandLine,
34
+ writeReleaseSettings,
35
+ } from './release-settings.mjs';
36
+ import {
37
+ REEXEC_ENV,
38
+ SRI_SHA512,
39
+ acquireUpdateLock,
40
+ findNpm,
41
+ installClient,
42
+ installPrefix,
43
+ installedVersionAt,
44
+ isInstant,
45
+ isRecord,
46
+ npmWorkingDirectory,
47
+ prefixWritable,
48
+ readOwnedJson,
49
+ reexecClient,
50
+ registryIntegrity,
51
+ releaseUpdateLock,
52
+ } from './update-actions.mjs';
53
+ // The actions keep their public names here: tests and callers import one module.
54
+ export {
55
+ INSTALL_TIMEOUT_MS,
56
+ LOCK_WAIT_MS,
57
+ NPM_WORKING_DIRECTORY,
58
+ REEXEC_ENV,
59
+ UPDATE_LOCK_FILE,
60
+ acquireUpdateLock,
61
+ findNpm,
62
+ installClient,
63
+ installPrefix,
64
+ installedVersionAt,
65
+ npmWorkingDirectory,
66
+ prefixWritable,
67
+ reexecClient,
68
+ registryIntegrity,
69
+ releaseUpdateLock,
70
+ } from './update-actions.mjs';
71
+
72
+ /** `<state>/release/client.json`: previous and current versions, last attempt (FR6). */
73
+ export const CLIENT_RECORD_FILE = 'client.json';
74
+ /** `<state>/release/last-launch.json`: manifest, host and update of the last launch (FR10). */
75
+ export const LAST_LAUNCH_FILE = 'last-launch.json';
76
+ /** After a failed install, no retry of the same sequence before this (FR6). */
77
+ export const UPDATE_BACKOFF_MS = 24 * 60 * 60 * 1000;
78
+ const YES_ANSWERS = new Set(['y', 'yes', 's', 'sim']);
79
+
80
+ /** The closed reason codes this module reports (FR10). */
81
+ export const UPDATE_REASONS = Object.freeze([
82
+ 'update_available',
83
+ 'update_mode_off',
84
+ 'self_update_disabled',
85
+ 'consent_pending',
86
+ 'manifest_expired',
87
+ 'manifest_unavailable',
88
+ 'update_channel_unlisted',
89
+ 'update_prefix_unknown',
90
+ 'update_prefix_not_writable',
91
+ 'update_privileged',
92
+ 'update_sessions_running',
93
+ 'update_in_progress',
94
+ 'update_integrity_mismatch',
95
+ 'update_registry_unavailable',
96
+ 'update_install_failed',
97
+ 'update_verify_failed',
98
+ 'update_restore_failed',
99
+ 'update_backoff',
100
+ 'update_rolled_back',
101
+ 'client_below_minimum',
102
+ ]);
103
+ const ATTEMPT_RESULTS = Object.freeze([
104
+ 'updated',
105
+ 'install_failed',
106
+ 'verify_failed',
107
+ 'restore_failed',
108
+ 'integrity_mismatch',
109
+ 'registry_unavailable',
110
+ 'rolled_back',
111
+ ]);
112
+
113
+ /**
114
+ * @typedef {import('./release-manifest.mjs').ResolvedManifest} ResolvedManifest
115
+ * @typedef {import('./release-settings.mjs').ReleaseSettings} ReleaseSettings
116
+ * @typedef {import('./release-settings.mjs').UpdateMode} UpdateMode
117
+ * @typedef {import('./engineering-pack.mjs').PackLocale} PackLocale
118
+ * @typedef {'updated' | 'install_failed' | 'verify_failed' | 'integrity_mismatch' | 'rolled_back'
119
+ * | 'registry_unavailable' | 'restore_failed'} AttemptResult
120
+ * @typedef {{ sequence: number, at: string, result: AttemptResult, from: string, to: string }} Attempt
121
+ * @typedef {{ version: string, at: string }} VersionRecord
122
+ * @typedef {{ schemaVersion: 1, current: VersionRecord | null, previous: VersionRecord | null,
123
+ * lastAttempt: Attempt | null }} ClientRecord
124
+ * @typedef {import('./update-actions.mjs').InstallPrefix} InstallPrefix
125
+ * @typedef {import('./update-actions.mjs').InstallInput} InstallInput
126
+ * @typedef {import('./update-actions.mjs').RegistryIntegrity} RegistryIntegrity
127
+ * @typedef {import('./update-actions.mjs').UpdateLock} UpdateLock
128
+ * @typedef {import('./update-actions.mjs').LockOptions} LockOptions
129
+ * @typedef {{ action: 'none' | 'notify' | 'install' | 'blocked', reason: string | null,
130
+ * mode: UpdateMode, channel: string, current: string, available: string | null,
131
+ * minimum: string | null, integrity: string | null, command: string, belowMinimum: boolean,
132
+ * packageName: string }} Decision
133
+ * @typedef {{ current: string, manifest: ResolvedManifest, settings: ReleaseSettings,
134
+ * env: NodeJS.ProcessEnv, packageName: string, record: ClientRecord, now: Date,
135
+ * liveSessions: number, prefix: InstallPrefix | null, writable: boolean, privileged: boolean,
136
+ * explicit?: boolean }} DecisionInput
137
+ * @typedef {{
138
+ * resolveManifest: typeof resolveReleaseManifest,
139
+ * liveSessions: (root: string) => Promise<number>,
140
+ * prefixWritable: (...directories: string[]) => Promise<boolean>,
141
+ * registryIntegrity: (npm: string, packageName: string, version: string, env: NodeJS.ProcessEnv, cwd: string) => RegistryIntegrity,
142
+ * installClient: (input: InstallInput) => Promise<boolean>,
143
+ * installedVersionAt: (cliPath: string, env: NodeJS.ProcessEnv) => string | null,
144
+ * reexec: (input: { cliPath: string, args: string[], version: string, env: NodeJS.ProcessEnv }) => Promise<{ code: number }>,
145
+ * ask: (locale: PackLocale) => Promise<UpdateMode | null>,
146
+ * findNpm: (env: NodeJS.ProcessEnv, prefix: InstallPrefix | null) => string | null,
147
+ * isPrivileged: () => boolean,
148
+ * acquireLock: (root: string, options: LockOptions) => Promise<UpdateLock>,
149
+ * releaseLock: (root: string) => Promise<void>,
150
+ * }} UpdateDependencies
151
+ * @typedef {{ kind: 'skipped' }
152
+ * | { kind: 'continue', lines: string[], decision: Decision }
153
+ * | { kind: 'reexec', exitCode: number }
154
+ * | { kind: 'blocked', reason: 'client_below_minimum' | 'update_in_progress', line: string }} LaunchUpdateOutcome
155
+ * @typedef {{ root: string, packageRoot: string, version: string, env: NodeJS.ProcessEnv,
156
+ * readConfig: () => Promise<{ endpoint: string, token: string } | null>, interactive: boolean,
157
+ * log?: (line: string) => void, warn?: (line: string) => void, now?: () => Date,
158
+ * dependencies?: Partial<UpdateDependencies> }} UpdateCommandDeps
159
+ * @typedef {{ deps: UpdateCommandDeps, dependencies: UpdateDependencies,
160
+ * described: Awaited<ReturnType<typeof describeInstallation>>, manifest: ResolvedManifest,
161
+ * decision: Decision, prefix: InstallPrefix | null, record: ClientRecord, env: NodeJS.ProcessEnv,
162
+ * now: () => Date, locale: PackLocale, json: boolean, log: (line: string) => void,
163
+ * warn: (line: string) => void, emit: (extra: Record<string, unknown>) => void }} UpdateCommandContext
164
+ */
165
+
166
+ /** @param {unknown} value @returns {value is string} */
167
+ function isSemver(value) {
168
+ return typeof value === 'string' && value.length <= 64 && SEMVER.test(value);
169
+ }
170
+
171
+ /** @param {unknown} value @returns {VersionRecord | null | undefined} undefined = invalid */
172
+ function versionRecord(value) {
173
+ if (value === null) return null;
174
+ if (!isRecord(value) || !isSemver(value.version) || !isInstant(value.at)) return undefined;
175
+ return { version: value.version, at: value.at };
176
+ }
177
+
178
+ /** @returns {ClientRecord} */
179
+ function emptyRecord() {
180
+ return { schemaVersion: 1, current: null, previous: null, lastAttempt: null };
181
+ }
182
+
183
+ /** @param {string} root @returns {Promise<ClientRecord>} */
184
+ export async function readClientRecord(root) {
185
+ const value = await readOwnedJson(join(root, RELEASE_STATE_DIRECTORY, CLIENT_RECORD_FILE));
186
+ if (!isRecord(value) || value.schemaVersion !== 1) return emptyRecord();
187
+ const current = versionRecord(value.current);
188
+ const previous = versionRecord(value.previous);
189
+ if (current === undefined || previous === undefined) return emptyRecord();
190
+ /** @type {Attempt | null} */
191
+ let lastAttempt = null;
192
+ if (value.lastAttempt !== null) {
193
+ const attempt = value.lastAttempt;
194
+ if (
195
+ !isRecord(attempt) ||
196
+ typeof attempt.sequence !== 'number' ||
197
+ !Number.isSafeInteger(attempt.sequence) ||
198
+ attempt.sequence < 0 ||
199
+ !isInstant(attempt.at) ||
200
+ typeof attempt.result !== 'string' ||
201
+ !ATTEMPT_RESULTS.includes(attempt.result) ||
202
+ !isSemver(attempt.from) ||
203
+ !isSemver(attempt.to)
204
+ )
205
+ return emptyRecord();
206
+ lastAttempt = {
207
+ sequence: attempt.sequence,
208
+ at: attempt.at,
209
+ result: /** @type {AttemptResult} */ (attempt.result),
210
+ from: attempt.from,
211
+ to: attempt.to,
212
+ };
213
+ }
214
+ return { schemaVersion: 1, current, previous, lastAttempt };
215
+ }
216
+
217
+ /** @param {string} root @param {ClientRecord} record */
218
+ export async function writeClientRecord(root, record) {
219
+ const directory = await ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY));
220
+ await atomicJson(join(directory, CLIENT_RECORD_FILE), record);
221
+ }
222
+
223
+ /**
224
+ * The host of a launch as the record names it (FR10): the mode, the version it
225
+ * ran and the closed reason behind a `system` launch.
226
+ * @typedef {{ name: 'claude' | 'codex', mode: import('./release-settings.mjs').HostMode,
227
+ * version?: string | null, reason?: string | null }} LaunchRecordHost
228
+ */
229
+
230
+ /**
231
+ * The launch record (FR10): what the last launch knew, no paths, no tokens.
232
+ * @param {string} root
233
+ * @param {{ manifest: { sequence: number | null, source: string }, host: LaunchRecordHost,
234
+ * update: { from: string, to: string | null, result: string | null }, at: string }} record
235
+ */
236
+ async function writeLaunchRecord(root, record) {
237
+ const directory = await ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY));
238
+ await atomicJson(join(directory, LAST_LAUNCH_FILE), { schemaVersion: 1, ...record });
239
+ }
240
+
241
+ /**
242
+ * Add the host this launch resolved to the launch record (FR10, R4): the mode,
243
+ * the version and the reason, never a path, with this launch's time and the
244
+ * manifest it used. The `update` section stays what the update step last wrote
245
+ * (this launch's when it ran, else an earlier launch's): `at` is the launch time,
246
+ * `update` the last update decision.
247
+ * @param {string} root @param {Required<LaunchRecordHost>} host
248
+ * @param {{ sequence: number | null, source: string } | null} [manifest]
249
+ * @param {() => Date} [now]
250
+ */
251
+ export async function recordLaunchHost(root, host, manifest = null, now = () => new Date()) {
252
+ const directory = await ensurePrivateDirectory(join(root, RELEASE_STATE_DIRECTORY));
253
+ const current = await readOwnedJson(join(directory, LAST_LAUNCH_FILE));
254
+ const record = isRecord(current) && current.schemaVersion === 1 ? current : { schemaVersion: 1 };
255
+ await atomicJson(join(directory, LAST_LAUNCH_FILE), {
256
+ ...record,
257
+ at: now().toISOString(),
258
+ ...(manifest === null ? {} : { manifest }),
259
+ host,
260
+ });
261
+ }
262
+
263
+ /**
264
+ * The FR6 table as a function. `explicit` is `aisac update`: the command is
265
+ * the consent, the recorded attempt does not hold it back, but the kill
266
+ * switches (environment, signed `features`, expiry) and a live session still do.
267
+ * @param {DecisionInput} input @returns {Decision}
268
+ */
269
+ export function decideUpdate(input) {
270
+ const { current, manifest, settings, packageName, record, now } = input;
271
+ const channel = settings.update.channel;
272
+ const effective = effectiveUpdateMode(settings, input.env);
273
+ const explicit = input.explicit === true;
274
+ const mode = explicit && effective.reason !== 'update_disabled_by_env' ? 'auto' : effective.mode;
275
+ /** @type {Decision} */
276
+ const base = {
277
+ action: 'none',
278
+ reason: null,
279
+ mode: effective.mode,
280
+ channel,
281
+ current,
282
+ available: null,
283
+ minimum: null,
284
+ integrity: null,
285
+ command: updateCommandLine(packageName, channel),
286
+ belowMinimum: false,
287
+ packageName,
288
+ };
289
+ const document = manifest.manifest;
290
+ if (document === null) return { ...base, reason: 'manifest_unavailable' };
291
+ const minimum = document.client.minimum_version;
292
+ const belowMinimum = compareVersions(current, minimum) < 0;
293
+ const entry = document.client.channels[channel];
294
+ if (entry === undefined) {
295
+ return belowMinimum
296
+ ? { ...base, minimum, belowMinimum, action: 'blocked', reason: 'client_below_minimum' }
297
+ : { ...base, minimum, reason: 'update_channel_unlisted' };
298
+ }
299
+ const integrity = entry.integrity[packageName] ?? null;
300
+ const newer = compareVersions(current, entry.version) < 0;
301
+ /** @type {Decision} */
302
+ const outcome = {
303
+ ...base,
304
+ minimum,
305
+ belowMinimum,
306
+ available: newer ? entry.version : null,
307
+ integrity,
308
+ };
309
+ /** @type {Decision} */
310
+ const blocked = { ...outcome, action: 'blocked', reason: 'client_below_minimum' };
311
+ if (!newer) return belowMinimum ? blocked : outcome;
312
+ /** @param {string} reason @returns {Decision} */
313
+ const notify = (reason) => (belowMinimum ? blocked : { ...outcome, action: 'notify', reason });
314
+ /** @param {string} reason @returns {Decision} */
315
+ const none = (reason) => (belowMinimum ? blocked : { ...outcome, reason });
316
+ if (document.features.self_update === false) return none('self_update_disabled');
317
+ if (mode === 'off') return none('update_mode_off');
318
+ if (manifest.state === 'expired') return notify('manifest_expired');
319
+ if (mode === 'notify')
320
+ return notify(effective.reason === 'consent_pending' ? 'consent_pending' : 'update_available');
321
+ if (integrity === null || !SRI_SHA512.test(integrity)) return notify('update_integrity_mismatch');
322
+ const attempt = record.lastAttempt;
323
+ if (!explicit && attempt !== null && attempt.sequence === (manifest.sequence ?? 0)) {
324
+ if (attempt.result === 'integrity_mismatch') return notify('update_integrity_mismatch');
325
+ if (attempt.result === 'rolled_back') return notify('update_rolled_back');
326
+ if (
327
+ (attempt.result === 'install_failed' ||
328
+ attempt.result === 'verify_failed' ||
329
+ attempt.result === 'restore_failed' ||
330
+ attempt.result === 'registry_unavailable') &&
331
+ // |age|: a future-dated record (clock skew, a hand edit) is not an endless backoff.
332
+ Math.abs(now.getTime() - Date.parse(attempt.at)) < UPDATE_BACKOFF_MS
333
+ )
334
+ return notify('update_backoff');
335
+ }
336
+ if (input.liveSessions > 0) return notify('update_sessions_running');
337
+ if (input.privileged) return notify('update_privileged');
338
+ if (input.prefix === null) return notify('update_prefix_unknown');
339
+ if (!input.writable) return notify('update_prefix_not_writable');
340
+ return { ...outcome, action: 'install', reason: null };
341
+ }
342
+
343
+ /** @type {UpdateDependencies} */
344
+ const DEFAULT_DEPENDENCIES = {
345
+ resolveManifest: resolveReleaseManifest,
346
+ liveSessions: (root) => liveLaunchCount(root),
347
+ prefixWritable,
348
+ registryIntegrity,
349
+ installClient,
350
+ installedVersionAt,
351
+ reexec: (input) => reexecClient(input),
352
+ ask: (locale) => askReleaseConsent(locale),
353
+ findNpm: (env, prefix) => findNpm(env, prefix),
354
+ // A privileged process never installs (FR6 "never with privileges").
355
+ isPrivileged: () => typeof process.getuid === 'function' && process.getuid() === 0,
356
+ acquireLock: (root, options) => acquireUpdateLock(root, options),
357
+ releaseLock: (root) => releaseUpdateLock(root),
358
+ };
359
+
360
+ /**
361
+ * Check the registry, install, verify, record (FR6). Whatever goes wrong once
362
+ * npm has touched the prefix (a failed or interrupted install, another version
363
+ * reported), the running version is put back and read back once; the running
364
+ * process keeps serving this launch in every failure.
365
+ * @param {{ root: string, prefix: InstallPrefix, packageName: string, npm: string | null,
366
+ * target: { version: string, integrity: string | null }, sequence: number, current: string,
367
+ * env: NodeJS.ProcessEnv, now: () => Date, record: ClientRecord, deps: UpdateDependencies,
368
+ * locale: PackLocale, progress: (line: string) => void }} input
369
+ * @returns {Promise<{ result: AttemptResult, reason: string | null }>}
370
+ */
371
+ async function performUpdate(input) {
372
+ const { prefix, packageName, env, deps } = input;
373
+ const version = input.target.version;
374
+ const at = input.now().toISOString();
375
+ /** @param {AttemptResult} result @returns {Attempt} */
376
+ const attempt = (result) => ({
377
+ sequence: input.sequence,
378
+ at,
379
+ result,
380
+ from: input.current,
381
+ to: version,
382
+ });
383
+ /** @param {AttemptResult} result @param {string} reason */
384
+ const fail = async (result, reason) => {
385
+ await writeClientRecord(input.root, { ...input.record, lastAttempt: attempt(result) }).catch(
386
+ () => undefined,
387
+ );
388
+ return { result, reason };
389
+ };
390
+ if (input.npm === null) return fail('install_failed', 'update_install_failed');
391
+ const npm = input.npm;
392
+ const cwd = await npmWorkingDirectory(input.root).catch(() => null);
393
+ if (cwd === null) return fail('install_failed', 'update_install_failed');
394
+ const registry = deps.registryIntegrity(npm, packageName, version, env, cwd);
395
+ if (registry.status !== 'ok') return fail('registry_unavailable', 'update_registry_unavailable');
396
+ if (registry.integrity !== input.target.integrity)
397
+ return fail('integrity_mismatch', 'update_integrity_mismatch');
398
+ input.progress(updatingLine(input.current, version, input.locale));
399
+ const installed = await deps.installClient({ npm, prefix, packageName, version, env, cwd });
400
+ const reported = () => deps.installedVersionAt(prefix.cliPath, env);
401
+ if (installed && reported() === version) {
402
+ await writeClientRecord(input.root, {
403
+ schemaVersion: 1,
404
+ previous: { version: input.current, at },
405
+ current: { version, at },
406
+ lastAttempt: attempt('updated'),
407
+ }).catch(() => undefined);
408
+ return { result: 'updated', reason: null };
409
+ }
410
+ // npm failed, was interrupted, or left another version: put the running
411
+ // version back when it is not there any more, and read it back.
412
+ const restored =
413
+ reported() === input.current ||
414
+ ((await deps
415
+ .installClient({ npm, prefix, packageName, version: input.current, env, cwd })
416
+ .catch(() => false)) &&
417
+ reported() === input.current);
418
+ if (!restored) return fail('restore_failed', 'update_restore_failed');
419
+ return installed
420
+ ? fail('verify_failed', 'update_verify_failed')
421
+ : fail('install_failed', 'update_install_failed');
422
+ }
423
+
424
+ /** @param {PackLocale} locale */
425
+ export function releaseDisclosure(locale) {
426
+ return locale === 'pt-BR'
427
+ ? 'Atualizações e versões (AISAC): ao abrir uma sessão, o aisac busca no AI Brain, com o token da sua conta, um manifesto de versões assinado (envia a versão do cliente e o nome da ferramenta, Claude Code ou Codex). Com a sua autorização, ele pode atualizar-se para a versão listada no canal escolhido e, em versões futuras, instalar uma cópia fixada do Claude Code ou do Codex na própria pasta dele, sem tocar nas suas instalações. Cada parte pode ser desligada: `aisac setup --update-mode off|notify`, `AISAC_NO_SELF_UPDATE=1`.'
428
+ : 'Updates and versions (AISAC): when a session opens, aisac fetches a signed release manifest from AI Brain with your account token (it sends the client version and the tool name, Claude Code or Codex). With your permission it may update itself to the version listed on your channel and, in future releases, install a pinned copy of Claude Code or Codex under its own directory, never touching your installs. Each part can be turned off: `aisac setup --update-mode off|notify`, `AISAC_NO_SELF_UPDATE=1`.';
429
+ }
430
+
431
+ /** @param {PackLocale} locale */
432
+ function consentQuestion(locale) {
433
+ return locale === 'pt-BR'
434
+ ? 'Permitir que o aisac se atualize sozinho para as versões listadas? [s/N] '
435
+ : 'Allow aisac to update itself to the listed versions? [y/N] ';
436
+ }
437
+
438
+ /**
439
+ * The one-time question (FR7, D8). Null when there is no terminal or the user
440
+ * cancels: nothing is recorded and the client keeps behaving as `notify`.
441
+ * @param {PackLocale} locale @returns {Promise<UpdateMode | null>}
442
+ */
443
+ export async function askReleaseConsent(locale) {
444
+ if (!stdin.isTTY || !stdout.isTTY) return null;
445
+ const rl = createInterface({ input: stdin, output: stdout });
446
+ try {
447
+ const answer = await rl.question(`\n${releaseDisclosure(locale)}\n${consentQuestion(locale)}`);
448
+ return YES_ANSWERS.has(answer.trim().toLowerCase()) ? 'auto' : 'notify';
449
+ } catch {
450
+ return null;
451
+ } finally {
452
+ rl.close();
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Record the consent and the mode it sets; the channel and the host modes
458
+ * stay as they were unless the caller names them (FR7, FR5).
459
+ * @param {string} root @param {ReleaseSettings} settings @param {UpdateMode} mode
460
+ * @param {{ channel?: import('./release-settings.mjs').Channel, at?: string,
461
+ * hosts?: Partial<ReleaseSettings['hosts']> }} [options]
462
+ */
463
+ export async function recordReleaseConsent(root, settings, mode, options = {}) {
464
+ await writeReleaseSettings(
465
+ {
466
+ consent: { version: CONSENT_VERSION, at: options.at ?? new Date().toISOString() },
467
+ update: { mode, channel: options.channel ?? settings.update.channel },
468
+ hosts: { ...settings.hosts, ...options.hosts },
469
+ },
470
+ root,
471
+ );
472
+ }
473
+
474
+ /**
475
+ * One line on stderr with the command (FR6). Never a path, never raw npm output.
476
+ * @param {Decision} decision @param {PackLocale} locale
477
+ */
478
+ export function updateNotice(decision, locale) {
479
+ const pt = locale === 'pt-BR';
480
+ const { current, available, minimum, command, reason } = decision;
481
+ if (decision.action === 'blocked')
482
+ return pt
483
+ ? `aisac: ${current} está abaixo da versão mínima ${minimum}; atualize antes de abrir uma sessão: ${command}`
484
+ : `aisac: ${current} is below the minimum version ${minimum}; update before opening a session: ${command}`;
485
+ switch (reason) {
486
+ case 'update_available':
487
+ case 'consent_pending':
488
+ return pt
489
+ ? `aisac: ${available} disponível (você usa ${current}); atualize com: ${command}`
490
+ : `aisac: ${available} available (you run ${current}); update with: ${command}`;
491
+ case 'update_sessions_running':
492
+ return pt
493
+ ? `aisac: ${available} disponível; a atualização espera as sessões abertas terminarem (ou rode: ${command})`
494
+ : `aisac: ${available} available; the update waits for the open sessions to end (or run: ${command})`;
495
+ case 'update_prefix_not_writable':
496
+ case 'update_prefix_unknown':
497
+ return pt
498
+ ? `aisac: ${available} disponível; a pasta desta instalação não é gravável por este usuário; rode: ${command}`
499
+ : `aisac: ${available} available; this installation's directory is not writable by this user; run: ${command}`;
500
+ case 'manifest_expired':
501
+ return pt
502
+ ? `aisac: ${available} disponível; o manifesto de versões expirou e a atualização automática está suspensa; rode: ${command}`
503
+ : `aisac: ${available} available; the release manifest expired and automatic update is suspended; run: ${command}`;
504
+ case 'update_integrity_mismatch':
505
+ return pt
506
+ ? `aisac: ${available} disponível, mas a integridade no registro npm difere do manifesto; atualização recusada`
507
+ : `aisac: ${available} available, but the npm registry integrity differs from the manifest; update refused`;
508
+ case 'update_rolled_back':
509
+ return pt
510
+ ? `aisac: ${available} disponível; você voltou para ${current} (aisac update --rollback); rode \`aisac update\` para avançar`
511
+ : `aisac: ${available} available; you rolled back to ${current} (aisac update --rollback); run \`aisac update\` to move on`;
512
+ case 'update_restore_failed':
513
+ return pt
514
+ ? `aisac: a atualização para ${available} falhou e ${current} não pôde ser reinstalado; reinstale com: npm install -g ${decision.packageName}@${current}`
515
+ : `aisac: the update to ${available} failed and ${current} could not be reinstalled; reinstall with: npm install -g ${decision.packageName}@${current}`;
516
+ case 'update_privileged':
517
+ return pt
518
+ ? `aisac: ${available} disponível; o cliente não se atualiza com privilégios (root); rode como seu usuário: ${command}`
519
+ : `aisac: ${available} available; the client never updates itself with privileges (root); run as your user: ${command}`;
520
+ case 'update_registry_unavailable':
521
+ case 'update_backoff':
522
+ case 'update_install_failed':
523
+ case 'update_verify_failed':
524
+ return pt
525
+ ? `aisac: a atualização para ${available} falhou (${reason}); nova tentativa em 24 h, ou rode: ${command}`
526
+ : `aisac: the update to ${available} failed (${reason}); retry in 24 h, or run: ${command}`;
527
+ default:
528
+ return pt
529
+ ? `aisac: ${available} disponível (${reason}); ${command}`
530
+ : `aisac: ${available} available (${reason}); ${command}`;
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Nothing to install: the client is at or above the channel's version, or the
536
+ * manifest lists nothing for it (the reason then says why).
537
+ * @param {Decision} decision @param {PackLocale} locale
538
+ */
539
+ function upToDateLine(decision, locale) {
540
+ const why = decision.reason === null ? '' : ` (${decision.reason})`;
541
+ return locale === 'pt-BR'
542
+ ? `aisac: ${decision.current} está em dia no canal ${decision.channel}${why}.`
543
+ : `aisac: ${decision.current} is up to date on channel ${decision.channel}${why}.`;
544
+ }
545
+
546
+ /** @param {string} from @param {string} to @param {PackLocale} locale */
547
+ function updatingLine(from, to, locale) {
548
+ return locale === 'pt-BR'
549
+ ? `aisac: atualizando de ${from} para ${to}…`
550
+ : `aisac: updating from ${from} to ${to}…`;
551
+ }
552
+
553
+ /** @param {string} from @param {string} to @param {PackLocale} locale */
554
+ function updatedLine(from, to, locale) {
555
+ return locale === 'pt-BR'
556
+ ? `aisac: atualizado de ${from} para ${to}; reiniciando.`
557
+ : `aisac: updated from ${from} to ${to}; restarting.`;
558
+ }
559
+
560
+ /** @param {PackLocale} locale */
561
+ function waitingLine(locale) {
562
+ return locale === 'pt-BR'
563
+ ? 'aisac: outro aisac está atualizando; aguardando.'
564
+ : 'aisac: another aisac is updating; waiting.';
565
+ }
566
+
567
+ /** @param {PackLocale} locale */
568
+ function inProgressLine(locale) {
569
+ return locale === 'pt-BR'
570
+ ? 'aisac: outro aisac ainda está atualizando (update_in_progress); tente de novo em instantes.'
571
+ : 'aisac: another aisac is still updating (update_in_progress); try again in a moment.';
572
+ }
573
+
574
+ /** The manifest when nothing could be resolved at all. @returns {ResolvedManifest} */
575
+ function noManifest() {
576
+ return {
577
+ manifest: null,
578
+ source: 'none',
579
+ state: 'none',
580
+ reason: 'manifest_unavailable',
581
+ sequence: null,
582
+ keyId: null,
583
+ issuedAt: null,
584
+ expiresAt: null,
585
+ lastFetch: null,
586
+ };
587
+ }
588
+
589
+ /**
590
+ * Everything the decision needs about this installation, shared by the
591
+ * launch step, `aisac update` and doctor.
592
+ * @param {{ root: string, packageRoot: string, version: string, env: NodeJS.ProcessEnv,
593
+ * manifest: ResolvedManifest, now: Date, explicit?: boolean, deps: UpdateDependencies }} input
594
+ */
595
+ async function describeInstallation(input) {
596
+ const [settings, record, packageName, liveSessions] = await Promise.all([
597
+ readReleaseSettings(input.root),
598
+ readClientRecord(input.root),
599
+ installedPackageName(input.packageRoot),
600
+ input.deps.liveSessions(input.root).catch(() => 0),
601
+ ]);
602
+ const prefix = installPrefix(input.packageRoot);
603
+ const writable =
604
+ prefix === null
605
+ ? false
606
+ : await input.deps.prefixWritable(prefix.modulesDirectory, join(prefix.prefix, 'bin'));
607
+ const decision = decideUpdate({
608
+ current: input.version,
609
+ manifest: input.manifest,
610
+ settings,
611
+ env: input.env,
612
+ packageName,
613
+ record,
614
+ now: input.now,
615
+ liveSessions,
616
+ prefix,
617
+ writable,
618
+ privileged: input.deps.isPrivileged(),
619
+ ...(input.explicit === undefined ? {} : { explicit: input.explicit }),
620
+ });
621
+ return { settings, record, packageName, liveSessions, prefix, writable, decision };
622
+ }
623
+
624
+ /**
625
+ * The `update` section of `aisac doctor --json` (FR8).
626
+ * @param {{ root: string, packageRoot: string, version: string, env: NodeJS.ProcessEnv,
627
+ * manifest: ResolvedManifest | null, now?: Date, dependencies?: Partial<UpdateDependencies> }} input
628
+ */
629
+ export async function updateDoctorSection(input) {
630
+ const deps = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
631
+ const described = await describeInstallation({
632
+ root: input.root,
633
+ packageRoot: input.packageRoot,
634
+ version: input.version,
635
+ env: input.env,
636
+ manifest: input.manifest ?? noManifest(),
637
+ now: input.now ?? new Date(),
638
+ deps,
639
+ });
640
+ const { settings, record, decision } = described;
641
+ return {
642
+ mode: decision.mode,
643
+ channel: decision.channel,
644
+ consent: settings.consent?.at ?? null,
645
+ current: decision.current,
646
+ available: decision.available,
647
+ minimum: decision.minimum,
648
+ action: decision.action,
649
+ reason: decision.reason,
650
+ prefix_writable: described.prefix === null ? null : described.writable,
651
+ live_sessions: described.liveSessions,
652
+ last_check: input.manifest?.lastFetch?.at ?? null,
653
+ last_result: record.lastAttempt,
654
+ previous: record.previous?.version ?? null,
655
+ };
656
+ }
657
+
658
+ /**
659
+ * The launch-time step (FR6), before any host work: the one-time consent
660
+ * question on a terminal, the decision, and the update with re-exec when it
661
+ * applies. Never throws; a launch below `minimum_version`, or one that finds
662
+ * another launcher still updating, are the cases that stop the host.
663
+ * @param {{ root: string, packageRoot: string, version: string,
664
+ * config: { endpoint: string, token: string } | null, host: 'claude' | 'codex',
665
+ * argv: string[], env: NodeJS.ProcessEnv, interactive: boolean, now?: () => Date,
666
+ * dependencies?: Partial<UpdateDependencies> }} input
667
+ * @returns {Promise<LaunchUpdateOutcome>}
668
+ */
669
+ export async function selfUpdateAtLaunch(input) {
670
+ try {
671
+ return await launchUpdateStep(input);
672
+ } catch {
673
+ // The update step never costs a launch: whatever it holds is released and
674
+ // the host starts on the running client.
675
+ const deps = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
676
+ await deps.releaseLock(input.root).catch(() => undefined);
677
+ return { kind: 'skipped' };
678
+ }
679
+ }
680
+
681
+ /**
682
+ * The step itself; `selfUpdateAtLaunch` guards it.
683
+ * @param {Parameters<typeof selfUpdateAtLaunch>[0]} input
684
+ * @returns {Promise<LaunchUpdateOutcome>}
685
+ */
686
+ async function launchUpdateStep(input) {
687
+ const { env } = input;
688
+ // The re-exec marker is read once and removed, so no host or shell inherits
689
+ // it; only the running version's own marker means anything, and it never
690
+ // lifts the minimum-version block.
691
+ const reexeced = env[REEXEC_ENV];
692
+ delete env[REEXEC_ENV];
693
+ const reexecChild = reexeced === input.version;
694
+ const now = input.now ?? (() => new Date());
695
+ const deps = { ...DEFAULT_DEPENDENCIES, ...input.dependencies };
696
+ const locale = resolvePackLocale(await readStoredLocale(input.root), env);
697
+ const settings = await readReleaseSettings(input.root);
698
+ if (
699
+ !reexecChild &&
700
+ settings.consent === null &&
701
+ input.interactive &&
702
+ env[NO_SELF_UPDATE_ENV] !== '1'
703
+ ) {
704
+ const answer = await deps.ask(locale).catch(() => null);
705
+ if (answer !== null)
706
+ await recordReleaseConsent(input.root, settings, answer, { at: now().toISOString() }).catch(
707
+ () => undefined,
708
+ );
709
+ }
710
+ const manifest =
711
+ (await deps
712
+ .resolveManifest({
713
+ root: input.root,
714
+ packageRoot: input.packageRoot,
715
+ endpoint: input.config?.endpoint ?? null,
716
+ token: input.config?.token ?? null,
717
+ host: input.host,
718
+ now,
719
+ })
720
+ .catch(() => null)) ?? noManifest();
721
+ // One installer at a time, and no host under an install: the lock is taken
722
+ // before the live-session count and kept until this launch writes its own
723
+ // marker (launch.mjs releases it) or re-executes.
724
+ const lock = await deps.acquireLock(input.root, {
725
+ now,
726
+ onWait: () => process.stderr.write(`${waitingLine(locale)}\n`),
727
+ });
728
+ if (!lock.acquired && lock.holder !== null)
729
+ return { kind: 'blocked', reason: 'update_in_progress', line: inProgressLine(locale) };
730
+ const described = await describeInstallation({
731
+ root: input.root,
732
+ packageRoot: input.packageRoot,
733
+ version: input.version,
734
+ env,
735
+ manifest,
736
+ now: now(),
737
+ deps,
738
+ });
739
+ let { decision } = described;
740
+ if (reexecChild) {
741
+ if (!decision.belowMinimum) return { kind: 'skipped' };
742
+ await deps.releaseLock(input.root);
743
+ return {
744
+ kind: 'blocked',
745
+ reason: 'client_below_minimum',
746
+ line: updateNotice(decision, locale),
747
+ };
748
+ }
749
+ /** @type {{ from: string, to: string | null, result: string | null }} */
750
+ const update = { from: input.version, to: null, result: null };
751
+ if (decision.action === 'install' && described.prefix !== null && decision.available !== null) {
752
+ const outcome = await performUpdate({
753
+ root: input.root,
754
+ prefix: described.prefix,
755
+ packageName: described.packageName,
756
+ npm: deps.findNpm(env, described.prefix),
757
+ target: { version: decision.available, integrity: decision.integrity },
758
+ sequence: manifest.sequence ?? 0,
759
+ current: input.version,
760
+ env,
761
+ now,
762
+ record: described.record,
763
+ deps,
764
+ locale,
765
+ progress: (line) => process.stderr.write(`${line}\n`),
766
+ });
767
+ update.to = decision.available;
768
+ update.result = outcome.result;
769
+ if (outcome.result === 'updated') {
770
+ await writeLaunchRecord(input.root, {
771
+ at: now().toISOString(),
772
+ manifest: { sequence: manifest.sequence, source: manifest.source },
773
+ host: { name: input.host, mode: 'system' },
774
+ update,
775
+ }).catch(() => undefined);
776
+ process.stderr.write(`${updatedLine(input.version, decision.available, locale)}\n`);
777
+ await deps.releaseLock(input.root);
778
+ const { code } = await deps.reexec({
779
+ cliPath: described.prefix.cliPath,
780
+ args: input.argv,
781
+ version: decision.available,
782
+ env,
783
+ });
784
+ return { kind: 'reexec', exitCode: code };
785
+ }
786
+ decision = decision.belowMinimum
787
+ ? { ...decision, action: 'blocked', reason: 'client_below_minimum' }
788
+ : { ...decision, action: 'notify', reason: outcome.reason };
789
+ }
790
+ await writeLaunchRecord(input.root, {
791
+ at: now().toISOString(),
792
+ manifest: { sequence: manifest.sequence, source: manifest.source },
793
+ host: { name: input.host, mode: 'system' },
794
+ update,
795
+ }).catch(() => undefined);
796
+ if (decision.action === 'blocked') {
797
+ await deps.releaseLock(input.root);
798
+ return {
799
+ kind: 'blocked',
800
+ reason: 'client_below_minimum',
801
+ line: updateNotice(decision, locale),
802
+ };
803
+ }
804
+ return {
805
+ kind: 'continue',
806
+ lines: decision.action === 'notify' ? [updateNotice(decision, locale)] : [],
807
+ decision,
808
+ };
809
+ }
810
+
811
+ /** A usage error exits 2, like `aisac init` and `aisac scan`. @param {string} code */
812
+ function usageError(code) {
813
+ return Object.assign(new Error(code), { exitCode: 2 });
814
+ }
815
+
816
+ /**
817
+ * `aisac update [--check] [--rollback] [--yes] [--json]` (FR6). The command is
818
+ * the consent; without a terminal on stdin it needs `--yes`. `--check` acts on
819
+ * nothing; `--rollback` reinstalls the recorded previous version, the only
820
+ * downgrade (D7).
821
+ * @param {string[]} args @param {UpdateCommandDeps} deps
822
+ * @returns {Promise<number>} the exit code
823
+ */
824
+ export async function updateCommand(args, deps) {
825
+ const log = deps.log ?? ((line) => console.log(line));
826
+ const warn = deps.warn ?? ((line) => console.error(line));
827
+ const now = deps.now ?? (() => new Date());
828
+ const dependencies = { ...DEFAULT_DEPENDENCIES, ...deps.dependencies };
829
+ const allowed = new Set(['--check', '--rollback', '--yes', '--json']);
830
+ for (const argument of args)
831
+ if (!allowed.has(argument)) throw usageError('invalid_update_option');
832
+ if (new Set(args).size !== args.length) throw usageError('duplicate_update_option');
833
+ const check = args.includes('--check');
834
+ const rollback = args.includes('--rollback');
835
+ const json = args.includes('--json');
836
+ if (check && rollback) throw usageError('update_check_and_rollback_exclusive');
837
+ if (!check && !deps.interactive && !args.includes('--yes'))
838
+ throw usageError('update_yes_required');
839
+ const { env } = deps;
840
+ const locale = resolvePackLocale(await readStoredLocale(deps.root), env);
841
+ const config = await deps.readConfig().catch(() => null);
842
+ const manifest =
843
+ (await dependencies
844
+ .resolveManifest({
845
+ root: deps.root,
846
+ packageRoot: deps.packageRoot,
847
+ endpoint: config?.endpoint ?? null,
848
+ token: config?.token ?? null,
849
+ now,
850
+ ...(config === null ? {} : { force: true }),
851
+ })
852
+ .catch(() => null)) ?? noManifest();
853
+ const described = await describeInstallation({
854
+ root: deps.root,
855
+ packageRoot: deps.packageRoot,
856
+ version: deps.version,
857
+ env,
858
+ manifest,
859
+ now: now(),
860
+ explicit: true,
861
+ deps: dependencies,
862
+ });
863
+ const { decision, prefix, record } = described;
864
+ /** @param {Record<string, unknown>} extra */
865
+ const emit = (extra) => {
866
+ if (json)
867
+ log(
868
+ JSON.stringify({
869
+ action: decision.action,
870
+ reason: decision.reason,
871
+ mode: decision.mode,
872
+ channel: decision.channel,
873
+ current: decision.current,
874
+ available: decision.available,
875
+ minimum: decision.minimum,
876
+ manifest: { sequence: manifest.sequence, source: manifest.source, state: manifest.state },
877
+ prefix_writable: prefix === null ? null : described.writable,
878
+ live_sessions: described.liveSessions,
879
+ previous: record.previous?.version ?? null,
880
+ command: decision.command,
881
+ ...extra,
882
+ }),
883
+ );
884
+ };
885
+ if (check) {
886
+ emit({});
887
+ if (!json)
888
+ log(
889
+ decision.action === 'install'
890
+ ? locale === 'pt-BR'
891
+ ? `aisac: ${decision.available} disponível; \`aisac update\` instala.`
892
+ : `aisac: ${decision.available} available; \`aisac update\` installs it.`
893
+ : decision.available === null
894
+ ? upToDateLine(decision, locale)
895
+ : updateNotice(decision, locale),
896
+ );
897
+ return 0;
898
+ }
899
+ // The command is the consent; the lock still serializes it with a launch that
900
+ // may be installing, and it is held until the install or rollback ends.
901
+ const lock = await dependencies.acquireLock(deps.root, {
902
+ now,
903
+ onWait: () => warn(waitingLine(locale)),
904
+ });
905
+ if (!lock.acquired && lock.holder !== null) {
906
+ emit({ result: 'refused', reason: 'update_in_progress' });
907
+ if (!json) warn(inProgressLine(locale));
908
+ return 1;
909
+ }
910
+ try {
911
+ const context = {
912
+ deps,
913
+ dependencies,
914
+ described,
915
+ manifest,
916
+ decision,
917
+ prefix,
918
+ record,
919
+ env,
920
+ now,
921
+ locale,
922
+ json,
923
+ log,
924
+ warn,
925
+ emit,
926
+ };
927
+ return rollback ? await rollbackOnDemand(context) : await installOnDemand(context);
928
+ } finally {
929
+ await dependencies.releaseLock(deps.root);
930
+ }
931
+ }
932
+
933
+ /**
934
+ * `aisac update --rollback`: the recorded previous version, the only downgrade
935
+ * (D7), never below `minimum_version`, never under a live session.
936
+ * @param {UpdateCommandContext} context @returns {Promise<number>}
937
+ */
938
+ async function rollbackOnDemand(context) {
939
+ const { deps, dependencies, described, manifest, decision, prefix, record, env, now } = context;
940
+ const { locale, json, log, warn, emit } = context;
941
+ const previous = record.previous;
942
+ /** @param {string} reason */
943
+ const refuse = (reason) => {
944
+ emit({ result: 'refused', rollback: reason });
945
+ if (!json) warn(`aisac: rollback refused (${reason})`);
946
+ return 1;
947
+ };
948
+ if (previous === null) return refuse('update_no_previous');
949
+ if (decision.minimum !== null && compareVersions(previous.version, decision.minimum) < 0)
950
+ return refuse('client_below_minimum');
951
+ if (prefix === null) return refuse('update_prefix_unknown');
952
+ if (!described.writable) return refuse('update_prefix_not_writable');
953
+ if (described.liveSessions > 0) return refuse('update_sessions_running');
954
+ const npm = dependencies.findNpm(env, prefix);
955
+ if (npm === null) return refuse('update_install_failed');
956
+ const cwd = await npmWorkingDirectory(deps.root).catch(() => null);
957
+ if (cwd === null) return refuse('update_install_failed');
958
+ const at = now().toISOString();
959
+ const installed = await dependencies.installClient({
960
+ npm,
961
+ prefix,
962
+ packageName: described.packageName,
963
+ version: previous.version,
964
+ env,
965
+ cwd,
966
+ });
967
+ if (!installed) return refuse('update_install_failed');
968
+ if (dependencies.installedVersionAt(prefix.cliPath, env) !== previous.version)
969
+ return refuse('update_verify_failed');
970
+ await writeClientRecord(deps.root, {
971
+ schemaVersion: 1,
972
+ current: { version: previous.version, at },
973
+ previous: { version: deps.version, at },
974
+ lastAttempt: {
975
+ sequence: manifest.sequence ?? 0,
976
+ at,
977
+ result: 'rolled_back',
978
+ from: deps.version,
979
+ to: previous.version,
980
+ },
981
+ }).catch(() => undefined);
982
+ emit({ result: 'rolled_back', rollback: previous.version });
983
+ if (!json)
984
+ log(
985
+ locale === 'pt-BR'
986
+ ? `aisac: voltou para ${previous.version} (antes: ${deps.version}).`
987
+ : `aisac: rolled back to ${previous.version} (before: ${deps.version}).`,
988
+ );
989
+ return 0;
990
+ }
991
+
992
+ /**
993
+ * `aisac update`: the decision, then the install without a re-exec.
994
+ * @param {UpdateCommandContext} context @returns {Promise<number>}
995
+ */
996
+ async function installOnDemand(context) {
997
+ const { deps, dependencies, described, manifest, decision, prefix, record, env, now } = context;
998
+ const { locale, json, log, warn, emit } = context;
999
+ if (decision.action !== 'install' || prefix === null || decision.available === null) {
1000
+ emit({ result: decision.action === 'none' ? 'nothing' : 'refused' });
1001
+ if (!json) {
1002
+ if (decision.available === null) log(upToDateLine(decision, locale));
1003
+ else warn(updateNotice(decision, locale));
1004
+ }
1005
+ return decision.action === 'none' ? 0 : 1;
1006
+ }
1007
+ const outcome = await performUpdate({
1008
+ root: deps.root,
1009
+ prefix,
1010
+ packageName: described.packageName,
1011
+ npm: dependencies.findNpm(env, prefix),
1012
+ target: { version: decision.available, integrity: decision.integrity },
1013
+ sequence: manifest.sequence ?? 0,
1014
+ current: deps.version,
1015
+ env,
1016
+ now,
1017
+ record,
1018
+ deps: dependencies,
1019
+ locale,
1020
+ progress: (line) => {
1021
+ if (!json) warn(line);
1022
+ },
1023
+ });
1024
+ emit({ result: outcome.result });
1025
+ if (outcome.result === 'updated') {
1026
+ if (!json)
1027
+ log(
1028
+ locale === 'pt-BR'
1029
+ ? `aisac: atualizado de ${deps.version} para ${decision.available}.`
1030
+ : `aisac: updated from ${deps.version} to ${decision.available}.`,
1031
+ );
1032
+ return 0;
1033
+ }
1034
+ if (!json) warn(updateNotice({ ...decision, action: 'notify', reason: outcome.reason }, locale));
1035
+ return 1;
1036
+ }