aptly 0.1.11 → 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 +6 -5
  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 +162 -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
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
  }
@@ -322,20 +338,16 @@ function updateTomlForwarding(text, names) {
322
338
  fail('unsupported_toml_layout');
323
339
  return rendered;
324
340
  }
341
+ /** CLI commands validate their explicitly selected config home, not a running host. */
342
+ function selectedCliPolicyPath(options) {
343
+ const env = options.env ?? process.env;
344
+ return resolvePolicySource(CODEX_HOME_POLICY_SOURCE, env.CODEX_HOME === undefined ? { ...env, CODEX_HOME: resolved(options, 'codex').dir } : env);
345
+ }
325
346
  function policyReferenceMatches(entry, client, policyPath, options) {
326
347
  const source = entry.env?.APTLY_HOOK_POLICY_PATH;
327
348
  if (source !== CODEX_HOME_POLICY_SOURCE)
328
349
  return source === policyPath;
329
- 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') && resolvePolicySource(source, options.env ?? process.env, options.home) === policyPath;
330
- }
331
- function resolved(options, client) {
332
- const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
333
- const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
334
- if (override && !isAbsolute(override))
335
- fail('relative_configuration_directory');
336
- const dir = override || join(home, client === 'codex' ? '.codex' : '.claude');
337
- const mcpPath = client === 'codex' ? join(dir, 'config.toml') : override ? join(dir, '.claude.json') : join(home, '.claude.json');
338
- return { dir, mcpPath, hooksPath: join(dir, client === 'codex' ? 'hooks.json' : 'settings.json'), privateDir: join(dir, 'aptly') };
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;
339
351
  }
340
352
  function ownership(value, client) {
341
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')
@@ -517,8 +529,8 @@ function prepare(options, client, removing, edit) {
517
529
  if ((edit && ('credential' in edit || 'migrate' in edit)) || servers.aptly.env?.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE)
518
530
  requireCredentialRuntime(servers.aptly, root);
519
531
  const currentEnv = map(servers.aptly, 'env');
520
- const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedBudget = budgetInheritance(servers.aptly, env, client);
521
- 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) : {};
522
534
  Object.assign(currentEnv, updates);
523
535
  if (created) {
524
536
  if (client === 'codex') {
@@ -611,11 +623,11 @@ function prepare(options, client, removing, edit) {
611
623
  if (requestedScope !== undefined)
612
624
  owner.policy = structuredClone(policyValue);
613
625
  if (edit && ('defaults' in edit || ('key' in edit && budgetEnvironmentKeys.includes(edit.key)))) {
614
- const budget = resolveBudgetSettings({ ...inheritedBudget.values, ...currentEnv });
626
+ const budget = resolveBudgetSettings({ ...inheritedEnvironment.values, ...currentEnv });
615
627
  result.budget = { limits: { ...budget.limits }, added: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && !originalEnvKeys.has(key)),
616
628
  updated: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && originalEnvKeys.has(key)),
617
629
  preserved: budgetEnvironmentKeys.filter(key => !Object.hasOwn(updates, key) && currentEnv[key] !== undefined),
618
- 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)) };
619
631
  }
620
632
  result.transmission = effectiveTransmission(policyValue);
621
633
  result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
@@ -915,7 +927,7 @@ export function setPolicySource(options, dryRun = false) {
915
927
  try {
916
928
  const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
917
929
  // Validate the selector even when CODEX_HOME is present but empty.
918
- if (resolvePolicySource(CODEX_HOME_POLICY_SOURCE, options.env ?? process.env, options.home) !== policyPath)
930
+ if (selectedCliPolicyPath(options) !== policyPath)
919
931
  fail('policy_source_home_invalid');
920
932
  const snap = (path) => { const file = read(path); return { path, before: file.text, after: file.text, mode: file.mode }; };
921
933
  const mcp = snap(paths.mcpPath), hooks = snap(paths.hooksPath), policy = snap(policyPath), manifest = snap(join(paths.privateDir, 'setup-ownership.json'));
@@ -1175,23 +1187,99 @@ export function prepareTransmissionReview(options = {}) {
1175
1187
  return merge(applied.clients, applied.status);
1176
1188
  } };
1177
1189
  }
