aptly 0.1.12 → 0.1.13

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 (50) hide show
  1. package/dist/bin/aptly.js +16 -2
  2. package/dist/src/automatic-hook.d.ts +7 -0
  3. package/dist/src/automatic-hook.js +33 -15
  4. package/dist/src/cli-help.js +5 -4
  5. package/dist/src/context-retry.d.ts +10 -0
  6. package/dist/src/context-retry.js +16 -3
  7. package/dist/src/core.d.ts +2 -0
  8. package/dist/src/core.js +39 -35
  9. package/dist/src/doctor.d.ts +84 -0
  10. package/dist/src/doctor.js +163 -0
  11. package/dist/src/host-paths.d.ts +10 -0
  12. package/dist/src/host-paths.js +15 -0
  13. package/dist/src/query-snapshot.d.ts +17 -0
  14. package/dist/src/query-snapshot.js +112 -0
  15. package/dist/src/server.js +2 -0
  16. package/dist/src/setup.d.ts +7 -5
  17. package/dist/src/setup.js +155 -39
  18. package/dist/src/statistics.d.ts +48 -2
  19. package/dist/src/statistics.js +87 -6
  20. package/dist/src/version.d.ts +1 -1
  21. package/dist/src/version.js +1 -1
  22. package/docs/guide/en/advanced.md +6 -0
  23. package/docs/guide/en/configuration.md +3 -1
  24. package/docs/guide/en/installation.md +2 -2
  25. package/docs/guide/en/statistics.md +4 -0
  26. package/docs/guide/en/transmission.md +7 -5
  27. package/docs/guide/en/troubleshooting.md +4 -2
  28. package/docs/guide/en.md +2 -0
  29. package/docs/guide/ja/advanced.md +6 -0
  30. package/docs/guide/ja/configuration.md +3 -1
  31. package/docs/guide/ja/installation.md +2 -2
  32. package/docs/guide/ja/statistics.md +4 -0
  33. package/docs/guide/ja/transmission.md +7 -5
  34. package/docs/guide/ja/troubleshooting.md +4 -2
  35. package/docs/guide/ja.md +2 -0
  36. package/docs/guide/ko/advanced.md +6 -0
  37. package/docs/guide/ko/configuration.md +3 -1
  38. package/docs/guide/ko/installation.md +2 -2
  39. package/docs/guide/ko/statistics.md +4 -0
  40. package/docs/guide/ko/transmission.md +7 -5
  41. package/docs/guide/ko/troubleshooting.md +4 -2
  42. package/docs/guide/ko.md +2 -0
  43. package/docs/guide/zh-CN/advanced.md +6 -0
  44. package/docs/guide/zh-CN/configuration.md +3 -1
  45. package/docs/guide/zh-CN/installation.md +2 -2
  46. package/docs/guide/zh-CN/statistics.md +4 -0
  47. package/docs/guide/zh-CN/transmission.md +7 -5
  48. package/docs/guide/zh-CN/troubleshooting.md +4 -2
  49. package/docs/guide/zh-CN.md +2 -0
  50. package/package.json +1 -1
