aptly 0.1.13 → 0.1.15

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/bin/aptly.js CHANGED
@@ -38,7 +38,7 @@ try {
38
38
  throw new Error('update_invalid_options');
39
39
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
40
40
  const result = updateGlobalInstallation({ packageRoot });
41
- output(result.status === 'complete' ? { ...result, next_steps: ['aptly setup', 'aptly set transmission --review'] } : result);
41
+ output(result.status === 'complete' ? { ...result, next_steps: ['aptly setup', 'aptly set transmission --review'], ...(process.platform !== 'win32' ? { stable_launcher_update_note: 'Existing stable registrations retain their snapshot until an explicit per-client migration; run aptly setup --help for --migrate-launcher --launcher stable.' } : {}) } : result);
42
42
  if (result.status === 'error')
43
43
  process.exitCode = 1;
44
44
  else if (process.stderr.isTTY && !process.env.CI)
@@ -220,6 +220,7 @@ try {
220
220
  let dryRun = false;
221
221
  let includeExisting = false;
222
222
  let policySource = false;
223
+ let launcher;
223
224
  const seen = new Set();
224
225
  for (let i = 0; i < args.length; i++) {
225
226
  const flag = args[i];
@@ -249,6 +250,8 @@ try {
249
250
  const value = args[++i];
250
251
  if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
251
252
  clients = value === 'all' ? ['codex', 'claude'] : [value];
253
+ else if (flag === '--launcher' && command === 'setup' && value === 'stable')
254
+ launcher = 'stable';
252
255
  else if (flag === '--policy-source' && command === 'setup' && value === 'codex-home')
253
256
  policySource = true;
254
257
  else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
@@ -261,7 +264,7 @@ try {
261
264
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
262
265
  if ((check && [...seen].some(flag => !['--check', '--client'].includes(flag))) || (migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || (policySource && (clients.length !== 1 || clients[0] !== 'codex' || [...seen].some(flag => !['--client', '--policy-source', '--dry-run'].includes(flag)))) || (dryRun && !migrate && !policySource) || (includeExisting && !migrate))
263
266
  throw new Error('setup_invalid_options');
264
- let result = policySource ? setPolicySource({ clients, packageRoot }, dryRun) : check ? checkSetup({ clients, packageRoot }) : migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
267
+ let result = policySource ? setPolicySource({ clients, packageRoot }, dryRun) : check ? checkSetup({ clients, packageRoot }) : migrate ? migrateLauncher({ clients, packageRoot, launcher }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission, launcher }) : removeSetup({ clients });
265
268
  if (command === 'setup' && !check && !migrate && !policySource && !automatic && transmission === undefined)
266
269
  result = await reviewAfterSetup(result, { clients, packageRoot });
267
270
  output(result);
@@ -20,9 +20,9 @@ const entries = {
20
20
  'stats disable': { usage: 'aptly stats disable [--client codex|claude|all]', description: 'Disable Aptly collection and remove unchanged product-owned observer definitions. Preserve statistics/key/history, custom or modified observers and all routing settings. Retained modified definitions are reported for local review.', options: { '--client': client } },
21
21
  budget: { usage: 'aptly budget status [--client codex|claude|all]', description: 'Inspect local per-ledger budget limits and reserved usage. No reset/refill command is provided.' },
22
22
  'budget status': { usage: 'aptly budget status [--client codex|claude|all]', description: 'Read registered host budget settings and ledger metadata; defaults to both clients. No credentials, provider calls, configuration writes or ledger/gate initialization.\nLiteral 0 ceilings display Unlimited; reservations are not OpenAI billing. This is a registration/permitted-environment snapshot, not verification of running custom launchers. An existing gate is held briefly and can be busy.', options: { '--client': client } },
23
- setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]\n aptly setup --client codex --policy-source codex-home [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing requires --migrate-launcher. --policy-source codex-home explicitly binds an existing owned Codex setup to the runtime CODEX_HOME using a reserved selector and forwarded CODEX_HOME; it preserves policy, ledger and statistics state. CLI commands select ~/.codex when CODEX_HOME is absent; an explicit override selects that account home and invalid overrides are rejected. MCP startup still requires a forwarded absolute CODEX_HOME, including the default home; missing values fail closed. Use it in the canonical registration and intended account homes when a manager mirrors MCP tables. --dry-run validates either migration without writing. Policy-source migration requires --client codex and cannot combine with other setup actions. Upgrade all MCP backends first; restart MCP afterward.\nOrdinary interactive setup reviews unreviewed transmission choices, including existing registrations; Enter keeps configured scopes or selects none for unselected clients. --automatic, --check and launcher migration never prompt. Explicit --transmission records that choice without asking. No keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--policy-source': ['codex-home'], '--include-existing': true, '--dry-run': true } },
23
+ setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--launcher stable] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--launcher stable] [--include-existing] [--dry-run]\n aptly setup --client codex --policy-source codex-home [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. --launcher stable explicitly selects a POSIX-only private immutable runtime outside versioned Node installs; for existing direct registrations combine it with --migrate-launcher. The snapshot includes the package and production dependencies, not Node itself. A supported installed Node is still required. Existing stable registrations stay stable, including later migrations without the flag. Default/automatic installations keep direct Node registrations. Modified/custom launchers remain unchanged. Stable migration updates owned statistics observers in the same host transaction; direct-to-direct legacy migration retains its separate observer refresh contract and may report statistics_observer_migration_required; keys, history and collection/native-metadata choices remain unchanged. Old/shared snapshots are retained after remove. Windows stable mode is unsupported; the existing direct mode remains available. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing requires --migrate-launcher. --policy-source codex-home explicitly binds an existing owned Codex setup to the runtime CODEX_HOME using a reserved selector and forwarded CODEX_HOME; it preserves policy, ledger and statistics state. CLI commands and MCP startup select ~/.codex under the OS user home when CODEX_HOME is absent; an explicit absolute override takes precedence. Explicitly empty, relative or control-character-containing overrides are rejected. A custom host that omits CODEX_HOME uses the default home policy and transmission scope. Custom account homes are not discovered automatically; account managers must forward the intended CODEX_HOME. This default-home MCP fallback is available starting with 0.1.15; published 0.1.14 requires explicit forwarding even for the default home. Use it in the canonical registration and intended account homes when a manager mirrors MCP tables. --dry-run validates either migration without writing. Policy-source migration requires --client codex and cannot combine with other setup actions. Upgrade all MCP backends first; restart MCP afterward.\nOrdinary interactive setup reviews unreviewed transmission choices, including existing registrations; Enter keeps configured scopes or selects none for unselected clients. --automatic, --check and launcher migration never prompt. Explicit --transmission records that choice without asking. No keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--launcher': ['stable'], '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--policy-source': ['codex-home'], '--include-existing': true, '--dry-run': true } },
24
24
  remove: { usage: 'aptly remove [--client codex|claude|all]', description: 'Remove only unchanged Aptly-owned registration for both clients by default. Preserve modified/user-owned entries, keys and ledger history. Restart host/MCP after removal.', options: { '--client': client } },
25
- update: { usage: 'aptly update', description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. Local/source/unverified installations are rejected. Lifecycle setup is not run: run aptly setup and restart hosts afterward. Existing launchers and keys are preserved. Update does not run setup or a new CLI process: next interactive setup/set default reviews pending transmission choices; use aptly set transmission --review for an explicit review. The first upgrade from older code requires a subsequent setup/default command to load this behavior.' },
25
+ update: { usage: 'aptly update', description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. Local/source/unverified installations are rejected. Lifecycle setup is not run: run aptly setup and restart hosts afterward. Existing stable registrations retain their selected snapshot until explicit per-client --migrate-launcher --launcher stable; plain setup reports stable_snapshot_outdated when versions differ. Existing launchers and keys are preserved. Update does not run setup or a new CLI process: next interactive setup/set default reviews pending transmission choices; use aptly set transmission --review for an explicit review. The first upgrade from older code requires a subsequent setup/default command to load this behavior.' },
26
26
  doctor: { usage: 'aptly doctor [--client codex|claude|all]', description: 'Read local registration, policy, package version and bounded ledger metadata as JSON. No launcher execution, credential-store query, provider/network call, state creation or update notification. Complete (exit 0) means the query completed, not host readiness; partial (exit 1) means an observation failed. Runtime version, Hook trust/execution, restart need and retry ticket usage remain unknown. Ledgers above 4 MiB are not scanned. A missing first-use ledger has unknown history. Scan time includes validation/rechecks; write timing is not measured. Existing report exports are separate and unchanged.', options: { '--client': client } },
27
27
  report: { usage: 'aptly report [--format md|json|both] [--output-dir DIR]', description: 'Write redacted local diagnostic attachments. Default format: both; directory: reports. No uploads or classification API probes. Review attachments before sharing.', options: { '--format': ['md', 'json', 'both'], '--output-dir': 'path' } },
28
28
  };
@@ -53,6 +53,8 @@ export declare function collectDoctor(options?: DoctorOptions): {
53
53
  retry_ticket_usage: "unknown";
54
54
  credential_validity: "unknown";
55
55
  status: string;
56
+ stable_snapshot_outdated?: boolean | undefined;
57
+ recovery?: string[] | undefined;
56
58
  registration: string;
57
59
  registered_package: {
58
60
  status: string;
@@ -80,5 +82,6 @@ export declare function collectDoctor(options?: DoctorOptions): {
80
82
  credential_validity: "unknown";
81
83
  status: string;
82
84
  code: string;
85
+ recovery?: string[] | undefined;
83
86
  })[];
84
87
  };
@@ -1,8 +1,9 @@
1
1
  /** Read-only local observations, deliberately separate from legacy report schema v1. */
2
- import { dirname, isAbsolute, join, resolve } from 'node:path';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { parse } from 'smol-toml';
5
5
  import { resolveHostPaths } from './host-paths.js';
6
+ import { validateStableRegistration, stableRuntimeLimits, stableReference } from './stable-runtime.js';
6
7
  import { QuerySnapshot } from './query-snapshot.js';
7
8
  import { queryAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
8
9
  import { validateLedgerState } from './core.js';
@@ -15,7 +16,7 @@ function fail(code) { throw new Error(code); }
15
16
  const version = (value) => typeof value === 'string' && /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/.test(value) ? value : null;
16
17
  const json = (bytes) => { const value = JSON.parse(bytes.toString('utf8')); if (!isRecord(value))
17
18
  fail('invalid_configuration'); return value; };
18
- const observationCode = (error) => error instanceof Error && error.message === 'concurrent_configuration_change' ? 'changed_during_observation' : error instanceof Error && ['invalid_ledger', 'invalid_outcome', 'invalid_usage'].includes(error.message) ? 'invalid_ledger' : error instanceof Error && ['invalid_configuration', 'invalid_policy', 'invalid_policy_binding', 'missing_hook_registration', 'invalid_ledger_binding'].includes(error.message) ? error.message : 'configuration_observation_failed';
19
+ const observationCode = (error) => error instanceof Error && error.message === 'concurrent_configuration_change' ? 'changed_during_observation' : error instanceof Error && ['invalid_ledger', 'invalid_outcome', 'invalid_usage'].includes(error.message) ? 'invalid_ledger' : error instanceof Error && ['stable_runtime_unverified', 'registered_node_missing', 'registered_package_missing', 'invalid_configuration', 'invalid_policy', 'invalid_policy_binding', 'missing_hook_registration', 'invalid_ledger_binding'].includes(error.message) ? error.message : 'configuration_observation_failed';
19
20
  /** No lock, load, state initialization, provider or filesystem mutation. */
20
21
  export function observeDoctorLedger(path, snapshot) {
21
22
  const bytes = snapshot.size(path, { privateFile: true, singleLink: true });
@@ -29,6 +30,9 @@ export function observeDoctorLedger(path, snapshot) {
29
30
  const records = Object.values(state.requests);
30
31
  return { ...base, status: 'validated_bounded_snapshot', counts: { total: records.length, complete: records.filter(r => r.state === 'complete').length, unknown: records.filter(r => r.state === 'unknown').length } };
31
32
  }
33
+ function directNodeShape(entry) {
34
+ return typeof entry.command === 'string' && isAbsolute(entry.command) && ['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) && Array.isArray(entry.args) && entry.args.length === 1 && typeof entry.args[0] === 'string' && isAbsolute(entry.args[0]) && /(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]) && !Object.hasOwn(entry, 'url');
35
+ }
32
36
  function standardEntry(entry) {
33
37
  return entry.command === process.execPath && Array.isArray(entry.args) && entry.args.length === 1 && typeof entry.args[0] === 'string' && isAbsolute(entry.args[0]) && /(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]) && !Object.hasOwn(entry, 'url');
34
38
  }
@@ -84,10 +88,25 @@ export function collectDoctor(options = {}) {
84
88
  const permitted = (key) => client === 'claude' || forwarded.includes(key);
85
89
  // A permitted passthrough is a future host binding, not evidence from this terminal.
86
90
  const setting = (key) => Object.hasOwn(settings, key) ? settings[key] : undefined;
87
- const candidate = standardEntry(entry), target = candidate ? packageObservation(entry, snapshot) : { status: 'custom_or_remote_launcher', version: null };
88
- const standard = candidate && ['observed_numeric_release', 'unsupported_version_metadata'].includes(target.status);
91
+ if (directNodeShape(entry)) {
92
+ if (!snapshot.track(entry.command))
93
+ fail('registered_node_missing');
94
+ if (!snapshot.track(entry.args[0]))
95
+ fail('registered_package_missing');
96
+ }
97
+ const reference = stableReference(entry, { home: options.home });
98
+ if (reference) {
99
+ snapshot.read(reference.command, { privateFile: true, maxBytes: 65536 });
100
+ snapshot.read(join(reference.runtimeRoot, 'bootstrap.cjs'), { privateFile: true, maxBytes: 65536 });
101
+ snapshot.read(join(reference.runtimeRoot, 'manifest.json'), { privateFile: true, maxBytes: stableRuntimeLimits.manifestBytes });
102
+ snapshot.read(join(reference.runtimeRoot, 'payload/package.json'), { privateFile: true, maxBytes: 65536 });
103
+ }
104
+ const stable = validateStableRegistration(entry, { home: options.home, metadataOnly: true });
105
+ const candidate = standardEntry(entry), stableVersion = stable ? version(stable.version) : null;
106
+ const target = stable ? { status: stableVersion ? 'observed_numeric_release' : 'unsupported_version_metadata', version: stableVersion } : candidate ? packageObservation(entry, snapshot) : { status: 'custom_or_remote_launcher', version: null };
107
+ const standard = !!stable || (candidate && ['observed_numeric_release', 'unsupported_version_metadata'].includes(target.status));
89
108
  if (target.status === 'target_missing')
90
- fail('invalid_configuration');
109
+ fail('registered_package_missing');
91
110
  const raw = setting('APTLY_HOOK_POLICY_PATH');
92
111
  let source = 'unconfigured', policyStatus = 'unconfigured', transmission = null;
93
112
  if (!standard) {
@@ -145,7 +164,7 @@ export function collectDoctor(options = {}) {
145
164
  ledger = { status: 'not_declared', counts: null, write_timing: 'not_measured' };
146
165
  }
147
166
  snapshot.verify();
148
- return { ...base, status: 'complete', registration: standard ? 'standard_node_registration' : 'custom_or_remote_launcher', registered_package: target, policy: { source_kind: source, status: policyStatus, transmission }, hook_registration: hook, credential_reference: settings.APTLY_SECRET_BACKEND === 'os' ? 'os_reference' : Object.hasOwn(settings, 'OPENAI_API_KEY') ? 'inline_environment_present' : permitted('OPENAI_API_KEY') ? 'runtime_environment_permitted' : 'not_declared', ledger: { ...ledger, diagnostic_scan_ms: Math.max(0, performance.now() - started), timing_scope: 'full_client_observation_and_rechecks' } };
167
+ return { ...base, status: 'complete', ...(stable && stable.version !== VERSION ? { stable_snapshot_outdated: true, recovery: [`aptly setup --client ${client} --migrate-launcher${process.platform === 'win32' ? '' : ' --launcher stable'} --dry-run`] } : {}), registration: stable ? 'stable_runtime_registration' : standard ? 'standard_node_registration' : 'custom_or_remote_launcher', registered_package: target, policy: { source_kind: source, status: policyStatus, transmission }, hook_registration: hook, credential_reference: settings.APTLY_SECRET_BACKEND === 'os' ? 'os_reference' : Object.hasOwn(settings, 'OPENAI_API_KEY') ? 'inline_environment_present' : permitted('OPENAI_API_KEY') ? 'runtime_environment_permitted' : 'not_declared', ledger: { ...ledger, diagnostic_scan_ms: Math.max(0, performance.now() - started), timing_scope: 'full_client_observation_and_rechecks' } };
149
168
  }
150
169
  catch (error) {
151
170
  // A changed observation takes precedence over a parse/validation failure.
@@ -156,7 +175,7 @@ export function collectDoctor(options = {}) {
156
175
  if (changed instanceof Error && changed.message === 'concurrent_configuration_change')
157
176
  error = changed;
158
177
  }
159
- return { ...base, status: 'partial', code: observationCode(error) };
178
+ return { ...base, status: 'partial', code: observationCode(error), ...(['stable_runtime_unverified', 'registered_node_missing', 'registered_package_missing'].includes(observationCode(error)) ? { recovery: [`aptly setup --client ${client} --migrate-launcher${process.platform === 'win32' ? '' : ' --launcher stable'} --dry-run`] } : {}) };
160
179
  }
161
180
  });
162
181
  return { kind: 'aptly-doctor', schema_version: 1, status: clients.some(c => c.status === 'partial') ? 'partial' : 'complete', cli_version: VERSION, scope: 'local_configuration_snapshot', readiness: 'not_certified', clients };
package/dist/src/files.js CHANGED
@@ -58,7 +58,7 @@ export function readRegularFile(path, { privateFile = false, maxBytes = 65536 }
58
58
  throw new Error('unsafe_file');
59
59
  if (privateFile && process.platform === 'win32')
60
60
  assertWindowsPrivatePath(path);
61
- const buffer = Buffer.alloc(maxBytes + 1);
61
+ const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));
62
62
  let size = 0;
63
63
  while (size < buffer.length) {
64
64
  const count = readSync(fd, buffer, size, buffer.length - size, null);
@@ -66,7 +66,7 @@ export function readRegularFile(path, { privateFile = false, maxBytes = 65536 }
66
66
  break;
67
67
  size += count;
68
68
  }
69
- if (size > maxBytes)
69
+ if (size > maxBytes || size > stat.size || fstatSync(fd).size !== stat.size)
70
70
  throw new Error('unsafe_file');
71
71
  return buffer.subarray(0, size);
72
72
  }
@@ -1,3 +1,3 @@
1
1
  export declare const CODEX_HOME_POLICY_SOURCE = "@codex-home";
2
- /** Resolve only the explicit Codex selector; existing fixed paths remain unchanged. */
3
- export declare function resolvePolicySource(value: string | undefined, env: NodeJS.ProcessEnv, _home?: string): string | undefined;
2
+ /** Resolve an explicit override or the OS default; never discover custom account homes. */
3
+ export declare function resolvePolicySource(value: string | undefined, env: NodeJS.ProcessEnv, home?: string): string | undefined;
@@ -1,10 +1,11 @@
1
1
  import { isAbsolute, join } from 'node:path';
2
+ import { homedir } from 'node:os';
2
3
  export const CODEX_HOME_POLICY_SOURCE = '@codex-home';
3
- /** Resolve only the explicit Codex selector; existing fixed paths remain unchanged. */
4
- export function resolvePolicySource(value, env, _home) {
4
+ /** Resolve an explicit override or the OS default; never discover custom account homes. */
5
+ export function resolvePolicySource(value, env, home) {
5
6
  if (value !== CODEX_HOME_POLICY_SOURCE)
6
7
  return value;
7
- const codexHome = env.CODEX_HOME;
8
+ const codexHome = env.CODEX_HOME === undefined ? join(home ?? homedir(), '.codex') : env.CODEX_HOME;
8
9
  if (codexHome === undefined || !codexHome.trim() || !isAbsolute(codexHome) || /[\x00-\x1f\x7f-\x9f]/.test(codexHome))
9
10
  throw new Error('policy_source_home_invalid');
10
11
  return join(codexHome, 'aptly', 'auto-policy.json');
@@ -3,6 +3,7 @@ export interface SetupOptions {
3
3
  home?: string;
4
4
  env?: NodeJS.ProcessEnv;
5
5
  packageRoot?: string;
6
+ launcher?: 'stable';
6
7
  automatic?: boolean;
7
8
  clients?: Client[];
8
9
  mode?: 'defaults' | 'advisory';
package/dist/src/setup.js CHANGED
@@ -8,6 +8,7 @@ import { parse } from 'smol-toml';
8
8
  import { resolveCatalog } from './catalog.js';
9
9
  import { budgetEnvironmentDefaults, budgetEnvironmentKeys, parseBudgetValue, resolveBudgetSettings, budgetErrorDetails } from './budget.js';
10
10
  import { Router, defaultPolicy } from './core.js';
11
+ import { planStableRuntime, materializeStableRuntime, validateStableRegistration, stableReference, stableObserverCommand } from './stable-runtime.js';
11
12
  import { resolveHostPaths as resolved } from './host-paths.js';
12
13
  import { QuerySnapshot } from './query-snapshot.js';
13
14
  import { loadAutomaticHookPolicy, queryAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
@@ -361,7 +362,21 @@ function ownership(value, client) {
361
362
  return value;
362
363
  }
363
364
  /** Compatibility restriction only: this does not authenticate arbitrary launcher code. */
364
- function requireCredentialRuntime(entry, root) {
365
+ function requireCredentialRuntime(entry, root, home, planned) {
366
+ const plannedMatch = planned && entry.command === planned.descriptor.command && isDeepStrictEqual(entry.args, planned.descriptor.args);
367
+ const stable = plannedMatch ? null : validateStableRegistration(entry, { home });
368
+ if (stable || plannedMatch) {
369
+ const payload = stable?.packageRoot ?? root;
370
+ try {
371
+ const server = read(join(payload, 'dist/src/server.js')).text, runtime = read(join(payload, 'dist/src/runtime.js')).text;
372
+ if (!server?.includes('./runtime.js') || !runtime?.includes('APTLY_SECRET_BACKEND') || !runtime.includes('APTLY_SECRET_CLIENT'))
373
+ fail('credential_launcher_unverified');
374
+ }
375
+ catch {
376
+ fail('credential_launcher_unverified');
377
+ }
378
+ return;
379
+ }
365
380
  const allowed = [join(root, 'dist', 'src', 'server.js'), join(root, 'src', 'server.ts')];
366
381
  const incompatible = (reason) => { throw Object.assign(new Error('credential_launcher_unverified'), { reason }); };
367
382
  if (entry.command !== process.execPath)
@@ -413,6 +428,7 @@ function prepare(options, client, removing, edit) {
413
428
  if (privateFile.before !== null)
414
429
  privatePermissions(privateFile.path, 'private_file_permissions');
415
430
  observations.push(mcp, hooks, policy, manifest);
431
+ let stableRuntime;
416
432
  const oldOwner = manifest.before === null ? undefined : ownership(json(manifest.before), client);
417
433
  if (removing && !oldOwner) {
418
434
  if (read(join(privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null)
@@ -486,11 +502,21 @@ function prepare(options, client, removing, edit) {
486
502
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
487
503
  const additions = { APTLY_HOOK_POLICY_PATH: policyPath, ROUTER_LEDGER_PATH: join(stateDir, 'ledger.json') };
488
504
  let created = false, tomlBlock;
505
+ // Explicit migration may replace an exact-owned unavailable/older generation.
506
+ // Its bytes are never executed or trusted for credential injection; only the
507
+ // replacement made from this CLI's verified source is used after commit.
508
+ const ownedStableMigration = edit && 'migrate' in edit && oldOwner?.mcp_created && isDeepStrictEqual(servers.aptly, oldOwner.mcp) ? stableReference(servers.aptly, { home: options.home }) : null;
509
+ const existingStable = ownedStableMigration ?? validateStableRegistration(servers.aptly, { home: options.home });
510
+ if (options.launcher === 'stable' && servers.aptly !== undefined && !existingStable && !(edit && 'migrate' in edit))
511
+ fail('stable_launcher_migration_required');
512
+ const stableRequested = options.launcher === 'stable' || !!existingStable;
513
+ if (stableRequested && (servers.aptly === undefined || !!(edit && 'migrate' in edit)))
514
+ stableRuntime = planStableRuntime({ packageRoot: root, home: options.home });
489
515
  if (edit && 'migrate' in edit) {
490
516
  if (!oldOwner || !object(servers.aptly) || (oldOwner.mcp_created ? !isDeepStrictEqual(servers.aptly, oldOwner.mcp) : !edit.includeExisting))
491
517
  fail('launcher_migration_not_owned');
492
518
  const entry = servers.aptly;
493
- if (typeof entry.command !== 'string' || !isAbsolute(entry.command) || !['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) || !Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string' || !isAbsolute(entry.args[0]) || !/(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]))
519
+ if (!existingStable && (typeof entry.command !== 'string' || !isAbsolute(entry.command) || !['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) || !Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string' || !isAbsolute(entry.args[0]) || !/(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0])))
494
520
  fail('launcher_migration_not_standard');
495
521
  if (!entries.some(entry => isDeepStrictEqual(entry, oldOwner.hook)) || !isDeepStrictEqual(json(policy.before), oldOwner.policy))
496
522
  fail('managed_entry_changed');
@@ -500,7 +526,7 @@ function prepare(options, client, removing, edit) {
500
526
  }
501
527
  if (servers.aptly === undefined) {
502
528
  created = true;
503
- servers.aptly = { ...(client === 'claude' ? { type: 'stdio' } : {}), command: process.execPath, args: [join(root, 'dist', 'src', 'server.js')], ...(client === 'codex' ? { env_vars: ['OPENAI_API_KEY'] } : {}), env: { ROUTER_PROVIDER: edit && 'defaults' in edit ? 'decisions' : env.ROUTER_PROVIDER === 'fixture' ? 'fixture' : 'decisions', ...additions } };
529
+ servers.aptly = { ...(client === 'claude' ? { type: 'stdio' } : {}), command: stableRuntime?.descriptor.command ?? process.execPath, args: stableRuntime?.descriptor.args ?? [join(root, 'dist', 'src', 'server.js')], ...(client === 'codex' ? { env_vars: ['OPENAI_API_KEY'] } : {}), env: { ROUTER_PROVIDER: edit && 'defaults' in edit ? 'decisions' : env.ROUTER_PROVIDER === 'fixture' ? 'fixture' : 'decisions', ...additions } };
504
530
  }
505
531
  else {
506
532
  if (!object(servers.aptly))
@@ -523,11 +549,11 @@ function prepare(options, client, removing, edit) {
523
549
  mcp.after = client === 'codex' ? addTomlEnv(mcp.before ?? '', missing) : stringify(config);
524
550
  }
525
551
  if (edit && 'migrate' in edit) {
526
- servers.aptly.command = process.execPath;
527
- servers.aptly.args = [join(root, 'dist', 'src', 'server.js')];
552
+ servers.aptly.command = stableRuntime?.descriptor.command ?? process.execPath;
553
+ servers.aptly.args = stableRuntime?.descriptor.args ?? [join(root, 'dist', 'src', 'server.js')];
528
554
  }
529
555
  if ((edit && ('credential' in edit || 'migrate' in edit)) || servers.aptly.env?.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE)
530
- requireCredentialRuntime(servers.aptly, root);
556
+ requireCredentialRuntime(servers.aptly, root, options.home, stableRuntime);
531
557
  const currentEnv = map(servers.aptly, 'env');
532
558
  const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedEnvironment = environmentInheritance(servers.aptly, env, client);
533
559
  const updates = edit ? editEnvironment(currentEnv, edit, client, inheritedEnvironment) : {};
@@ -632,6 +658,8 @@ function prepare(options, client, removing, edit) {
632
658
  result.transmission = effectiveTransmission(policyValue);
633
659
  result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
634
660
  manifest.after = stringify(owner);
661
+ if (edit && 'migrate' in edit && stableRuntime)
662
+ appendStatisticsLauncherMigration(options, client, root, servers.aptly, stableRuntime, policyPath, hooksObject, hooks, changes, observations);
635
663
  const review = transmissionReviewSnapshot(options, client);
636
664
  observations.push(review);
637
665
  if (requestedScope !== undefined) {
@@ -640,9 +668,12 @@ function prepare(options, client, removing, edit) {
640
668
  changes.push(review);
641
669
  }
642
670
  result.transmission_review = reviewMatches(review.after, options, client, policyValue) ? 'complete' : 'required';
671
+ const snapshotOutdated = !!existingStable && !stableRuntime && 'version' in existingStable && existingStable.version !== json(read(join(root, 'package.json')).text).version;
672
+ if (snapshotOutdated)
673
+ result.recovery = [`aptly setup --client ${client} --migrate-launcher --launcher stable --dry-run`];
643
674
  if (client === 'codex')
644
675
  result.requires_hook_review = true;
645
- result.codes = [...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined || result.budget?.restart_required ? ['mcp_restart_required'] : [])];
676
+ result.codes = [...(snapshotOutdated ? ['stable_snapshot_outdated'] : []), ...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined || result.budget?.restart_required ? ['mcp_restart_required'] : [])];
646
677
  dirs.push(dir, privateDir, stateDir);
647
678
  }
648
679
  // Validate complete desired data before any host file is changed.
@@ -656,7 +687,7 @@ function prepare(options, client, removing, edit) {
656
687
  const markerIndex = changes.findIndex(item => item.reviewPrivate);
657
688
  if (markerIndex >= 0)
658
689
  changes.push(...changes.splice(markerIndex, 1));
659
- return { changes, observations, dirs, result };
690
+ return { changes, observations, dirs, result, ...(stableRuntime ? { stableRuntime } : {}) };
660
691
  }
661
692
  /** Secure sibling staging is short-lived and never a backup; original settings stay in memory. */
662
693
  function replace(snapshot, forward) {
@@ -714,13 +745,15 @@ function policyRecovery(client) {
714
745
  }
715
746
  function errorResult(client, error) {
716
747
  const detail = error?.policyConflict;
717
- return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : {}) };
748
+ return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : ['stable_runtime_unverified', 'stable_runtime_busy', 'stable_snapshot_outdated'].includes(safeCode(error)) ? { recovery: [`aptly setup --client ${client} --migrate-launcher --launcher stable --dry-run`, 'Review unavailable, modified or busy runtime state locally; do not delete shared generations or locks while referenced or being written.'] } : {}) };
718
749
  }
719
750
  function execute(options, removing, edit, captured) {
720
751
  const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
721
752
  if (clients.some(client => client !== 'codex' && client !== 'claude'))
722
753
  return { status: 'partial', clients: [] };
723
754
  const env = options.env ?? process.env;
755
+ if (options.launcher !== undefined && (options.launcher !== 'stable' || removing || !!(edit && !('migrate' in edit))))
756
+ return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['stable_launcher_invalid_options'] })) };
724
757
  if (options.transmission !== undefined && !['none', 'description', 'excerpt'].includes(options.transmission))
725
758
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
726
759
  if (!removing && options.automatic && (env.APTLY_SKIP_SETUP === '1' || !!env.CI))
@@ -734,7 +767,7 @@ function execute(options, removing, edit, captured) {
734
767
  }
735
768
  });
736
769
  const results = prepared.map(plan => plan.result);
737
- if (edit && results.some(result => result.status === 'error'))
770
+ if ((edit || options.launcher === 'stable') && results.some(result => result.status === 'error'))
738
771
  return { status: 'partial', clients: results.map(result => result.status === 'error' ? result : { ...result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
739
772
  // Each host is independent; prepare every host before committing any host.
740
773
  for (const plan of prepared) {
@@ -743,6 +776,10 @@ function execute(options, removing, edit, captured) {
743
776
  const written = [], madeDirs = [];
744
777
  try {
745
778
  validateObservations(plan);
779
+ if (plan.stableRuntime) {
780
+ materializeStableRuntime(plan.stableRuntime);
781
+ validateObservations(plan);
782
+ }
746
783
  for (const path of plan.dirs) {
747
784
  noSymlinks(path);
748
785
  try {
@@ -797,18 +834,21 @@ function execute(options, removing, edit, captured) {
797
834
  }
798
835
  return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
799
836
  }
800
- const codes = new Set(['policy_source_home_invalid', 'policy_source_requires_setup', 'policy_source_invalid_options', 'transmission_review_requires_setup', 'transmission_review_invalid_options', 'statistics_requires_setup', 'statistics_policy_conflict', 'statistics_config_invalid', 'statistics_ownership_invalid', 'statistics_observers_present', 'statistics_key_missing', 'statistics_shared_state', 'statistics_platform_unsupported', 'statistics_invalid_options', 'statistics_observer_missing', 'unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
837
+ const codes = new Set(['stable_launcher_platform_unsupported', 'stable_runtime_unverified', 'stable_launcher_migration_required', 'stable_launcher_invalid_options', 'stable_source_unverified', 'stable_source_changed', 'stable_runtime_limit', 'stable_plan_unverified', 'stable_runtime_busy', 'policy_source_home_invalid', 'policy_source_requires_setup', 'policy_source_invalid_options', 'transmission_review_requires_setup', 'transmission_review_invalid_options', 'statistics_requires_setup', 'statistics_policy_conflict', 'statistics_config_invalid', 'statistics_ownership_invalid', 'statistics_observers_present', 'statistics_key_missing', 'statistics_shared_state', 'statistics_platform_unsupported', 'statistics_invalid_options', 'statistics_observer_missing', 'unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
801
838
  function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
802
839
  export function setupHosts(options = {}) { return execute(options, false); }
803
840
  /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
804
841
  export function checkSetup(options = {}) {
805
842
  const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
806
- if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined)
843
+ if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined || options.launcher !== undefined)
807
844
  return { status: 'partial', clients: [] };
808
845
  const results = clients.map(client => {
809
846
  try {
810
847
  const plan = prepare(options, client, false);
811
- return { ...plan.result, status: 'unchanged', codes: [plan.changes.length ? 'setup_check_configure_ready' : 'setup_check_ok', ...plan.result.codes] };
848
+ const paths = resolved(options, client), config = client === 'codex' ? toml(read(paths.mcpPath).text ?? '') : json(read(paths.mcpPath).text);
849
+ const command = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly?.command;
850
+ const pinned = typeof command === 'string' && /[\\/]\.nvm[\\/]versions[\\/]node[\\/]/.test(command);
851
+ return { ...plan.result, status: 'unchanged', codes: [plan.changes.length ? 'setup_check_configure_ready' : 'setup_check_ok', ...plan.result.codes, ...(pinned ? ['launcher_pinned_to_versioned_node'] : [])] };
812
852
  }
813
853
  catch (error) {
814
854
  return errorResult(client, error);
@@ -912,7 +952,7 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
912
952
  return { status: 'complete', clients: [{ client, status: 'unchanged', codes: [plan.changes.length ? 'launcher_migration_available' : 'launcher_current'], requires_hook_review: client === 'codex' }] };
913
953
  const result = execute(options, false, edit, [plan]);
914
954
  if (result.status === 'complete')
915
- result.clients[0].codes.push('launcher_migrated', 'mcp_restart_required');
955
+ result.clients[0].codes.push('launcher_migrated', 'mcp_restart_required', ...(!plan.stableRuntime && read(join(resolved(options, client).privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null ? ['statistics_observer_migration_required'] : []));
916
956
  return result;
917
957
  }
918
958
  catch (error) {
@@ -953,7 +993,7 @@ export function setPolicySource(options, dryRun = false) {
953
993
  if (!loadAutomaticHookPolicy(policyPath).policy || !isDeepStrictEqual(json(policy.before), owner.policy))
954
994
  fail('managed_policy_changed');
955
995
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
956
- requireCredentialRuntime(entry, root);
996
+ requireCredentialRuntime(entry, root, options.home);
957
997
  if (entry.env.CODEX_HOME !== undefined)
958
998
  fail('mcp_environment_conflict');
959
999
  if (entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((v) => typeof v !== 'string')))
@@ -1346,6 +1386,7 @@ function statisticEntries(value, event, create = false) {
1346
1386
  }
1347
1387
  function statisticsPolicy(options, client, requireRegistration = true) {
1348
1388
  const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
1389
+ let stable = null;
1349
1390
  if (requireRegistration) {
1350
1391
  const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
1351
1392
  const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
@@ -1353,25 +1394,56 @@ function statisticsPolicy(options, client, requireRegistration = true) {
1353
1394
  fail('statistics_requires_setup');
1354
1395
  if (!policyReferenceMatches(entry, client, policyPath, options))
1355
1396
  fail('statistics_policy_conflict');
1397
+ stable = validateStableRegistration(entry, { home: options.home });
1356
1398
  }
1357
1399
  const loaded = loadAutomaticHookPolicy(policyPath);
1358
1400
  if (!loaded.policy)
1359
1401
  fail('statistics_requires_setup');
1360
- return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory };
1402
+ return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory, stable };
1361
1403
  }
1362
- function statisticsHooks(root, client, policyPath) {
1404
+ function statisticsHooks(root, client, policyPath, stable) {
1363
1405
  const observer = join(root, 'dist', 'bin', 'aptly-observe.js');
1364
- if (read(observer).text === null)
1406
+ if (!stable && read(observer).text === null)
1365
1407
  fail('statistics_observer_missing');
1366
1408
  for (const path of [process.execPath, observer, policyPath])
1367
1409
  if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
1368
1410
  fail('statistics_invalid_options');
1369
1411
  const quote = (v) => "'" + v.replaceAll("'", "'\\''") + "'";
1370
- const command = [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
1412
+ const command = stable ? stableObserverCommand(stable, client, policyPath) : [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
1371
1413
  const handler = { type: 'command', command, timeout: 5, statusMessage: 'Aptly local execution statistics' };
1372
1414
  const events = client === 'codex' ? ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'] : ['PostToolUse', 'SubagentStart', 'SubagentStop'];
1373
1415
  return Object.fromEntries(events.map(event => [event, { ...(event === 'PostToolUse' ? { matcher: client === 'codex' ? '^(spawn_agent|collaborationspawn_agent|collaboration\\.spawn_agent)$' : '^(Agent|Task)$' } : {}), hooks: [{ ...handler }] }]));
1374
1416
  }
1417
+ function appendStatisticsLauncherMigration(options, client, root, entry, planned, policyPath, hooksObject, hooks, changes, observations) {
1418
+ const paths = resolved(options, client), receipt = statisticsSnapshot(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
1419
+ observations.push(receipt);
1420
+ if (receipt.before === null) {
1421
+ for (const name of ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'])
1422
+ if (statisticEntries(hooksObject, name).some(possibleStatisticsObserver))
1423
+ fail('statistics_observers_present');
1424
+ return;
1425
+ }
1426
+ const owner = statisticsOwner(json(receipt.before), client), policy = loadAutomaticHookPolicy(policyPath).policy;
1427
+ if (!policy || owner.state_directory !== policy.state_directory)
1428
+ fail('statistics_policy_conflict');
1429
+ for (const [event, definition] of Object.entries(owner.hooks)) {
1430
+ const list = statisticEntries(hooksObject, event), matches = list.filter(v => isDeepStrictEqual(v, definition));
1431
+ if (matches.length !== 1)
1432
+ fail('managed_hook_changed');
1433
+ }
1434
+ const stable = planned ?? validateStableRegistration(entry, { home: options.home });
1435
+ const next = statisticsHooks(root, client, policyPath, stable);
1436
+ for (const [event, definition] of Object.entries(owner.hooks)) {
1437
+ const list = statisticEntries(hooksObject, event);
1438
+ list.splice(list.findIndex(v => isDeepStrictEqual(v, definition)), 1);
1439
+ }
1440
+ for (const [event, definition] of Object.entries(next))
1441
+ statisticEntries(hooksObject, event, true).push(definition);
1442
+ receipt.after = stringify({ ...owner, hooks: next, hooks_fingerprint: createHash('sha256').update(JSON.stringify(next)).digest('hex') });
1443
+ hooks.after = stringify(hooksObject);
1444
+ if (receipt.after !== receipt.before)
1445
+ changes.push(receipt);
1446
+ }
1375
1447
  function statisticsSnapshot(path) { const value = read(path); if (value.text !== null) {
1376
1448
  privatePermissions(path, 'private_file_permissions');
1377
1449
  if (lstatSync(path).nlink !== 1)
@@ -1386,7 +1458,7 @@ function statisticsConfig(snapshot) {
1386
1458
  return value;
1387
1459
  }
1388
1460
  function possibleStatisticsObserver(entry) {
1389
- return object(entry) && Array.isArray(entry.hooks) && entry.hooks.some((h) => object(h) && h.type === 'command' && (h.statusMessage === 'Aptly local execution statistics' || (typeof h.command === 'string' && h.command.includes('aptly-observe.js'))));
1461
+ return object(entry) && Array.isArray(entry.hooks) && entry.hooks.some((h) => object(h) && h.type === 'command' && (h.statusMessage === 'Aptly local execution statistics' || (typeof h.command === 'string' && (h.command.includes('aptly-observe.js') || /[\/]aptly[\/]runtimes[\/][a-f0-9]{64}[\/]launch['"]?\s+['"]?observe\b/.test(h.command)))));
1390
1462
  }
1391
1463
  function clearCodexMetadata(state, client) { if (client === 'codex') {
1392
1464
  delete state.codex_native_metadata;
@@ -1537,7 +1609,7 @@ export function setStatisticsCollection(enabled, options = {}) {
1537
1609
  state.codex_home = paths.dir;
1538
1610
  }
1539
1611
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
1540
- const entries = statisticsHooks(root, client, paths.policyPath);
1612
+ const entries = statisticsHooks(root, client, paths.policyPath, paths.stable);
1541
1613
  for (const [event, entry] of Object.entries(entries)) {
1542
1614
  const list = statisticEntries(value, event, true);
1543
1615
  if (list.some(possibleStatisticsObserver))
@@ -0,0 +1,61 @@
1
+ export declare const stableRuntimeLimits: Readonly<{
2
+ files: 12000;
3
+ totalBytes: number;
4
+ fileBytes: number;
5
+ manifestBytes: number;
6
+ }>;
7
+ export interface StableFile {
8
+ readonly path: string;
9
+ readonly size: number;
10
+ readonly sha256: string;
11
+ }
12
+ export interface StableManifest {
13
+ readonly schema_version: 1;
14
+ readonly kind: 'aptly-stable-runtime';
15
+ readonly version: string;
16
+ readonly home: string;
17
+ readonly node_path: string;
18
+ readonly launcher_revision: 1;
19
+ readonly bootstrap_sha256: string;
20
+ readonly launcher_sha256: string;
21
+ readonly files: readonly StableFile[];
22
+ readonly generation: string;
23
+ }
24
+ export interface StableRegistration {
25
+ readonly command: string;
26
+ readonly args: readonly ['serve'];
27
+ readonly packageRoot: string;
28
+ readonly runtimeRoot: string;
29
+ readonly version: string;
30
+ readonly generation: string;
31
+ readonly manifest: StableManifest;
32
+ readonly integrity: 'full' | 'metadata';
33
+ }
34
+ export interface StableRuntimePlan extends StableRegistration {
35
+ readonly descriptor: {
36
+ readonly command: string;
37
+ readonly args: readonly ['serve'];
38
+ };
39
+ readonly payloadRoot: string;
40
+ }
41
+ export interface StableReference {
42
+ readonly command: string;
43
+ readonly args: readonly ['serve'];
44
+ readonly generation: string;
45
+ readonly runtimeRoot: string;
46
+ }
47
+ /** Shape only. Reads OS alias metadata, never runtime bytes or credentials. */
48
+ export declare function stableReference(entry: unknown, { home }?: {
49
+ home?: string;
50
+ }): StableReference | null;
51
+ export declare function planStableRuntime(options: {
52
+ packageRoot: string;
53
+ home?: string;
54
+ nodePath?: string;
55
+ }): StableRuntimePlan;
56
+ export declare function materializeStableRuntime(plan: StableRuntimePlan): void;
57
+ export declare function validateStableRegistration(entry: unknown, { home, metadataOnly }?: {
58
+ home?: string;
59
+ metadataOnly?: boolean;
60
+ }): StableRegistration | null;
61
+ export declare function stableObserverCommand(registration: StableRegistration, client: 'codex' | 'claude', policyPath: string): string;