1178
- /** 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. */
1179
1247
  export function showTransmission(options = {}) {
1180
- 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;
1181
1253
  try {
1182
- const { privateDir } = resolved(options, client);
1183
- noSymlinks(privateDir);
1184
- 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 = () => {
1185
1264
  if (!loaded.policy)
1186
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 });
1187
1270
  return { client, status: 'configured', application_mode: loaded.policy.mode, enabled: loaded.policy.enabled,
1188
- 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',
1189
1272
  transmission: effectiveTransmission(loaded.policy), transmission_source: loaded.policy.schema_version === 1 ? 'legacy' : effectiveTransmission(loaded.policy) === 'unselected' ? 'unselected' : 'explicit' };
1190
- }
1191
- catch (error) {
1192
- return { client, status: 'error', code: safeCode(error) };
1193
- }
1194
- }) };
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) };
1195
1283
  }
1196
1284
  /** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
1197
1285
  export function showBudgetStatus(options = {}) {
@@ -1342,7 +1430,7 @@ export function setStatisticsCollection(enabled, options = {}) {
1342
1430
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
1343
1431
  if (process.platform === 'win32')
1344
1432
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
1345
- const states = new Set();
1433
+ const states = new Set(), initializationPaths = new Map();
1346
1434
  const plans = clients.map(client => {
1347
1435
  try {
1348
1436
  if (!enabled) {
@@ -1363,6 +1451,7 @@ export function setStatisticsCollection(enabled, options = {}) {
1363
1451
  if (states.has(paths.stateDirectory))
1364
1452
  fail('statistics_shared_state');
1365
1453
  states.add(paths.stateDirectory);
1454
+ initializationPaths.set(client, paths.stateDirectory);
1366
1455
  const observations = [], changes = [];
1367
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; };
1368
1457
  const policy = snap(paths.policyPath);
@@ -1478,18 +1567,52 @@ export function setStatisticsCollection(enabled, options = {}) {
1478
1567
  });
1479
1568
  if (enabled && plans.some(p => p.result.status === 'error'))
1480
1569
  return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
1481
- 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 };
1482
1585
  }
1483
1586
  /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
1484
1587
  export function showStatistics(options = {}, today = false) {
1485
1588
  const clients = options.clients ?? ['codex', 'claude'];
1486
1589
  if (process.platform === 'win32')
1487
- return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
1488
- return { clients: clients.map(client => { try {
1489
- const path = statisticsPolicy(options, client);
1490
- 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 };
1491
1612
  }
1492
1613
  catch (error) {
1493
- return { client, status: safeCode(error), collection: 'disabled' };
1494
- } }) };
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) };
1495
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 {};
@@ -4,6 +4,7 @@ import { createRequire } from 'node:module';
4
4
  import { isAbsolute, join } from 'node:path';
5
5
  import { assertPrivateStatePath, readRegularFile } from './files.js';
6
6
  import { isRecord } from './types.js';
7
+ import { QuerySnapshot } from './query-snapshot.js';
7
8
  export const STATISTICS_CONFIG_FILE = 'stats-config.json';
8
9
  export const STATISTICS_KEY_FILE = 'stats-key';
9
10
  export const STATISTICS_DATABASE_FILE = 'stats.sqlite';
@@ -147,6 +148,19 @@ function connection(options, write) {
147
148
  throw error;
148
149
  }
149
150
  }
151
+ /** Explicit enable-time initialization only; read queries and observers retain their own paths. */
152
+ export function initializeStatisticsStore(options) {
153
+ const path = join(options.stateDirectory, STATISTICS_DATABASE_FILE);
154
+ assertPrivateStatePath(path);
155
+ checkSidecars(path);
156
+ if (!existsSync(path))
157
+ initialize(path);
158
+ // Validate an existing store without replacing it or opening a write transaction.
159
+ const db = connection(options, false);
160
+ if (!db)
161
+ throw new Error('statistics_database_invalid');
162
+ db.close();
163
+ }
150
164
  function rows(db, table) {
151
165
  return db.prepare(`SELECT * FROM ${table} ORDER BY created,id`).all().map(row => ({ ...row, data: JSON.parse(String(row.data)) }));
152
166
  }
@@ -356,21 +370,70 @@ function modelState(d, c, ambiguous, created, now) {
356
370
  return 'unknown';
357
371
  return expected === actual ? 'model_match' : 'model_mismatch';
358
372
  }