@@ -0,0 +1,10 @@
1
+ /** Shared CLI selection; never claims the home of a running host. */
2
+ export declare function resolveHostPaths(options: {
3
+ home?: string;
4
+ env?: NodeJS.ProcessEnv;
5
+ }, client: 'codex' | 'claude'): {
6
+ dir: string;
7
+ mcpPath: string;
8
+ hooksPath: string;
9
+ privateDir: string;
10
+ };
@@ -0,0 +1,15 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { CODEX_HOME_POLICY_SOURCE, resolvePolicySource } from './policy-source.js';
4
+ /** Shared CLI selection; never claims the home of a running host. */
5
+ export function resolveHostPaths(options, client) {
6
+ const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
7
+ const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
8
+ if (override && !isAbsolute(override))
9
+ throw new Error('relative_configuration_directory');
10
+ if (client === 'codex' && override !== undefined)
11
+ resolvePolicySource(CODEX_HOME_POLICY_SOURCE, env);
12
+ const dir = override || join(home, client === 'codex' ? '.codex' : '.claude');
13
+ const mcpPath = client === 'codex' ? join(dir, 'config.toml') : override ? join(dir, '.claude.json') : join(home, '.claude.json');
14
+ return { dir, mcpPath, hooksPath: join(dir, client === 'codex' ? 'hooks.json' : 'settings.json'), privateDir: join(dir, 'aptly') };
15
+ }
@@ -0,0 +1,17 @@
1
+ interface Options {
2
+ privateFile?: boolean;
3
+ directory?: boolean;
4
+ singleLink?: boolean;
5
+ identityOnly?: boolean;
6
+ maxBytes?: number;
7
+ }
8
+ export declare class QuerySnapshot {
9
+ private observations;
10
+ private remember;
11
+ track(path: string, options?: Options): boolean;
12
+ /** Checked size from the same observation later verified; does not read the body. */
13
+ size(path: string, options?: Options): number | null;
14
+ read(path: string, options?: Options): Buffer | null;
15
+ verify(): void;
16
+ }
17
+ export {};
@@ -0,0 +1,112 @@
1
+ /** Checked, bounded observations for read-only CLI queries; never an atomic multi-file snapshot. */
2
+ import { lstatSync, readlinkSync } from 'node:fs';
3
+ import { dirname, isAbsolute, resolve } from 'node:path';
4
+ import { assertPrivateStatePath, readRegularFile, systemAliasAllowed } from './files.js';
5
+ import { assertWindowsPrivatePath } from './windows-private.js';
6
+ function metadata(path) {
7
+ try {
8
+ const s = lstatSync(path);
9
+ if (s.isSymbolicLink() && !systemAliasAllowed(path, s, readlinkSync(path)))
10
+ throw new Error('unsafe_configuration_file');
11
+ return { dev: s.dev, ino: s.ino, mode: s.mode, uid: s.uid, gid: s.gid, nlink: s.nlink, size: s.size, mtime: s.mtimeMs, ctime: s.ctimeMs, directory: s.isDirectory() };
12
+ }
13
+ catch (error) {
14
+ if (error.code === 'ENOENT')
15
+ return null;
16
+ throw error;
17
+ }
18
+ }
19
+ function signature(value, identityOnly = false) {
20
+ if (value === null)
21
+ return 'absent';
22
+ const { dev, ino, mode, uid, gid, nlink, size, mtime, ctime, directory } = value;
23
+ return JSON.stringify(directory ? { dev, ino, mode, uid, gid, directory } : identityOnly ? { dev, ino, mode, uid, gid, nlink, directory } : { dev, ino, mode, uid, gid, nlink, size, mtime, ctime, directory });
24
+ }
25
+ export class QuerySnapshot {
26
+ observations = new Map();
27
+ remember(path, value, options = {}) {
28
+ const old = this.observations.get(path);
29
+ if (old && signature(old.metadata, old.options.identityOnly) !== signature(value, old.options.identityOnly))
30
+ throw new Error('concurrent_configuration_change');
31
+ if (!old)
32
+ this.observations.set(path, { metadata: value, options: { ...options } });
33
+ else
34
+ old.options = { ...old.options, ...options, privateFile: old.options.privateFile || options.privateFile, singleLink: old.options.singleLink || options.singleLink };
35
+ }
36
+ track(path, options = {}) {
37
+ if (typeof path !== 'string' || !isAbsolute(path))
38
+ throw new Error('unsafe_configuration_file');
39
+ path = resolve(path);
40
+ const value = metadata(path);
41
+ this.remember(path, value, options);
42
+ for (let parent = dirname(path);; parent = dirname(parent)) {
43
+ this.remember(parent, metadata(parent), { directory: true, identityOnly: true });
44
+ if (dirname(parent) === parent)
45
+ break;
46
+ }
47
+ if (value === null) {
48
+ // Missing content does not make an existing insecure private parent safe.
49
+ if (options.privateFile && !options.directory && this.observations.get(dirname(path))?.metadata !== null)
50
+ assertPrivateStatePath(path);
51
+ return false;
52
+ }
53
+ if (options.directory ? !value.directory : value.directory || (value.mode & 0o170000) !== 0o100000)
54
+ throw new Error('unsafe_configuration_file');
55
+ if (options.singleLink && !value.directory && value.nlink !== 1)
56
+ throw new Error('unsafe_configuration_file');
57
+ if (options.privateFile) {
58
+ if (options.directory) {
59
+ if (process.platform === 'win32')
60
+ assertWindowsPrivatePath(path);
61
+ else if ((value.mode & 0o077) || (process.getuid && value.uid !== process.getuid()))
62
+ throw new Error('private_directory_permissions');
63
+ }
64
+ else
65
+ assertPrivateStatePath(path);
66
+ if (!options.directory && process.platform !== 'win32' && ((value.mode & 0o077) || (process.getuid && value.uid !== process.getuid())))
67
+ throw new Error('private_file_permissions');
68
+ }
69
+ return true;
70
+ }
71
+ /** Checked size from the same observation later verified; does not read the body. */
72
+ size(path, options = {}) {
73
+ if (!this.track(path, options))
74
+ return null;
75
+ return this.observations.get(resolve(path)).metadata.size;
76
+ }
77
+ read(path, options = {}) {
78
+ if (typeof path !== 'string' || !isAbsolute(path))
79
+ throw new Error('unsafe_configuration_file');
80
+ path = resolve(path);
81
+ if (!this.track(path, options))
82
+ return null;
83
+ const bytes = readRegularFile(path, { privateFile: options.privateFile, maxBytes: options.maxBytes ?? 4 * 1024 * 1024 });
84
+ const observed = this.observations.get(path);
85
+ if (signature(observed.metadata) !== signature(metadata(path)))
86
+ throw new Error('concurrent_configuration_change');
87
+ if (observed.bytes && !observed.bytes.equals(bytes))
88
+ throw new Error('concurrent_configuration_change');
89
+ observed.bytes = bytes;
90
+ observed.options = { ...observed.options, ...options };
91
+ return bytes;
92
+ }
93
+ verify() {
94
+ for (const [path, observation] of this.observations) {
95
+ try {
96
+ if (signature(observation.metadata, observation.options.identityOnly) !== signature(metadata(path), observation.options.identityOnly))
97
+ throw new Error('concurrent_configuration_change');
98
+ if (observation.bytes) {
99
+ const bytes = readRegularFile(path, { privateFile: observation.options.privateFile, maxBytes: observation.options.maxBytes ?? 4 * 1024 * 1024 });
100
+ if (!observation.bytes.equals(bytes) || signature(observation.metadata) !== signature(metadata(path)))
101
+ throw new Error('concurrent_configuration_change');
102
+ }
103
+ }
104
+ catch (error) {
105
+ // A previously observed path becoming redirected/unsafe is an observation change.
106
+ if (error instanceof Error && ['unsafe_configuration_file', 'unsafe_path', 'unsafe_file'].includes(error.message))
107
+ throw new Error('concurrent_configuration_change');
108
+ throw error;
109
+ }
110
+ }
111
+ }
112
+ }
@@ -24,6 +24,7 @@ const observationSchema = z.object({ client: hookSchema.client.optional(), event
24
24
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
25
25
  export function createServer({ env: inputEnv = process.env } = {}) {
26
26
  const codexBound = inputEnv.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE;
27
+ const policySourceKind = codexBound ? 'codex_home' : inputEnv.APTLY_HOOK_POLICY_PATH === undefined ? 'unconfigured' : 'fixed';
27
28
  const env = { ...inputEnv, APTLY_HOOK_POLICY_PATH: resolvePolicySource(inputEnv.APTLY_HOOK_POLICY_PATH, inputEnv) };
28
29
  const { router, budget, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
29
30
  const observations = new RoutingObservations();
@@ -71,6 +72,7 @@ export function createServer({ env: inputEnv = process.env } = {}) {
71
72
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
72
73
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
73
74
  credential_status: credentialStatus,
75
+ runtime_diagnostics: { version: VERSION, policy_source_kind: policySourceKind, credential_status_observed: 'startup_snapshot', context_retries: retries.diagnostics() },
74
76
  execution_statistics: { collection: 'explicit_operator_opt_in', view: 'aptly stats', semantics: 'host_reported_model_evidence_not_user_acceptance', effective_effort: 'not_measured', usage_rollups: 'not_collected' },
75
77
  automatic_hook: { status: automatic.reason, mode: automatic.policy?.mode ?? 'disabled', transmission: automatic.policy ? effectiveTransmission(automatic.policy) : null, transmission_provenance: automatic.policy ? (automatic.policy.schema_version === 1 ? 'legacy_v1_default' : 'operator_policy_v2') : 'unavailable', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', context_retry_tool: 'retry_spawn_recommendation', context_retry_limit: 1, fresh_delegation_tool: 'prepare_fresh_delegation', fresh_delegation_intent: 'caller_declared_not_verified', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported',
76
78
  guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny_when_transmission_enabled', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
@@ -73,8 +73,9 @@ export declare function prepareTransmissionReview(options?: SetupOptions & {
73
73
  candidates: TransmissionReviewCandidate[];
74
74
  apply(choice: 'keep' | TransmissionScope): SetupResult;
75
75
  };
76
- /** Read-only redacted policy state. Does not create host directories or contact a provider. */
76
+ /** Redacted policy query; aggregate status is query completion, not host readiness. */
77
77
  export declare function showTransmission(options?: SetupOptions): {
78
+ status: string;
78
79
  clients: ({
79
80
  client: Client;
80
81
  status: string;
@@ -142,7 +143,12 @@ export declare function setStatisticsCollection(enabled: boolean, options?: Setu
142
143
  }): SetupResult;
143
144
  /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
144
145
  export declare function showStatistics(options?: SetupOptions, today?: boolean): {
146
+ status: string;
145
147
  clients: ({
148
+ client: Client;
149
+ status: string;
150
+ collection: string;
151
+ } | {
146
152
  status: string;
147
153
  scope: string;
148
154
  semantics: string;
@@ -178,10 +184,6 @@ export declare function showStatistics(options?: SetupOptions, today?: boolean):
178
184
  model_alias_scope: string;
179
185
  counts_are_lifetime: boolean;
180
186
  client: Client;
181
- } | {
182
- client: Client;
183
- status: string;
184
- collection: string;
185
187
  })[];
186
188
  };
187
189
  export {};
package/dist/src/setup.js CHANGED
@@ -8,11 +8,13 @@ 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 { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
11
+ import { resolveHostPaths as resolved } from './host-paths.js';
12
+ import { QuerySnapshot } from './query-snapshot.js';
13
+ import { loadAutomaticHookPolicy, queryAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
12
14
  import { assertPrivateStatePath } from './files.js';
13
15
  import { CODEX_HOME_POLICY_SOURCE, resolvePolicySource } from './policy-source.js';
14
16
  import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
15
- import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatistics } from './statistics.js';
17
+ import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatisticsQuery, initializeStatisticsStore } from './statistics.js';
16
18
  const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
17
19
  const stringify = (value) => JSON.stringify(value, null, 2) + '\n';
18
20
  const fail = (code) => { throw new Error(code); };
@@ -188,7 +190,8 @@ function validateEnvironmentValue(key, value) {
188
190
  }
189
191
  }
190
192
  }
191
- function budgetInheritance(entry, environment, client) {
193
+ const candidateEnvironmentAliases = { APTLY_CLAUDE_MODELS: 'CLAUDE_MODELS', APTLY_CODEX_MODELS: 'CODEX_MODELS' };
194
+ function environmentInheritance(entry, environment, client) {
192
195
  if (client === 'codex' && entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((key) => typeof key !== 'string')))
193
196
  fail('configuration_shape_conflict');
194
197
  const permitted = client === 'codex' ? (entry.env_vars ?? []) : [], keys = new Set(), values = {};
@@ -202,14 +205,27 @@ function budgetInheritance(entry, environment, client) {
202
205
  for (const key of Object.keys(environment))
203
206
  if ((key.startsWith('APTLY_MAX_') || key.startsWith('APTLY_ESTIMATED_')) && (client === 'claude' || permitted.includes(key)))
204
207
  values[key] = environment[key];
208
+ for (const key of Object.entries(candidateEnvironmentAliases).flat()) {
209
+ const descriptor = Object.getOwnPropertyDescriptor(environment, key);
210
+ // A declared Codex passthrough remains external even when this CLI cannot observe its value.
211
+ if (client === 'codex' ? !permitted.includes(key) : !descriptor || ('value' in descriptor && descriptor.value === undefined))
212
+ continue;
213
+ keys.add(key);
214
+ if (descriptor) {
215
+ if (!('value' in descriptor))
216
+ fail('environment_invalid_value');
217
+ if (descriptor.value !== undefined)
218
+ values[key] = descriptor.value;
219
+ }
220
+ }
205
221
  return { keys, values };
206
222
  }
207
223
  function editEnvironment(current, edit, client, inherited) {
208
224
  const updates = {};
209
225
  if ('defaults' in edit) {
210
226
  for (const [key, value] of Object.entries(defaultEnvironment)) {
211
- const alias = key === 'APTLY_CLAUDE_MODELS' ? 'CLAUDE_MODELS' : key === 'APTLY_CODEX_MODELS' ? 'CODEX_MODELS' : null;
212
- if (current[key] === undefined && (!alias || current[alias] === undefined) && !(budgetEnvironmentKeys.includes(key) && inherited.keys.has(key)))
227
+ const alias = candidateEnvironmentAliases[key];
228
+ if (current[key] === undefined && (!alias || current[alias] === undefined) && !inherited.keys.has(key) && (!alias || !inherited.keys.has(alias)))
213
229
  updates[key] = value;
214
230
  }
215
231
  }
@@ -333,17 +349,6 @@ function policyReferenceMatches(entry, client, policyPath, options) {
333
349
  return source === policyPath;
334
350
  return client === 'codex' && entry.env?.CODEX_HOME === undefined && Array.isArray(entry.env_vars) && entry.env_vars.every((x) => typeof x === 'string') && entry.env_vars.includes('CODEX_HOME') && selectedCliPolicyPath(options) === policyPath;
335
351
  }
336
- function resolved(options, client) {
337
- const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
338
- const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
339
- if (override && !isAbsolute(override))
340
- fail('relative_configuration_directory');
341
- if (client === 'codex' && override !== undefined)
342
- resolvePolicySource(CODEX_HOME_POLICY_SOURCE, env);
343
- const dir = override || join(home, client === 'codex' ? '.codex' : '.claude');
344
- const mcpPath = client === 'codex' ? join(dir, 'config.toml') : override ? join(dir, '.claude.json') : join(home, '.claude.json');
345
- return { dir, mcpPath, hooksPath: join(dir, client === 'codex' ? 'hooks.json' : 'settings.json'), privateDir: join(dir, 'aptly') };
346
- }
347
352
  function ownership(value, client) {
348
353
  if (value.schema_version !== 1 || value.kind !== 'aptly-setup-ownership' || value.client !== client || !object(value.hook) || typeof value.mcp_created !== 'boolean' || !object(value.env_added) || !object(value.policy) || typeof value.policy_created !== 'boolean')
349
354
  fail('invalid_ownership');
@@ -524,8 +529,8 @@ function prepare(options, client, removing, edit) {
524
529
  if ((edit && ('credential' in edit || 'migrate' in edit)) || servers.aptly.env?.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE)
525
530
  requireCredentialRuntime(servers.aptly, root);
526
531
  const currentEnv = map(servers.aptly, 'env');
527
- const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedBudget = budgetInheritance(servers.aptly, env, client);
528
- const updates = edit ? editEnvironment(currentEnv, edit, client, inheritedBudget) : {};
532
+ const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedEnvironment = environmentInheritance(servers.aptly, env, client);
533
+ const updates = edit ? editEnvironment(currentEnv, edit, client, inheritedEnvironment) : {};
529
534
  Object.assign(currentEnv, updates);
530
535
  if (created) {
531
536
  if (client === 'codex') {
@@ -618,11 +623,11 @@ function prepare(options, client, removing, edit) {
618
623
  if (requestedScope !== undefined)
619
624
  owner.policy = structuredClone(policyValue);
620
625
  if (edit && ('defaults' in edit || ('key' in edit && budgetEnvironmentKeys.includes(edit.key)))) {
621
- const budget = resolveBudgetSettings({ ...inheritedBudget.values, ...currentEnv });
626
+ const budget = resolveBudgetSettings({ ...inheritedEnvironment.values, ...currentEnv });
622
627
  result.budget = { limits: { ...budget.limits }, added: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && !originalEnvKeys.has(key)),
623
628
  updated: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && originalEnvKeys.has(key)),
624
629
  preserved: budgetEnvironmentKeys.filter(key => !Object.hasOwn(updates, key) && currentEnv[key] !== undefined),
625
- inherited: budgetEnvironmentKeys.filter(key => currentEnv[key] === undefined && inheritedBudget.keys.has(key)), restart_required: budgetEnvironmentKeys.some(key => Object.hasOwn(updates, key)) };
630
+ inherited: budgetEnvironmentKeys.filter(key => currentEnv[key] === undefined && inheritedEnvironment.keys.has(key)), restart_required: budgetEnvironmentKeys.some(key => Object.hasOwn(updates, key)) };
626
631
  }
627
632
  result.transmission = effectiveTransmission(policyValue);
628
633
  result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
@@ -1182,23 +1187,99 @@ export function prepareTransmissionReview(options = {}) {
1182
1187
  return merge(applied.clients, applied.status);
1183
1188
  } };
1184
1189
  }
1185
- /** Read-only redacted policy state. Does not create host directories or contact a provider. */
1190
+ /** Query context only: no credential lookup, native discovery or configuration repair. */
1191
+ function queryContext(options, client, snapshot, statistics, policyMissing) {
1192
+ const paths = resolved(options, client), mcp = snapshot.read(paths.mcpPath);
1193
+ const config = client === 'codex' ? toml(mcp?.toString('utf8') ?? '') : json(mcp?.toString('utf8') ?? null);
1194
+ const servers = config[client === 'codex' ? 'mcp_servers' : 'mcpServers'], entry = servers?.aptly;
1195
+ let failed = (servers !== undefined && !object(servers)) || (entry !== undefined && (!object(entry) || (entry.env !== undefined && !object(entry.env))));
1196
+ let statisticsExpected = false;
1197
+ let expected = failed || (object(entry?.env) && Object.hasOwn(entry.env, 'APTLY_HOOK_POLICY_PATH'));
1198
+ try {
1199
+ const receipt = snapshot.read(join(paths.privateDir, 'setup-ownership.json'), { privateFile: true });
1200
+ if (receipt) {
1201
+ expected = true;
1202
+ ownership(json(receipt.toString('utf8')), client);
1203
+ }
1204
+ }
1205
+ catch {
1206
+ failed = true;
1207
+ expected = true;
1208
+ }
1209
+ if (statistics || policyMissing)
1210
+ try {
1211
+ const statOwner = snapshot.read(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE), { privateFile: true });
1212
+ if (statOwner) {
1213
+ expected = true;
1214
+ statisticsOwner(json(statOwner.toString('utf8')), client);
1215
+ statisticsExpected = true;
1216
+ }
1217
+ }
1218
+ catch {
1219
+ failed = true;
1220
+ expected = true;
1221
+ }
1222
+ if (policyMissing && !expected)
1223
+ try {
1224
+ // A normal remove retains a disabled config and history; this is not broken setup.
1225
+ const bytes = snapshot.read(join(paths.privateDir, 'state', STATISTICS_CONFIG_FILE), { privateFile: true, maxBytes: 8192, singleLink: true });
1226
+ if (bytes) {
1227
+ const state = parseStatisticsConfig(JSON.parse(bytes.toString('utf8')));
1228
+ if (!state) {
1229
+ failed = true;
1230
+ expected = true;
1231
+ }
1232
+ else
1233
+ expected = state.enabled_clients.includes(client);
1234
+ }
1235
+ else
1236
+ for (const name of [STATISTICS_KEY_FILE, STATISTICS_DB_FILE])
1237
+ if (snapshot.track(join(paths.privateDir, 'state', name), { privateFile: true, singleLink: true, identityOnly: true }))
1238
+ expected = true;
1239
+ }
1240
+ catch {
1241
+ failed = true;
1242
+ expected = true;
1243
+ }
1244
+ return { entry, expected, failed, paths, statisticsExpected };
1245
+ }
1246
+ /** Redacted policy query; aggregate status is query completion, not host readiness. */
1186
1247
  export function showTransmission(options = {}) {
1187
- return { clients: (options.clients ?? ['codex', 'claude']).map(client => {
1248
+ const outcomes = (options.clients ?? ['codex', 'claude']).map(client => {
1249
+ const snapshot = new QuerySnapshot();
1250
+ try {
1251
+ const { privateDir } = resolved(options, client), loaded = queryAutomaticHookPolicy(join(privateDir, 'auto-policy.json'), snapshot);
1252
+ let expected = false, contextFailed = false;
1188
1253
  try {
1189
- const { privateDir } = resolved(options, client);
1190
- noSymlinks(privateDir);
1191
- const loaded = loadAutomaticHookPolicy(join(privateDir, 'auto-policy.json'));
1254
+ const context = queryContext(options, client, snapshot, false, !loaded.policy);
1255
+ expected = context.expected;
1256
+ // Local policy contents cannot certify a conflicting/missing MCP policy binding.
1257
+ // Preserve legacy client fields; aggregate health reports the failed query contract.
1258
+ contextFailed = context.failed || (expected && (!object(context.entry) || !policyReferenceMatches(context.entry, client, join(privateDir, 'auto-policy.json'), options)));
1259
+ }
1260
+ catch {
1261
+ contextFailed = true;
1262
+ }
1263
+ const legacy = () => {
1192
1264
  if (!loaded.policy)
1193
1265
  return { client, status: 'unavailable', code: loaded.reason };
1266
+ // Preserve validation of the acknowledgement but read it only once for this query.
1267
+ const markerPath = join(privateDir, TRANSMISSION_REVIEW_FILE);
1268
+ validateReviewPrivate(markerPath);
1269
+ const marker = snapshot.read(markerPath, { privateFile: true, singleLink: true });
1194
1270
  return { client, status: 'configured', application_mode: loaded.policy.mode, enabled: loaded.policy.enabled,
1195
- transmission_review: reviewMatches(transmissionReviewSnapshot(options, client).before, options, client, loaded.policy) ? 'complete' : 'required',
1271
+ transmission_review: reviewMatches(marker?.toString('utf8') ?? null, options, client, loaded.policy) ? 'complete' : 'required',
1196
1272
  transmission: effectiveTransmission(loaded.policy), transmission_source: loaded.policy.schema_version === 1 ? 'legacy' : effectiveTransmission(loaded.policy) === 'unselected' ? 'unselected' : 'explicit' };
1197
- }
1198
- catch (error) {
1199
- return { client, status: 'error', code: safeCode(error) };
1200
- }
1201
- }) };
1273
+ };
1274
+ const result = legacy();
1275
+ snapshot.verify();
1276
+ return { result, failed: contextFailed || loaded.availability === 'error' || (loaded.availability === 'absent' && expected) };
1277
+ }
1278
+ catch (error) {
1279
+ return { result: { client, status: 'error', code: safeCode(error) }, failed: true };
1280
+ }
1281
+ });
1282
+ return { status: outcomes.some(o => o.failed) ? 'partial' : 'complete', clients: outcomes.map(o => o.result) };
1202
1283
  }
1203
1284
  /** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
1204
1285
  export function showBudgetStatus(options = {}) {
@@ -1349,7 +1430,7 @@ export function setStatisticsCollection(enabled, options = {}) {
1349
1430
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
1350
1431
  if (process.platform === 'win32')
1351
1432
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
1352
- const states = new Set();
1433
+ const states = new Set(), initializationPaths = new Map();
1353
1434
  const plans = clients.map(client => {
1354
1435
  try {
1355
1436
  if (!enabled) {
@@ -1370,6 +1451,7 @@ export function setStatisticsCollection(enabled, options = {}) {
1370
1451
  if (states.has(paths.stateDirectory))
1371
1452
  fail('statistics_shared_state');
1372
1453
  states.add(paths.stateDirectory);
1454
+ initializationPaths.set(client, paths.stateDirectory);
1373
1455
  const observations = [], changes = [];
1374
1456
  const snap = (path, privateFile = true) => { const result = privateFile ? statisticsSnapshot(path) : (() => { const v = read(path); return { path, before: v.text, after: v.text, mode: v.mode }; })(); observations.push(result); return result; };
1375
1457
  const policy = snap(paths.policyPath);
@@ -1485,18 +1567,52 @@ export function setStatisticsCollection(enabled, options = {}) {
1485
1567
  });
1486
1568
  if (enabled && plans.some(p => p.result.status === 'error'))
1487
1569
  return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
1488
- return execute(options, false, undefined, plans);
1570
+ const applied = execute(options, false, undefined, plans);
1571
+ if (!enabled || applied.status !== 'complete')
1572
+ return applied;
1573
+ // Configuration was applied successfully; initialization failures are reported
1574
+ // as partial setup, never rolled back or hidden as a complete activation.
1575
+ const initialized = applied.clients.map(result => {
1576
+ try {
1577
+ initializeStatisticsStore({ stateDirectory: initializationPaths.get(result.client) });
1578
+ return result;
1579
+ }
1580
+ catch {
1581
+ return { ...result, status: 'error', codes: [...result.codes, 'statistics_store_initialization_failed'] };
1582
+ }
1583
+ });
1584
+ return { status: initialized.some(result => result.status === 'error') ? 'partial' : 'complete', clients: initialized };
1489
1585
  }
1490
1586
  /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
1491
1587
  export function showStatistics(options = {}, today = false) {
1492
1588
  const clients = options.clients ?? ['codex', 'claude'];
1493
1589
  if (process.platform === 'win32')
1494
- return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
1495
- return { clients: clients.map(client => { try {
1496
- const path = statisticsPolicy(options, client);
1497
- return { client, ...readStatistics({ stateDirectory: path.stateDirectory }, { client, today }) };
1590
+ return { status: 'partial', clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
1591
+ const outcomes = clients.map(client => {
1592
+ const snapshot = new QuerySnapshot();
1593
+ try {
1594
+ const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
1595
+ const loaded = queryAutomaticHookPolicy(policyPath, snapshot);
1596
+ const context = queryContext(options, client, snapshot, true, !loaded.policy);
1597
+ if (!object(context.entry)) {
1598
+ snapshot.verify();
1599
+ return { result: { client, status: 'statistics_requires_setup', collection: 'disabled' }, failed: context.failed || !!loaded.policy || loaded.availability === 'error' || context.expected };
1600
+ }
1601
+ if (!policyReferenceMatches(context.entry, client, policyPath, options)) {
1602
+ snapshot.verify();
1603
+ return { result: { client, status: 'statistics_policy_conflict', collection: 'disabled' }, failed: context.failed || loaded.availability !== 'absent' || context.expected };
1604
+ }
1605
+ if (!loaded.policy) {
1606
+ snapshot.verify();
1607
+ return { result: { client, status: 'statistics_requires_setup', collection: 'disabled' }, failed: context.failed || loaded.availability === 'error' || context.expected };
1608
+ }
1609
+ const outcome = readStatisticsQuery({ stateDirectory: loaded.policy.state_directory }, { client, today }, snapshot, context.statisticsExpected);
1610
+ snapshot.verify();
1611
+ return { result: { client, ...outcome.result }, failed: outcome.failed || context.failed };
1498
1612
  }
1499
1613
  catch (error) {
1500
- return { client, status: safeCode(error), collection: 'disabled' };
1501
- } }) };
1614
+ return { result: { client, status: safeCode(error), collection: 'disabled' }, failed: true };
1615
+ }
1616
+ });
1617
+ return { status: outcomes.some(o => o.failed) ? 'partial' : 'complete', clients: outcomes.map(o => o.result) };
1502
1618
  }
@@ -1,4 +1,5 @@
1
1
  import { type Client } from './types.ts';
2
+ import { QuerySnapshot } from './query-snapshot.ts';
2
3
  export declare const STATISTICS_CONFIG_FILE = "stats-config.json";
3
4
  export declare const STATISTICS_KEY_FILE = "stats-key";
4
5
  export declare const STATISTICS_DATABASE_FILE = "stats.sqlite";
@@ -43,16 +44,20 @@ export declare function serializeStatisticsConfig(value: StatisticsConfig): stri
43
44
  export declare function loadStatisticsConfig(options: StatisticsOptions): StatisticsConfig | null;
44
45
  export declare function statisticsHash(key: string, domain: Parameters<StatisticsHash>[0], client: Client, value: string): string;
45
46
  export declare function loadStatisticsHash(options: StatisticsOptions): StatisticsHash | null;
47
+ /** Explicit enable-time initialization only; read queries and observers retain their own paths. */
48
+ export declare function initializeStatisticsStore(options: StatisticsOptions): void;
46
49
  export declare function recordStatisticsRecommendation(options: StatisticsOptions, input: StatisticsRecommendation): StatisticsResult;
47
50
  export declare function observeStatistics(options: StatisticsOptions, input: {
48
51
  client: Client;
49
52
  event: unknown;
50
53
  }, bridge?: StatisticsBridge): StatisticsResult;
51
54
  export type ModelState = 'model_match' | 'model_mismatch' | 'model_changed' | 'unknown' | 'pending' | 'expired_pending' | 'application_unconfirmed';
52
- export declare function readStatistics(options: StatisticsOptions, filter?: {
55
+ type StatisticsFilter = {
53
56
  client?: Client | 'all';
54
57
  today?: boolean;
55
- }): {
58
+ };
59
+ /** Existing best-effort projection, including its historical status semantics. */
60
+ export declare function readStatistics(options: StatisticsOptions, filter?: StatisticsFilter): {
56
61
  status: string;
57
62
  scope: string;
58
63
  semantics: string;
@@ -88,3 +93,44 @@ export declare function readStatistics(options: StatisticsOptions, filter?: {
88
93
  model_alias_scope: string;
89
94
  counts_are_lifetime: boolean;
90
95
  };
96
+ /** Read the same projection while reporting query failures separately. */
97
+ export declare function readStatisticsQuery(options: StatisticsOptions, filter?: StatisticsFilter, snapshot?: QuerySnapshot, configurationExpected?: boolean): {
98
+ result: {
99
+ status: string;
100
+ scope: string;
101
+ semantics: string;
102
+ observation_completeness: string;
103
+ today_basis: string;
104
+ filter: {
105
+ client: "all" | Client;
106
+ today: boolean;
107
+ };
108
+ collection: {
109
+ codex: boolean;
110
+ claude: boolean;
111
+ };
112
+ capacity: {
113
+ delegations: number;
114
+ children: number;
115
+ reached: boolean;
116
+ };
117
+ delegations: number;
118
+ auto: Record<ModelState, number>;
119
+ advisory: Record<ModelState, number>;
120
+ blocked: number;
121
+ explicit_preserved: number;
122
+ unbound: number;
123
+ effort_actual_unknown: number;
124
+ application_confirmed: number;
125
+ unknown_alias_count: number;
126
+ model_observed: number;
127
+ model_comparable: number;
128
+ model_match_denominator: number;
129
+ observation_denominator: number;
130
+ usage_scope: string;
131
+ model_alias_scope: string;
132
+ counts_are_lifetime: boolean;
133
+ };
134
+ failed: boolean;
135
+ };
136
+ export {};