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/bin/aptly.js CHANGED
@@ -5,6 +5,7 @@ import { serve } from '../src/server.js';
5
5
  import { runtime } from '../src/runtime.js';
6
6
  import { explainSettings } from '../src/inspect.js';
7
7
  import { VERSION } from '../src/version.js';
8
+ import { collectDoctor } from '../src/doctor.js';
8
9
  import { collectDiagnostics } from '../src/diagnostics.js';
9
10
  import { exportDiagnosticReport } from '../src/report.js';
10
11
  import { fetchModelInfo, saveModelInfo } from '../src/model-info.js';
@@ -43,6 +44,18 @@ try {
43
44
  else if (process.stderr.isTTY && !process.env.CI)
44
45
  process.stderr.write('Run aptly setup after updating; its first interactive run reviews transmission scope. Use aptly set transmission --review for an explicit review, then restart MCP.\n');
45
46
  }
47
+ else if (command === 'doctor') {
48
+ let clients = ['codex', 'claude'];
49
+ if (args.length) {
50
+ if (args.length !== 2 || args[0] !== '--client' || !['codex', 'claude', 'all'].includes(args[1]))
51
+ throw new Error('doctor_invalid_options');
52
+ clients = args[1] === 'all' ? ['codex', 'claude'] : [args[1]];
53
+ }
54
+ const result = collectDoctor({ clients });
55
+ output(result);
56
+ if (result.status === 'partial')
57
+ process.exitCode = 1;
58
+ }
46
59
  else if (command === 'stats') {
47
60
  let action, start = 0;
48
61
  if (args[0] === 'enable' || args[0] === 'disable') {
@@ -303,13 +316,14 @@ catch (error) {
303
316
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
304
317
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
305
318
  const inputCode = ['set_input_cancelled', 'set_interactive_input_required'].includes(message ?? '') ? message : undefined;
306
- const code = command === 'stats' ? 'statistics_invalid_options' : command === 'update' ? (message === 'update_invalid_options' ? message : 'update_failed') : command === 'set' ? (setCodes.includes(message ?? '') ? message : 'set_failed') : command === 'report' ? (caughtCode && codes.includes(caughtCode) ? caughtCode : 'report_failed') : inputCode ?? budgetCode ?? configCode ?? 'operation_failed';
319
+ const recognizedInput = (message === 'setup_invalid_options' && ['setup', 'remove'].includes(command)) || (message === 'input_too_large' && ['recommend', 'inspect'].includes(command)) ? message : undefined;
320
+ const code = command === 'doctor' ? (message === 'doctor_invalid_options' ? message : 'doctor_failed') : command === 'stats' ? (message === 'statistics_invalid_options' ? message : 'statistics_failed') : command === 'update' ? (message === 'update_invalid_options' ? message : 'update_failed') : command === 'set' ? (setCodes.includes(message ?? '') ? message : 'set_failed') : command === 'report' ? (caughtCode && codes.includes(caughtCode) ? caughtCode : 'report_failed') : recognizedInput ?? inputCode ?? budgetCode ?? configCode ?? 'operation_failed';
307
321
  const budgetDetails = budgetErrorDetails(error);
308
322
  process.stderr.write('aptly: ' + code + (budgetDetails.invalid_budget_keys?.length ? ' [' + budgetDetails.invalid_budget_keys.join(', ') + ']' : '') + (budgetDetails.budget_error ? ' (' + budgetDetails.budget_error + ')' : '') + '\n');
309
323
  process.exitCode = 1;
310
324
  }
311
325
  finally {
312
- if (!process.exitCode && !helpHandled && command !== 'stats') {
326
+ if (!process.exitCode && !helpHandled && !['stats', 'doctor'].includes(command)) {
313
327
  try {
314
328
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
315
329
  if (hint)
@@ -1,4 +1,5 @@
1
1
  import { Router } from './core.ts';
2
+ import { QuerySnapshot } from './query-snapshot.ts';
2
3
  import type { HookOutput } from './hook.ts';
3
4
  import type { Client } from './types.ts';
4
5
  interface AutoPolicyBase {
@@ -109,6 +110,12 @@ export declare function loadAutomaticHookPolicy(path: unknown): {
109
110
  reason: string;
110
111
  fingerprint?: string;
111
112
  };
113
+ /** Query-only availability; the Hook's historical missing/invalid reasons remain unchanged. */
114
+ export declare function queryAutomaticHookPolicy(path: string, snapshot: QuerySnapshot): {
115
+ policy: AutoPolicy | null;
116
+ reason: string;
117
+ availability: 'valid' | 'absent' | 'error';
118
+ };
112
119
  export declare function automaticCallIdentity(client: unknown, event: unknown): {
113
120
  key: string;
114
121
  id: string;
@@ -5,6 +5,7 @@ import { isAbsolute, join } from 'node:path';
5
5
  import { Router } from './core.js';
6
6
  import { hasSufficientTaskText } from './context-sufficiency.js';
7
7
  import { assertPrivateStatePath, readRegularFile } from './files.js';
8
+ import { QuerySnapshot } from './query-snapshot.js';
8
9
  import { hookInput, hookOutput, validatedHookProfile, profilePreservesChoices, effortKeys } from './hook.js';
9
10
  import { digestToolInput } from './provenance.js';
10
11
  export function effectiveTransmission(policy) {
@@ -17,29 +18,46 @@ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).diges
17
18
  const safeText = (value, max) => typeof value === 'string' && !!value.trim() && Buffer.byteLength(value) <= max;
18
19
  const sensitive = (value) => /\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(value);
19
20
  const policyKeys = ['schema_version', 'kind', 'mode', 'issuer', 'enabled', 'state_directory'];
21
+ function parseAutomaticHookPolicy(value) {
22
+ if (!plain(value))
23
+ throw new Error('invalid_policy');
24
+ const keys = value.schema_version === 2 ? [...policyKeys, 'transmission'] : policyKeys;
25
+ if (Object.keys(value).length !== keys.length || Object.keys(value).some(key => !keys.includes(key)) ||
26
+ ![1, 2].includes(value.schema_version) || (value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(value.transmission)) || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
27
+ value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' ||
28
+ typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
29
+ throw new Error('invalid_policy');
30
+ // Validate an existing private state directory, without creating a path from untrusted event data.
31
+ assertPrivateStatePath(join(value.state_directory, '.aptly-state-check'));
32
+ const policy = Object.fromEntries(keys.map(key => [key, value[key]]));
33
+ return policy;
34
+ }
35
+ function loadedPolicy(policy) { return { policy, fingerprint: hash(policy), reason: policy.enabled ? 'automatic_policy_enabled' : 'automatic_policy_disabled' }; }
20
36
  export function loadAutomaticHookPolicy(path) {
21
37
  if (path === undefined)
22
38
  return { policy: null, reason: 'automatic_policy_missing' };
23
39
  try {
24
40
  assertPrivateStatePath(path);
25
- const value = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'));
26
- if (!plain(value))
27
- throw new Error('invalid_policy');
28
- const keys = value.schema_version === 2 ? [...policyKeys, 'transmission'] : policyKeys;
29
- if (Object.keys(value).length !== keys.length || Object.keys(value).some(key => !keys.includes(key)) ||
30
- ![1, 2].includes(value.schema_version) || (value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(value.transmission)) || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
31
- value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' ||
32
- typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
33
- throw new Error('invalid_policy');
34
- // Validate an existing private state directory, without creating a path from untrusted event data.
35
- assertPrivateStatePath(join(value.state_directory, '.aptly-state-check'));
36
- const policy = Object.fromEntries(keys.map(key => [key, value[key]]));
37
- return { policy, fingerprint: hash(policy), reason: policy.enabled ? 'automatic_policy_enabled' : 'automatic_policy_disabled' };
41
+ return loadedPolicy(parseAutomaticHookPolicy(JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'))));
38
42
  }
39
43
  catch {
40
44
  return { policy: null, reason: 'automatic_policy_invalid' };
41
45
  }
42
46
  }
47
+ /** Query-only availability; the Hook's historical missing/invalid reasons remain unchanged. */
48
+ export function queryAutomaticHookPolicy(path, snapshot) {
49
+ try {
50
+ const bytes = snapshot.read(path, { privateFile: true, maxBytes: 4096 });
51
+ if (bytes === null)
52
+ return { policy: null, reason: 'automatic_policy_invalid', availability: 'absent' };
53
+ const policy = parseAutomaticHookPolicy(JSON.parse(bytes.toString('utf8')));
54
+ snapshot.track(policy.state_directory, { directory: true, privateFile: true, identityOnly: true });
55
+ return { ...loadedPolicy(policy), availability: 'valid' };
56
+ }
57
+ catch {
58
+ return { policy: null, reason: 'automatic_policy_invalid', availability: 'error' };
59
+ }
60
+ }
43
61
  function readCall(client, event) {
44
62
  try {
45
63
  if ((client !== 'codex' && client !== 'claude') || !plain(event) || event.hook_event_name !== 'PreToolUse' ||
@@ -284,7 +302,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
284
302
  return preserve(currentContext?.reason ?? 'context_changed');
285
303
  const legacyId = hookInput({ client, event, policy: router.policy })?.request_id ?? hash([call.client, call.event.session_id, call.event.tool_use_id ?? call.event.tool_call_id]);
286
304
  try {
287
- router.load();
305
+ router.load({ readOnly: true });
288
306
  }
289
307
  catch {
290
308
  return preserve('ledger_error');
@@ -307,7 +325,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
307
325
  const legacyId = hookInput({ client, event, policy: router.policy })?.request_id ??
308
326
  hash([call.client, call.event.session_id, call.event.tool_use_id ?? call.event.tool_call_id]);
309
327
  try {
310
- router.load();
328
+ router.load({ readOnly: true });
311
329
  }
312
330
  catch {
313
331
  return preserve('ledger_error');
@@ -3,7 +3,7 @@ import { budgetEnvironmentDefaults } from './budget.js';
3
3
  const client = ['codex', 'claude', 'all'];
4
4
  const scope = ['none', 'description', 'excerpt'];
5
5
  const entries = {
6
- '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; review transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select, review or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n stats [enable|disable] Inspect or control opt-in local execution statistics.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
6
+ '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; review transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select, review or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n stats [enable|disable] Inspect or control opt-in local execution statistics.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n doctor Inspect local registration and bounded ledger metadata.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
7
7
  serve: { usage: 'aptly serve', description: 'Start the stdio MCP server (default: fixture/shadow).\nDecisions mode requires ROUTER_PROVIDER=decisions, an absolute private ROUTER_LEDGER_PATH and a configured API key. Use aptly set env OPENAI_API_KEY for OS credential storage. Never put keys in request JSON or command arguments.' },
8
8
  capabilities: { usage: 'aptly capabilities', description: 'Print the active catalog, local limits and configuration metadata. No classification API call. Reads runtime configuration and credential availability; help does neither.' },
9
9
  catalog: { usage: 'aptly catalog\n aptly catalog refresh --output ABS_PATH', description: 'Print the active catalog without classification. Refresh is a separate explicit network operation; use aptly catalog refresh --help.' },
@@ -14,15 +14,16 @@ const entries = {
14
14
  set: { usage: 'aptly set default [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\n aptly set transmission --review [--client codex|claude|all]', description: 'Set operator-controlled defaults, environment values or transmission scope. Use the subcommand help for input, preservation and restart details.' },
15
15
  'set default': { usage: 'aptly set default [--client codex|claude|all]', description: 'Fill missing MCP environment defaults for both clients by default. Preserve existing values, inherited budget bindings and launchers. Does not reset budget usage or caches. Eligible interactive runs review each client/home once, including existing scopes. Excerpt is recommended; Enter keeps configured choices and sets unselected to none. Noninteractive, CI and lifecycle runs do not opt in. Prompts use stderr; stdout remains JSON. Restart MCP after changes.', options: { '--client': client } },
16
16
  'set env': { usage: 'aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]', description: 'Set a supported value using hidden input; --stdin explicitly reads standard input. --client defaults to all. --check is only for OPENAI_API_KEY and checks registration and Linux store readiness without reading/storing a key.\nOPENAI_API_KEY uses OS credential storage; host files contain references only. Values are never accepted as command arguments. Existing launchers are preserved. Restart MCP after changes.\nBudget defaults: ' + Object.entries(budgetEnvironmentDefaults).map(([key, value]) => key + '=' + value).join(', ') + '. Only literal 0 disables a ceiling; the per-call rate stays positive.\nSupported environment keys: $ENV_KEYS', options: { '--client': client, '--stdin': true, '--check': true }, positional: ['environment'] },
17
- 'set transmission': { usage: 'aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\n aptly set transmission --review [--client codex|claude|all]', description: 'Control automatic task-data transmission to OpenAI Decisions, not developer telemetry. none disables automatic transmission; description permits caller-provided descriptions only; excerpt permits native excerpts. Direct recommendations remain separate explicit requests. --show reads redacted registration/review state. --review explicitly asks again for configured clients; requires eligible interactive terminal streams and never repairs missing setup. Enter keeps each existing scope and selects none for unselected clients; excerpt is recommended, not the Enter default. Review completion is remembered per client/home, independently of package version, mode or statistics. Restart MCP after changes.', options: { '--client': client, '--show': true, '--review': true }, positional: ['scope'] },
18
- stats: { usage: 'aptly stats [--client codex|claude|all] [--today]\n aptly stats enable [--client codex|claude|all] [--codex-native-metadata]\n aptly stats disable [--client codex|claude|all]', description: 'Read retained local execution statistics without provider, credential or network access, state creation or update notification. Collection is disabled by default. --today uses UTC binding creation, not completion time. Model matches are host-reported model evidence, not user consent, quality, effective effort or billing. Aliases without canonical evidence remain unknown.', options: { '--client': client, '--today': true } },
19
- 'stats enable': { usage: 'aptly stats enable [--client codex|claude|all] [--codex-native-metadata]', description: 'Explicitly register local statistics observers and enable collection after existing Aptly setup. Initial support is POSIX only. Preserve routing, credentials, budget ledger, custom launchers and Hooks. Restart MCP/host and review new Codex Hooks with /hooks; trust is never written automatically. --codex-native-metadata additionally permits exact-child native SQLite metadata reads; existing SHM read marks may change, no row/schema writes or new sidecar files are intended. Unsupported/ambiguous evidence remains unknown.', options: { '--client': client, '--codex-native-metadata': true } },
17
+ 'set transmission': { usage: 'aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\n aptly set transmission --review [--client codex|claude|all]', description: 'Control automatic task-data transmission to OpenAI Decisions, not developer telemetry. none disables automatic transmission; description permits caller-provided descriptions only; excerpt permits native excerpts. Direct recommendations remain separate explicit requests. --show reads redacted registration/review state. Its additive top-level status is complete (exit 0) for completed queries, including none, unselected and genuinely unconfigured clients; partial (exit 1) reports query failures while retaining successful client results. Complete does not certify host routing, model or trust readiness. Strict JSON consumers must accept status. No automatic repair, consent or provider call occurs. --review explicitly asks again for configured clients; requires eligible interactive terminal streams and never repairs missing setup. Enter keeps each existing scope and selects none for unselected clients; excerpt is recommended, not the Enter default. Review completion is remembered per client/home, independently of package version, mode or statistics. Restart MCP after changes.', options: { '--client': client, '--show': true, '--review': true }, positional: ['scope'] },
18
+ stats: { usage: 'aptly stats [--client codex|claude|all] [--today]\n aptly stats enable [--client codex|claude|all] [--codex-native-metadata]\n aptly stats disable [--client codex|claude|all]', description: 'Read retained local execution statistics without provider, credential or network access, state creation or update notification. The additive top-level status is complete (exit 0) for completed queries, including disabled or genuinely unconfigured clients; partial (exit 1) reports query failures while retaining successful client results. Complete does not certify host routing, model or trust readiness. Strict JSON consumers must accept status. Collection is disabled by default. --today uses UTC binding creation, not completion time. Model matches are host-reported model evidence, not user consent, quality, effective effort or billing. Aliases without canonical evidence remain unknown.', options: { '--client': client, '--today': true } },
19
+ 'stats enable': { usage: 'aptly stats enable [--client codex|claude|all] [--codex-native-metadata]', description: 'Explicitly register local statistics observers and enable collection after existing Aptly setup. Initialize an empty statistics database before the first event; validate and preserve existing stores. Initialization failure reports partial setup with statistics_store_initialization_failed; applied registration may remain. Queries never initialize or repair a store. Initial support is POSIX only. Preserve routing, credentials, budget ledger, custom launchers and Hooks. Restart MCP/host and review new Codex Hooks with /hooks; trust is never written automatically. --codex-native-metadata additionally permits exact-child native SQLite metadata reads; existing SHM read marks may change, no row/schema writes or new sidecar files are intended. Unsupported/ambiguous evidence remains unknown.', options: { '--client': client, '--codex-native-metadata': true } },
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. CODEX_HOME must be explicitly set to an absolute directory at migration and server startup, 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] [--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 } },
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
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.' },
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 } },
26
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' } },
27
28
  };
28
29
  const helpFlag = (value) => value === '--help' || value === '-h';
@@ -14,6 +14,16 @@ export declare class ContextRetries {
14
14
  private policyPath;
15
15
  private now;
16
16
  constructor(router: Router, policyPath: unknown, now?: () => number);
17
+ /** Snapshot retained slots only; this does not check retry eligibility or mutate entries. */
18
+ diagnostics(): {
19
+ readonly scope: 'this_process';
20
+ readonly capacity: 128;
21
+ readonly used: number;
22
+ readonly remaining: number;
23
+ readonly expired_retained: number;
24
+ readonly in_flight: number;
25
+ readonly retry_eligibility: 'not_checked';
26
+ };
17
27
  private current;
18
28
  register(seed: ContextRetrySeed, current?: () => string | undefined): {
19
29
  retry_id?: string;
@@ -12,6 +12,19 @@ export class ContextRetries {
12
12
  policyPath;
13
13
  now;
14
14
  constructor(router, policyPath, now = Date.now) { this.router = router; this.policyPath = policyPath; this.now = now; }
15
+ /** Snapshot retained slots only; this does not check retry eligibility or mutate entries. */
16
+ diagnostics() {
17
+ const now = this.now();
18
+ let expired_retained = 0, in_flight = 0;
19
+ for (const entry of this.entries.values()) {
20
+ if (now - entry.at >= 300_000)
21
+ expired_retained++;
22
+ if (entry.active)
23
+ in_flight++;
24
+ }
25
+ const used = this.entries.size;
26
+ return { scope: 'this_process', capacity: 128, used, remaining: 128 - used, expired_retained, in_flight, retry_eligibility: 'not_checked' };
27
+ }
15
28
  current(entry, signal) {
16
29
  if (entry.cancelled || signal?.aborted)
17
30
  return 'context_retry_cancelled';
@@ -41,7 +54,7 @@ export class ContextRetries {
41
54
  if (!policy.policy?.enabled || policy.fingerprint !== seed.policy_fingerprint || ['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
42
55
  return { reason: 'automatic_policy_changed' };
43
56
  try {
44
- this.router.load();
57
+ this.router.load({ readOnly: true });
45
58
  const original = this.router.state.requests[seed.request_id];
46
59
  if (original && (original.state !== 'complete' || original.result?.status !== 'needs_context'))
47
60
  return { reason: original.state === 'unknown' ? 'outcome_unknown' : 'context_retry_not_eligible' };
@@ -65,7 +78,7 @@ export class ContextRetries {
65
78
  if (!seed.fresh_eligible || seed.application_blocked !== 'inherited_context_application_unverified')
66
79
  return { reason: 'fresh_delegation_unsupported' };
67
80
  try {
68
- this.router.load();
81
+ this.router.load({ readOnly: true });
69
82
  const record = this.router.state.requests[seed.request_id];
70
83
  if (!record || record.state !== 'complete' || record.result?.status !== 'recommended')
71
84
  return { reason: 'recommendation_not_available' };
@@ -191,7 +204,7 @@ export class ContextRetries {
191
204
  if (entry.active || this.router.active)
192
205
  return reject('concurrency_limit');
193
206
  try {
194
- this.router.load();
207
+ this.router.load({ readOnly: true });
195
208
  const record = this.router.state.requests[entry.recommendation_id ?? retry_id];
196
209
  if (!record)
197
210
  return reject('recommendation_not_found');
@@ -19,6 +19,8 @@ interface RouterOptions {
19
19
  ledgerPath?: string;
20
20
  budgetConfigurable?: boolean;
21
21
  }
22
+ export declare function validateStoredOutcome(result: unknown): asserts result is RoutingResult;
23
+ export declare function validateLedgerState(state: unknown): asserts state is LedgerState;
22
24
  export declare class Router {
23
25
  policy: RoutingPolicy;
24
26
  provider: RoutingProvider;
package/dist/src/core.js CHANGED
@@ -62,6 +62,43 @@ const outcomeReasons = {
62
62
  };
63
63
  const isClient = (value) => value === 'codex' || value === 'claude';
64
64
  const preservedFields = ['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits'];
65
+ export function validateStoredOutcome(result) {
66
+ if (!keysOnly(result, ['status', 'reason', 'application', 'policy_version', 'catalog_version', 'profile_id', 'profile', 'usage', 'latency_ms', 'confidence']) ||
67
+ typeof result.status !== 'string' || !own(outcomeReasons, result.status) || typeof result.reason !== 'string' || !outcomeReasons[result.status].includes(result.reason) || result.application !== 'advisory_only' ||
68
+ !safeVersion(result.policy_version) || !safeVersion(result.catalog_version) ||
69
+ (own(result, 'latency_ms') && (typeof result.latency_ms !== 'number' || !Number.isFinite(result.latency_ms) || result.latency_ms < 0 || result.latency_ms > 3600000)) ||
70
+ (own(result, 'confidence') && (typeof result.confidence !== 'number' || !Number.isFinite(result.confidence) || result.confidence < 0 || result.confidence > 1)))
71
+ throw new Error('invalid_outcome');
72
+ if (own(result, 'usage'))
73
+ usageOf(result.usage);
74
+ if (result.status === 'recommended') {
75
+ // Validate archival shape/known provenance without requiring membership
76
+ // in today's selected subset. Eligibility is checked again before reuse.
77
+ if (!isStoredProfile(result.profile) || result.profile_id !== result.profile.id)
78
+ throw new Error('invalid_outcome');
79
+ }
80
+ else if (own(result, 'profile') || own(result, 'profile_id'))
81
+ throw new Error('invalid_outcome');
82
+ }
83
+ export function validateLedgerState(state) {
84
+ if (!keysOnly(state, ['version', 'calls', 'estimated_usd', 'days', 'requests']) || state.version !== 1 || !safeInt(state.calls) || typeof state.estimated_usd !== 'number' || !Number.isFinite(state.estimated_usd) || state.estimated_usd < 0 ||
85
+ !isRecord(state.days) || !isRecord(state.requests))
86
+ throw new Error('invalid_ledger');
87
+ const days = state.days;
88
+ if (Object.entries(days).some(([day, calls]) => !/^\d{4}-\d{2}-\d{2}$/.test(day) || !safeInt(calls)))
89
+ throw new Error('invalid_ledger');
90
+ const validatedDays = days;
91
+ if (Object.values(validatedDays).reduce((a, b) => a + b, 0) !== state.calls)
92
+ throw new Error('invalid_ledger');
93
+ for (const [id, record] of Object.entries(state.requests)) {
94
+ if (!/^[A-Za-z0-9_-]{1,96}$/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id) || !keysOnly(record, ['digest', 'state', 'result']) || typeof record.digest !== 'string' || !/^[a-f0-9]{64}$/.test(record.digest) || (record.state !== 'complete' && record.state !== 'unknown'))
95
+ throw new Error('invalid_ledger');
96
+ if (record.state === 'complete')
97
+ validateStoredOutcome(record.result);
98
+ else if (own(record, 'result'))
99
+ throw new Error('invalid_ledger');
100
+ }
101
+ }
65
102
  export class Router {
66
103
  policy;
67
104
  provider;
@@ -155,24 +192,7 @@ export class Router {
155
192
  result(status, reason, extra = {}) {
156
193
  return { status, reason, application: 'advisory_only', policy_version: this.policy.version, catalog_version: this.policy.catalog_version, ...extra };
157
194
  }
158
- validateOutcome(result) {
159
- if (!keysOnly(result, ['status', 'reason', 'application', 'policy_version', 'catalog_version', 'profile_id', 'profile', 'usage', 'latency_ms', 'confidence']) ||
160
- typeof result.status !== 'string' || !own(outcomeReasons, result.status) || typeof result.reason !== 'string' || !outcomeReasons[result.status].includes(result.reason) || result.application !== 'advisory_only' ||
161
- !safeVersion(result.policy_version) || !safeVersion(result.catalog_version) ||
162
- (own(result, 'latency_ms') && (typeof result.latency_ms !== 'number' || !Number.isFinite(result.latency_ms) || result.latency_ms < 0 || result.latency_ms > 3600000)) ||
163
- (own(result, 'confidence') && (typeof result.confidence !== 'number' || !Number.isFinite(result.confidence) || result.confidence < 0 || result.confidence > 1)))
164
- throw new Error('invalid_outcome');
165
- if (own(result, 'usage'))
166
- usageOf(result.usage);
167
- if (result.status === 'recommended') {
168
- // Validate archival shape/known provenance without requiring membership
169
- // in today's selected subset. Eligibility is checked again before reuse.
170
- if (!isStoredProfile(result.profile) || result.profile_id !== result.profile.id)
171
- throw new Error('invalid_outcome');
172
- }
173
- else if (own(result, 'profile') || own(result, 'profile_id'))
174
- throw new Error('invalid_outcome');
175
- }
195
+ validateOutcome(result) { validateStoredOutcome(result); }
176
196
  load({ readOnly = false } = {}) {
177
197
  if (!this.ledgerPath)
178
198
  return;
@@ -184,23 +204,7 @@ export class Router {
184
204
  if (!readOnly)
185
205
  chmodSync(this.ledgerPath, 0o600);
186
206
  const state = JSON.parse(readFileSync(this.ledgerPath, 'utf8'));
187
- if (!keysOnly(state, ['version', 'calls', 'estimated_usd', 'days', 'requests']) || state.version !== 1 || !safeInt(state.calls) || typeof state.estimated_usd !== 'number' || !Number.isFinite(state.estimated_usd) || state.estimated_usd < 0 ||
188
- !isRecord(state.days) || !isRecord(state.requests))
189
- throw new Error('invalid_ledger');
190
- const days = state.days;
191
- if (Object.entries(days).some(([day, calls]) => !/^\d{4}-\d{2}-\d{2}$/.test(day) || !safeInt(calls)))
192
- throw new Error('invalid_ledger');
193
- const validatedDays = days;
194
- if (Object.values(validatedDays).reduce((a, b) => a + b, 0) !== state.calls)
195
- throw new Error('invalid_ledger');
196
- for (const [id, record] of Object.entries(state.requests)) {
197
- if (!/^[A-Za-z0-9_-]{1,96}$/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id) || !keysOnly(record, ['digest', 'state', 'result']) || typeof record.digest !== 'string' || !/^[a-f0-9]{64}$/.test(record.digest) || (record.state !== 'complete' && record.state !== 'unknown'))
198
- throw new Error('invalid_ledger');
199
- if (record.state === 'complete')
200
- this.validateOutcome(record.result);
201
- else if (own(record, 'result'))
202
- throw new Error('invalid_ledger');
203
- }
207
+ validateLedgerState(state);
204
208
  // All records, counters and outcomes were validated above; no parsed
205
209
  // JSON shape is trusted at the file boundary before those checks.
206
210
  this.state = state;
@@ -0,0 +1,84 @@
1
+ import { QuerySnapshot } from './query-snapshot.ts';
2
+ import type { Client } from './types.ts';
3
+ export declare const DOCTOR_LEDGER_SCAN_LIMIT: number;
4
+ /** No lock, load, state initialization, provider or filesystem mutation. */
5
+ export declare function observeDoctorLedger(path: string, snapshot: QuerySnapshot): {
6
+ bytes: number | null;
7
+ scan_limit_bytes: number;
8
+ write_timing: string;
9
+ counts: null;
10
+ status: string;
11
+ history: "unknown";
12
+ } | {
13
+ bytes: number | null;
14
+ scan_limit_bytes: number;
15
+ write_timing: string;
16
+ status: string;
17
+ counts: {
18
+ total: number;
19
+ complete: number;
20
+ unknown: number;
21
+ };
22
+ };
23
+ export interface DoctorOptions {
24
+ home?: string;
25
+ env?: NodeJS.ProcessEnv;
26
+ clients?: Client[];
27
+ }
28
+ export declare function collectDoctor(options?: DoctorOptions): {
29
+ kind: string;
30
+ schema_version: number;
31
+ status: string;
32
+ cli_version: string;
33
+ scope: string;
34
+ readiness: string;
35
+ clients: ({
36
+ client: Client;
37
+ selected_home_source: string;
38
+ connected_mcp_version: "unknown";
39
+ hook_trust: "unknown";
40
+ hook_execution: "unknown";
41
+ restart_required: "unknown";
42
+ retry_ticket_usage: "unknown";
43
+ credential_validity: "unknown";
44
+ status: string;
45
+ registration: string;
46
+ } | {
47
+ client: Client;
48
+ selected_home_source: string;
49
+ connected_mcp_version: "unknown";
50
+ hook_trust: "unknown";
51
+ hook_execution: "unknown";
52
+ restart_required: "unknown";
53
+ retry_ticket_usage: "unknown";
54
+ credential_validity: "unknown";
55
+ status: string;
56
+ registration: string;
57
+ registered_package: {
58
+ status: string;
59
+ version: string | null;
60
+ };
61
+ policy: {
62
+ source_kind: string;
63
+ status: string;
64
+ transmission: unknown;
65
+ };
66
+ hook_registration: string;
67
+ credential_reference: string;
68
+ ledger: {
69
+ diagnostic_scan_ms: number;
70
+ timing_scope: string;
71
+ };
72
+ } | {
73
+ client: Client;
74
+ selected_home_source: string;
75
+ connected_mcp_version: "unknown";
76
+ hook_trust: "unknown";
77
+ hook_execution: "unknown";
78
+ restart_required: "unknown";
79
+ retry_ticket_usage: "unknown";
80
+ credential_validity: "unknown";
81
+ status: string;
82
+ code: string;
83
+ })[];
84
+ };