359
- export function readStatistics(options, filter = {}) {
373
+ function readStatisticsInternal(options, filter, snapshot, configurationExpected = false) {
360
374
  const now = (options.now ?? Date.now)();
361
375
  const output = { status: 'ok', scope: 'retained_records', semantics: 'retained_routing_records_not_user_acceptance_or_execution_total', observation_completeness: 'best_effort_not_full_execution_history', today_basis: 'UTC_binding_creation', filter: { client: filter.client ?? 'all', today: filter.today === true },
362
376
  collection: { codex: false, claude: false }, capacity: { delegations: limit(options.maxDelegations), children: limit(options.maxChildren), reached: false },
363
377
  delegations: 0, auto: emptyCounts(), advisory: emptyCounts(), blocked: 0, explicit_preserved: 0, unbound: 0,
364
378
  effort_actual_unknown: 0, application_confirmed: 0, unknown_alias_count: 0, model_observed: 0, model_comparable: 0, model_match_denominator: 0, observation_denominator: 0,
365
379
  usage_scope: 'not_collected', model_alias_scope: 'exact_canonical_model_ids_only', counts_are_lifetime: false };
366
- const config = loadStatisticsConfig(options);
380
+ let failed = false;
381
+ let config = null;
382
+ let configAbsent = false;
383
+ if (snapshot) {
384
+ try {
385
+ const bytes = snapshot.read(join(options.stateDirectory, STATISTICS_CONFIG_FILE), { privateFile: true, maxBytes: 8192, singleLink: true });
386
+ if (bytes === null)
387
+ configAbsent = true;
388
+ else {
389
+ config = parseStatisticsConfig(JSON.parse(bytes.toString('utf8')));
390
+ if (!config)
391
+ failed = true;
392
+ }
393
+ }
394
+ catch {
395
+ failed = true;
396
+ }
397
+ }
398
+ else
399
+ config = loadStatisticsConfig(options);
367
400
  for (const client of config?.enabled_clients ?? [])
368
401
  output.collection[client] = true;
402
+ if (snapshot && configAbsent && configurationExpected)
403
+ failed = true;
404
+ if (snapshot && configAbsent)
405
+ try {
406
+ if (snapshot.track(join(options.stateDirectory, STATISTICS_KEY_FILE), { privateFile: true, singleLink: true, identityOnly: true }))
407
+ failed = true;
408
+ }
409
+ catch {
410
+ failed = true;
411
+ }
412
+ const collectionExpected = !!config?.enabled_clients.some(client => !filter.client || filter.client === 'all' || filter.client === client);
369
413
  let db = null;
370
414
  try {
415
+ if (snapshot) {
416
+ let present;
417
+ try {
418
+ present = snapshot.track(join(options.stateDirectory, STATISTICS_DATABASE_FILE), { privateFile: true, singleLink: true, identityOnly: true });
419
+ }
420
+ catch {
421
+ failed = true;
422
+ }
423
+ if (present === false) {
424
+ if (collectionExpected)
425
+ failed = true;
426
+ return { result: output, failed };
427
+ }
428
+ if (present && configAbsent)
429
+ failed = true;
430
+ }
371
431
  db = connection(options, false);
372
- if (!db)
373
- return output;
432
+ if (!db) {
433
+ if (snapshot && collectionExpected)
434
+ failed = true;
435
+ return { result: output, failed };
436
+ }
374
437
  // All projection inputs must come from one SQLite snapshot. Separate implicit
375
438
  // SELECT transactions can otherwise combine old bindings with new child facts.
376
439
  db.exec('BEGIN');
@@ -453,11 +516,11 @@ export function readStatistics(options, filter = {}) {
453
516
  }
454
517
  }
455
518
  }
456
- return output;
519
+ return { result: output, failed };
457
520
  }
458
521
  catch {
459
522
  output.status = 'unavailable';
460
- return output;
523
+ return { result: output, failed: true };
461
524
  }
462
525
  finally {
463
526
  try {
@@ -470,3 +533,21 @@ export function readStatistics(options, filter = {}) {
470
533
  catch { }
471
534
  }
472
535
  }
536
+ /** Existing best-effort projection, including its historical status semantics. */
537
+ export function readStatistics(options, filter = {}) {
538
+ return readStatisticsInternal(options, filter).result;
539
+ }
540
+ /** Read the same projection while reporting query failures separately. */
541
+ export function readStatisticsQuery(options, filter = {}, snapshot, configurationExpected = false) {
542
+ const owned = snapshot === undefined;
543
+ const view = snapshot ?? new QuerySnapshot();
544
+ const outcome = readStatisticsInternal(options, filter, view, configurationExpected);
545
+ if (owned)
546
+ try {
547
+ view.verify();
548
+ }
549
+ catch {
550
+ outcome.failed = true;
551
+ }
552
+ return outcome;
553
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.11";
1
+ export declare const VERSION = "0.1.13";
@@ -1 +1 @@
1
- export const VERSION = '0.1.11';
1
+ export const VERSION = '0.1.13';
@@ -185,6 +185,12 @@ The current automatic Hook has no field for passing a URL separately as plaintex
185
185
 
186
186
  ## Diagnostics and development
187
187
 
188
+ `aptly doctor [--client codex|claude|all]` reads local registration, policy, registered package versions and ledger metadata using a separate JSON schema (`kind: aptly-doctor`, `schema_version: 1`). `complete`/exit 0 means the query completed; `partial`/exit 1 means an observation failed. Neither certifies host readiness. Connected MCP version, Hook trust/execution, restart need and ticket usage remain `unknown` locally. It never executes registered launchers, queries credential stores, calls APIs/networks, creates/modifies state or shows update notifications.
189
+
190
+ The ledger size is checked first through a safe path. At most 4 MiB is validated using the existing storage schema before reporting `total`, `complete` and `unknown` counts. Larger files return `scan_skipped_size_limit` without reading the body. A missing first-use ledger means unobserved history, not zero records. Changes during observation discard counts with `changed_during_observation`. Diagnostic timing includes validation/rechecks; write timing is `not_measured`. Output excludes keys, paths, environment values, request IDs and task bodies. Only numeric release versions are shown; arbitrary version suffixes produce `unsupported_version_metadata`.
191
+
192
+ The connected MCP's `get_routing_capabilities.runtime_diagnostics` adds the responding process version, policy source kind and process-local recovery slot `capacity`, `used`, `remaining`, `expired_retained` and `in_flight`. Expired tickets still occupy slots. Observation neither renews/prunes tickets nor checks retry eligibility (`retry_eligibility: not_checked`). Existing `credential_status` is a startup snapshot. Matching versions prove neither settings reload nor that all writers stopped. Strict MCP consumers must allow this additive object. The existing `aptly report` schema and file exports remain unchanged.
193
+
188
194
  ```sh
189
195
  aptly report --format both --output-dir reports
190
196
  ```
@@ -32,7 +32,7 @@ Claude Code stores Hooks in `~/.claude/settings.json` by default, or `$CLAUDE_CO
32
32
 
33
33
  ## Configure with the CLI
34
34
 
35
- In unreleased source, the first normal interactive `aptly set default` groups pending transmission reviews by client home. The recommendation is `excerpt`; Enter preserves an existing scope or selects `none` if unselected. See [transmission review](transmission.md#guide-transmission-scope). This review is not in published 0.1.10.
35
+ From 0.1.11, the first normal interactive `aptly set default` groups pending transmission reviews by client home. The recommendation is `excerpt`; Enter preserves an existing scope or selects `none` if unselected. See [transmission review](transmission.md#guide-transmission-scope). This review flow is not supported in 0.1.10, so update first.
36
36
 
37
37
  The `set` commands require 0.1.1 or later. Commands do not automatically switch existing launch paths. API-key setup accepts only the current package’s standard Node/server registration with a verified OS-source-compatible runtime. Custom wrappers, older versions, and other installation prefixes are rejected with `credential_launcher_unverified`; explicitly switch the registration or upgrade it before trying again.
38
38
 
@@ -97,6 +97,8 @@ MCP `env` values are strings, so candidate arrays must also be passed as JSON st
97
97
 
98
98
  When unset, the defaults above apply; `[]` disables recommendations for that client. Empty strings, duplicates, unsupported models, and malformed JSON are errors. `CLAUDE_MODELS` and `CODEX_MODELS` are supported aliases, but setting both the primary name and its alias for the same provider is an error. Candidate configuration does not override existing choices or certify model access for an account.
99
99
 
100
+ `aptly set default` preserves candidates and aliases already in MCP `env`, Codex `env_vars` declarations, and inherited candidates visible to the current CLI for Claude. It adds default candidates only for a model family with neither name configured. A Codex passthrough is preserved even when its value is unavailable in the current terminal; inherited values are not copied into configuration files. The CLI gives a static `env` value precedence over an inherited value with the same name when validating effective settings. Catalog validation remains in place, so conflicting aliases or malformed values reject the configuration change. Check the final candidates in the restarted MCP separately.
101
+
100
102
  ## Related topics
101
103
 
102
104
  [Installation and updates](installation.md) · [Automatic recommendations](routing.md) · [Decisions API transmission](transmission.md) · [Advanced MCP integration and development](advanced.md) · [Troubleshooting](troubleshooting.md)
@@ -48,11 +48,11 @@ npm install -g aptly@latest --ignore-scripts
48
48
  aptly setup --client all
49
49
  ```
50
50
 
51
- In unreleased source, npm lifecycle installation does not ask for transmission review. After upgrading to a release containing the feature, run interactive `aptly setup`, `aptly set default`, or `aptly set transmission --review` with the same account environment. The 0.1.10 updater cannot ask the new question during that update; see [transmission review](transmission.md#guide-transmission-scope).
51
+ Transmission review is available from 0.1.11 and does not prompt during npm lifecycle installation. When upgrading from 0.1.10, update the package first, then run interactive `aptly setup`, `aptly set default`, or `aptly set transmission --review` with the same account environment. The update process does not perform the new review or imply consent; see [transmission review](transmission.md#guide-transmission-scope).
52
52
 
53
53
  Explicit `setup` works regardless of lifecycle execution. It preserves existing launchers; use the [launcher recovery steps](troubleshooting.md#guide-launcher-recovery) for stale paths. Key setup, MCP restart, and Codex `/hooks` trust review remain separate steps.
54
54
 
55
- The unreleased installer writes only a stderr instruction to run `aptly set transmission --review` when registrations need review; it does not ask a question or record a choice.
55
+ The 0.1.11 or later installer writes only a stderr instruction to run `aptly set transmission --review` when setup completes successfully and registered clients have reviews pending; it does not ask a question or record a choice.
56
56
 
57
57
  <a id="guide-package-updates"></a>
58
58
 
@@ -22,8 +22,12 @@ aptly stats enable --client codex --codex-native-metadata
22
22
  aptly stats disable --client codex
23
23
  ```
24
24
 
25
+ The top-level `status` in `aptly stats` reads, including `--today`, is `complete` (exit 0) when the query completes and `partial` (exit 1) for unsupported statistics requests or corrupt, read, or store errors. Disabled collection and genuinely unconfigured clients are completed queries. Successful client results remain available when another client fails. Existing client JSON fields and values are retained; strict full-object consumers must accept the additive `status`. `complete` does not certify host routing, model, or trust readiness. Unexpected statistics failures report `statistics_failed`; raw paths, input, keys, and stacks are not printed. Reads do not repair setup, obtain consent, or call a provider.
26
+
25
27
  The command forms are `aptly stats [--today] [--client codex|claude|all]`, `aptly stats enable [--client] [--codex-native-metadata]` and `aptly stats disable [--client]`. Collection is off by default and postinstall does not enable it. Enable installs Aptly-owned command observers recorded separately in `stats-ownership.json`; it leaves the legacy receipt, MCP, launchers, keys, budget and transmission settings intact. Restart MCP and the host after enabling; for Codex, review native Hook trust in `/hooks`.
26
28
 
29
+ `stats enable` initializes an empty statistics database before the first event and validates existing stores without replacing them. Initialization failure returns `partial` with `statistics_store_initialization_failed`; applied registration may remain. If an older version enabled collection but no event has created its database, rerun `stats enable`. Queries never create or repair the database.
30
+
27
31
  Disable turns collection off and removes only unchanged owned observers. Modified or custom observers are preserved with a warning; data and the key remain. `remove` validates and removes stats-owned definitions but keeps the data. Independently managed collectors and custom Hooks are not adopted automatically.
28
32
 
29
33
  Private state uses `stats.sqlite`, `stats-config.json` and `stats-key` (an HMAC secret), separately from the budget ledger. Do not share the key. Records contain no task text, transcripts, raw IDs, paths, errors or credentials. Reading stats makes no API, key or credential-store calls, initializes nothing and runs no notifier.