aptly 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -23,12 +23,12 @@ Our own tests showed **about 52–58% lower API-equivalent costs**. See the [tes
23
23
  Requires Node.js **24 or later** and Claude Code or Codex. Install the latest stable version globally with these commands.
24
24
 
25
25
  ```sh
26
- npm install -g aptly@latest
26
+ npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
28
  aptly --version
29
29
  ```
30
30
 
31
- Check the installed version with `aptly --version`.
31
+ Check the installed version with `aptly --version`. On supported npm versions, `--allow-scripts=aptly` allows Aptly’s installation script. If your npm does not support this option, follow the explicit installation and setup steps in the [installation guide](docs/guide/en.md#installation).
32
32
 
33
33
  Before upgrading, stop all related host, MCP, and CLI processes and review the ledger transition in the [installation and upgrade guide](docs/guide/en.md#installation).
34
34
 
@@ -40,11 +40,11 @@ Store the classification key, `OPENAI_API_KEY`, in the OS credential store using
40
40
 
41
41
  | Mode | Behavior |
42
42
  |---|---|
43
- | Automatic Hook | Selects defaults for fresh, general-purpose calls without an explicit model, effort, fixed role, inherited history, or resume target |
43
+ | Automatic Hook | Checks constraints and recommends unspecified defaults for new calls |
44
44
  | Direct recommendation | Returns a profile through `recommend_agent` or `aptly recommend`; review it and decide separately whether to run it in the host |
45
45
  | fixture | Tests recommendations generated by local rules without a key or network access; these are not actual Decisions results |
46
46
 
47
- Automatic selection targets Codex calls with `fork_turns: "none"` and Claude Code calls with `subagent_type: "general-purpose"`. Explicit choices, insufficient context, and authentication or connection errors leave the original call unchanged. A recommendation does not verify model access or the host's complete configuration.
47
+ From Aptly 0.1.4, inherited calls also reach recommendation. Application still requires explicit `fork_turns: "none"` in Codex or a general-purpose Claude Code call without history constraints; specified fields are preserved. Recommendation, Hook argument updates and child execution are separate facts. See the [guide](docs/guide/en.md#automatic-hook) for application conditions.
48
48
 
49
49
  ## Documentation
50
50
 
package/README.ja.md CHANGED
@@ -23,12 +23,12 @@ Aptly は必要最小限のタスク要約を OpenAI Decisions API で分類し
23
23
  Node.js **24 以上**と Claude Code または Codex が必要です。以下のコマンドで最新の安定版をグローバルインストールしてください。
24
24
 
25
25
  ```sh
26
- npm install -g aptly@latest
26
+ npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
28
  aptly --version
29
29
  ```
30
30
 
31
- `aptly --version` でインストール済みのバージョンを確認してください。
31
+ `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。
32
32
 
33
33
  アップグレード前に、関連するホスト・MCP・CLI の全プロセスを停止し、[インストールとアップグレードの案内](docs/guide/ja.md#インストール)で台帳の移行手順を確認してください。
34
34
 
@@ -40,11 +40,11 @@ aptly --version
40
40
 
41
41
  | 方法 | 動作 |
42
42
  |---|---|
43
- | 自動 Hook | モデル・effort・固定ロール・履歴継承・resume の指定がない、新しい汎用呼び出しのデフォルト値を選びます |
43
+ | 自動 Hook | 新しい呼び出しの制約を確認し、未指定のデフォルト値を推薦します |
44
44
  | 直接推薦 | `recommend_agent` または `aptly recommend` でプロファイルを受け取り、実行するかどうかをホストで明示的に判断します |
45
45
  | fixture | キーやネットワークを使わず、ローカルで生成した試験用の推薦を確認できます。実際の Decisions の結果ではありません |
46
46
 
47
- 自動選択の対象は、Codex の `fork_turns: "none"`、Claude Code の `subagent_type: "general-purpose"` の呼び出しです。明示的な指定や、コンテキスト不足・認証・接続エラーがある場合は、元の呼び出しの引数を変更しません。推薦されたというだけでは、モデルへのアクセス権限やホストの設定全体が確認されたことにはなりません。
47
+ Aptly 0.1.4 以降では継承呼び出しも推薦を評価します。適用には Codex の明示的な `fork_turns: "none"`、または履歴制約のない Claude Code の汎用呼び出しが必要で、指定済みフィールドは保持します。推薦・Hook 引数更新・実際の子の実行は別です。適用条件は[ガイド](docs/guide/ja.md#自動-hook)を参照してください。
48
48
 
49
49
  ## ドキュメント
50
50
 
package/README.md CHANGED
@@ -23,12 +23,12 @@ Aptly는 최소한의 작업 요약을 OpenAI Decisions API로 분류하고 허
23
23
  Node.js **24 이상**과 Claude Code 또는 Codex가 필요합니다. 다음 명령으로 최신 안정 버전을 전역 설치하십시오.
24
24
 
25
25
  ```sh
26
- npm install -g aptly@latest
26
+ npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
28
  aptly --version
29
29
  ```
30
30
 
31
- `aptly --version`으로 설치된 버전을 확인하십시오.
31
+ `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오.
32
32
 
33
33
  업그레이드 전에는 관련 호스트·MCP·CLI 프로세스를 모두 중지하고 [설치·업그레이드 안내](docs/guide/ko.md#설치)의 원장 전환 절차를 확인하십시오.
34
34
 
@@ -40,11 +40,11 @@ aptly --version
40
40
 
41
41
  | 방식 | 동작 |
42
42
  |---|---|
43
- | 자동 Hook | 모델·effort·고정 역할·이력 상속·resume을 지정하지 않은 새 일반 호출의 기본값을 선택합니다 |
43
+ | 자동 Hook | 새 호출의 제약을 검사하고 미지정 기본값을 추천합니다 |
44
44
  | 직접 추천 | `recommend_agent` 또는 `aptly recommend`로 프로필을 받고 호스트에서 명시적으로 실행합니다 |
45
45
  | fixture | 키·네트워크 없이 시험용 추천을 확인합니다. 실제 Decisions 결과가 아닙니다 |
46
46
 
47
- 자동 선택 대상은 Codex의 `fork_turns: "none"`, Claude Code의 `subagent_type: "general-purpose"` 호출입니다. 명시 선택이나 맥락 부족·인증·연결 오류가 있으면 원래 호출을 유지합니다. 추천은 모델 접근 권한이나 호스트 전체 설정의 확인을 뜻하지 않습니다.
47
+ Aptly 0.1.4부터 상속 호출도 추천을 평가합니다. Codex의 적용은 명시적인 `fork_turns: "none"`, Claude Code는 이력 제약 없는 일반 호출로 제한하며 명시한 필드는 보존합니다. 추천·Hook 인자 변경·실제 자식 실행은 별개입니다. 적용 조건은 [가이드](docs/guide/ko.md#자동-hook)에서 확인하십시오.
48
48
 
49
49
  ## 문서
50
50
 
package/README.zh-CN.md CHANGED
@@ -23,12 +23,12 @@ Aptly 使用 OpenAI Decisions API 对简要任务摘要进行分类,并推荐
23
23
  需要 Node.js **24 或更高版本**以及 Claude Code 或 Codex。请使用以下命令全局安装最新稳定版。
24
24
 
25
25
  ```sh
26
- npm install -g aptly@latest
26
+ npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
28
  aptly --version
29
29
  ```
30
30
 
31
- 请使用 `aptly --version` 确认已安装的版本。
31
+ 请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。
32
32
 
33
33
  升级前,请停止所有相关宿主、MCP 和 CLI 进程,并查看[安装与升级指南](docs/guide/zh-CN.md#安装)中的账本迁移步骤。
34
34
 
@@ -40,11 +40,11 @@ aptly --version
40
40
 
41
41
  | 方式 | 行为 |
42
42
  |---|---|
43
- | 自动 Hook | 为未指定模型、effort、固定角色、历史继承或 resume 的新建通用调用选择默认值 |
43
+ | 自动 Hook | 检查新调用的约束,并推荐未指定的默认值 |
44
44
  | 直接推荐 | 通过 `recommend_agent` 或 `aptly recommend` 获取执行配置,再在宿主中明确选择并执行 |
45
45
  | fixture | 无需密钥或网络即可测试本地模拟推荐;结果并非实际 Decisions 判断 |
46
46
 
47
- 自动选择适用于 Codex 的 `fork_turns: "none"` 调用和 Claude Code 的 `subagent_type: "general-purpose"` 调用。如果已有明确选择,或发生上下文不足、认证或连接错误,则保留原始调用。推荐结果并不表示已确认账户的模型访问权限,也不表示已核实宿主的全部配置。
47
+ Aptly 0.1.4 起也会为继承调用评估推荐。应用仍要求 Codex 显式指定 `fork_turns: "none"`,或 Claude Code 使用无历史约束的通用调用;已指定字段会保留。推荐、Hook 参数更新与实际子代理执行是不同事实。应用条件详见[指南](docs/guide/zh-CN.md#自动-hook)。
48
48
 
49
49
  ## 文档
50
50
 
package/dist/bin/aptly.js CHANGED
@@ -12,11 +12,26 @@ import { errorCode } from '../src/types.js';
12
12
  import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher } from '../src/setup.js';
13
13
  import { readEnvironmentValue } from '../src/cli-input.js';
14
14
  import { prepareApiKey } from '../src/credential-setup.js';
15
+ import { updateGlobalInstallation } from '../src/update.js';
16
+ import { updateNotification } from '../src/update-notifier.js';
15
17
  const [command = 'serve', ...args] = process.argv.slice(2);
16
18
  const output = (value) => process.stdout.write(JSON.stringify(value, null, 2) + '\n');
17
19
  try {
18
20
  if (['--help', '-h', 'help'].includes(command)) {
19
- process.stdout.write('Aptly (preview)\n\nCommands:\n serve Start the stdio MCP server (default: fixture/shadow).\n capabilities Print the active catalog; no API call.\n catalog Print the active catalog; no API call.\n catalog refresh --output ABS_PATH Fetch official model descriptions to a private cache.\n recommend Recommend for a task JSON on stdin; no host evidence required.\n inspect CLIENT FILE Inspect an explicit JSON settings inventory; no API call.\n config CLIENT Print an MCP registration fragment; does not edit settings.\n set default Add missing default MCP environment settings.\n set env ENV_KEY Prompt for an MCP environment value.\n setup Register MCP and automatic PreToolUse Hooks.\n remove Remove only unchanged Aptly-owned registration.\n report Write redacted local diagnostic attachments (default: md + json).\n --format md|json|both Select report formats.\n --output-dir DIR Private output directory (default: reports).\n --version Print the package version.\n\nUse aptly set env OPENAI_API_KEY for OS storage, or pass it through the MCP environment.\nPaid mode additionally requires\nROUTER_PROVIDER=decisions and an absolute ROUTER_LEDGER_PATH in a private directory.\nROUTER_CONFIG_PATH is an optional private operator configuration file.\n');
21
+ process.stdout.write('Aptly (preview)\n\nCommands:\n serve Start the stdio MCP server (default: fixture/shadow).\n capabilities Print the active catalog; no API call.\n catalog Print the active catalog; no API call.\n catalog refresh --output ABS_PATH Fetch official model descriptions to a private cache.\n recommend Recommend for a task JSON on stdin; no host evidence required.\n inspect CLIENT FILE Inspect an explicit JSON settings inventory; no API call.\n config CLIENT Print an MCP registration fragment; does not edit settings.\n set default Add missing default MCP environment settings.\n set env ENV_KEY Prompt for an MCP environment value.\n setup Register MCP and automatic PreToolUse Hooks.\n remove Remove only unchanged Aptly-owned registration.\n update Update this verified global npm installation.\n report Write redacted local diagnostic attachments (default: md + json).\n --format md|json|both Select report formats.\n --output-dir DIR Private output directory (default: reports).\n --version Print the package version.\n\nUse aptly set env OPENAI_API_KEY for OS storage, or pass it through the MCP environment.\nPaid mode additionally requires\nROUTER_PROVIDER=decisions and an absolute ROUTER_LEDGER_PATH in a private directory.\nROUTER_CONFIG_PATH is an optional private operator configuration file.\n');
22
+ }
23
+ else if (command === 'update') {
24
+ if (args.length === 1 && args[0] === '--help')
25
+ process.stdout.write('Usage: aptly update\nRequires a verified global npm installation. Stop other hosts/MCP/CLI writers first.\nUpdates the same npm prefix without lifecycle setup. Run aptly setup and restart hosts afterward; existing launchers are preserved.\n');
26
+ else {
27
+ if (args.length)
28
+ throw new Error('update_invalid_options');
29
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
30
+ const result = updateGlobalInstallation({ packageRoot });
31
+ output(result);
32
+ if (result.status === 'error')
33
+ process.exitCode = 1;
34
+ }
20
35
  }
21
36
  else if (command === '--version')
22
37
  process.stdout.write(VERSION + '\n');
@@ -102,13 +117,14 @@ try {
102
117
  }
103
118
  else if (['setup', 'remove'].includes(command)) {
104
119
  if (args.length === 1 && args[0] === '--help')
105
- process.stdout.write('Usage: aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--dry-run]\n aptly remove [--client codex|claude|all]\nSetup merges MCP and PreToolUse registration. Codex requires native /hooks trust review.\nAutomatic setup skips CI, APTLY_SKIP_SETUP=1, and absent host directories. No keys are stored.\n');
120
+ process.stdout.write('Usage: aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]\n aptly remove [--client codex|claude|all]\nSetup merges MCP and PreToolUse registration. Codex requires native /hooks trust review.\nAutomatic setup skips CI, APTLY_SKIP_SETUP=1, and absent host directories. No keys are stored.\n');
106
121
  else {
107
122
  let clients = ['codex', 'claude'];
108
123
  let mode = 'defaults';
109
124
  let automatic = false;
110
125
  let migrate = false;
111
126
  let dryRun = false;
127
+ let includeExisting = false;
112
128
  const seen = new Set();
113
129
  for (let i = 0; i < args.length; i++) {
114
130
  const flag = args[i];
@@ -119,6 +135,10 @@ try {
119
135
  migrate = true;
120
136
  continue;
121
137
  }
138
+ if (flag === '--include-existing' && command === 'setup') {
139
+ includeExisting = true;
140
+ continue;
141
+ }
122
142
  if (flag === '--dry-run' && command === 'setup') {
123
143
  dryRun = true;
124
144
  continue;
@@ -136,9 +156,9 @@ try {
136
156
  throw new Error('setup_invalid_options');
137
157
  }
138
158
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
139
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode'))) || (dryRun && !migrate))
159
+ if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode'))) || ((dryRun || includeExisting) && !migrate))
140
160
  throw new Error('setup_invalid_options');
141
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot }) : removeSetup({ clients });
161
+ const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot }) : removeSetup({ clients });
142
162
  output(result);
143
163
  if (result.status === 'partial' && !automatic)
144
164
  process.exitCode = 1;
@@ -194,7 +214,17 @@ catch (error) {
194
214
  const message = error instanceof Error ? error.message : undefined;
195
215
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
196
216
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
197
- const code = command === 'set' ? (setCodes.includes(message ?? '') ? message : 'set_failed') : command === 'report' ? (caughtCode && codes.includes(caughtCode) ? caughtCode : 'report_failed') : configCode ?? 'operation_failed';
217
+ const code = 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') : configCode ?? 'operation_failed';
198
218
  process.stderr.write('aptly: ' + code + '\n');
199
219
  process.exitCode = 1;
200
220
  }
221
+ finally {
222
+ if (!process.exitCode) {
223
+ try {
224
+ const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
225
+ if (hint)
226
+ process.stderr.write(hint + '\n');
227
+ }
228
+ catch { /* Optional update hints cannot fail a successful command. */ }
229
+ }
230
+ }
@@ -9,7 +9,14 @@ export interface AutoPolicy {
9
9
  state_directory: string;
10
10
  }
11
11
  export interface AutomaticHookObservation {
12
- status: 'applied' | 'advisory' | 'preserved';
12
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending';
13
+ preflight: 'observed';
14
+ correlation_id?: string;
15
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
16
+ recommendation: 'not_produced' | 'produced';
17
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
18
+ execution: 'not_observed';
19
+ constraint_provenance: 'unknown';
13
20
  reason: string;
14
21
  profile_id?: string;
15
22
  request_id?: string;
@@ -29,7 +36,15 @@ export interface AutomaticHookOptions {
29
36
  router: Router;
30
37
  /** Internal configuration only: callers read APTLY_HOOK_POLICY_PATH, never MCP arguments. */
31
38
  policyPath?: unknown;
39
+ /** Internal process-local handoff; never accepted as native policy/provenance. */
40
+ context?: () => {
41
+ summary?: string;
42
+ fingerprint?: string;
43
+ reason?: string;
44
+ } | undefined;
32
45
  signal?: AbortSignal;
46
+ /** Internal diagnostics callback; never supplied through native tool arguments. */
47
+ onObservation?: (observation: AutomaticHookObservation) => void;
33
48
  /** A caller may revoke the pending event; absence does not certify native dispatch. */
34
49
  stillCurrent?: () => boolean | Promise<boolean>;
35
50
  }
@@ -38,5 +53,11 @@ export declare function loadAutomaticHookPolicy(path: unknown): {
38
53
  reason: string;
39
54
  fingerprint?: string;
40
55
  };
56
+ export declare function automaticCallIdentity(client: unknown, event: unknown): {
57
+ key: string;
58
+ id: string;
59
+ } | undefined;
60
+ export declare function automaticCallId(client: unknown, event: unknown): string | undefined;
61
+ export declare function initialHookObservation(client: unknown, event: unknown): AutomaticHookObservation;
41
62
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
42
- export declare function automaticHook({ client, event, router, policyPath, signal, stillCurrent }: AutomaticHookOptions): Promise<AutomaticHookResult>;
63
+ export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation }: AutomaticHookOptions): Promise<AutomaticHookResult>;
@@ -4,7 +4,7 @@ import { closeSync, openSync, writeFileSync } from 'node:fs';
4
4
  import { isAbsolute, join } from 'node:path';
5
5
  import { Router } from './core.js';
6
6
  import { assertPrivateStatePath, readRegularFile } from './files.js';
7
- import { hookInput, hookOutput } from './hook.js';
7
+ import { hookInput, hookOutput, validatedHookProfile, profilePreservesChoices, effortKeys } from './hook.js';
8
8
  import { digestToolInput } from './provenance.js';
9
9
  const own = (object, key) => Object.hasOwn(object, key);
10
10
  const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) &&
@@ -61,20 +61,40 @@ function readCall(client, event) {
61
61
  }
62
62
  function preservation(call) {
63
63
  const input = call.input;
64
- if (own(input, 'model'))
65
- return 'explicit_model';
66
- if (['effort', 'reasoning_effort', 'model_reasoning_effort'].some(key => own(input, key)))
67
- return 'explicit_effort';
68
64
  if (['resume', 'resume_agent', 'agent_id'].some(key => own(input, key)))
69
65
  return 'resumed_agent';
70
66
  if (['role', 'agent_type'].some(key => own(input, key)) ||
71
- (call.client === 'claude' && input.subagent_type !== 'general-purpose'))
67
+ (call.client === 'claude' && input.subagent_type !== 'general-purpose') ||
68
+ (call.client === 'codex' && own(input, 'subagent_type')))
72
69
  return 'fixed_role';
73
- if (['fork_context', 'fork', 'fork_session', 'inherit_history'].some(key => own(input, key)) ||
74
- (call.client === 'codex' ? input.fork_turns !== 'none' : own(input, 'fork_turns')))
75
- return 'inherited_fork';
76
70
  return null;
77
71
  }
72
+ /** History semantics are checked at application, not used to suppress task advice. */
73
+ function applicationConstraint(call) {
74
+ if (['fork_context', 'fork', 'fork_session', 'inherit_history'].some(key => own(call.input, key)))
75
+ return 'history_semantics_unverified';
76
+ if (call.client === 'codex' && call.input.fork_turns !== 'none')
77
+ return 'inherited_context_application_unverified';
78
+ if (call.client === 'claude' && own(call.input, 'fork_turns'))
79
+ return 'history_semantics_unverified';
80
+ // Only reasoning_effort has an application contract for native Codex spawns.
81
+ if (effortKeys.some(key => key !== 'reasoning_effort' && own(call.input, key)))
82
+ return 'effort_argument_unsupported';
83
+ return null;
84
+ }
85
+ export function automaticCallIdentity(client, event) {
86
+ const call = readCall(client, event);
87
+ return call ? { key: call.callKey, id: hash(['aptly-observation-v1', call.callKey, call.payloadDigest]) } : undefined;
88
+ }
89
+ export function automaticCallId(client, event) {
90
+ const call = readCall(client, event);
91
+ return call ? hash(['aptly-observation-v1', call.callKey, call.payloadDigest]) : undefined;
92
+ }
93
+ export function initialHookObservation(client, event) {
94
+ const id = automaticCallId(client, event);
95
+ return { status: 'pending', reason: 'preflight_pending', preflight: 'observed', ...(id ? { correlation_id: id } : {}),
96
+ classification: 'not_requested', recommendation: 'not_produced', application: 'not_attempted', execution: 'not_observed', constraint_provenance: 'unknown' };
97
+ }
78
98
  function catalogFingerprint(policy) {
79
99
  return hash([policy.version, policy.catalog_version, policy.provider_id ?? null, policy.profiles, policy.profile_descriptions ?? {}]);
80
100
  }
@@ -90,10 +110,14 @@ function boundedSummary(call, maxBytes) {
90
110
  // it or forward it to the provider: a sufficiently descriptive visible name
91
111
  // is a separate, explicitly labelled source of task advice only.
92
112
  if (call.client === 'codex' && /^gAAAA[A-Za-z0-9_-]{75,}={0,2}$/.test(body)) {
93
- if (!safeText(label, 512) || Buffer.byteLength(label) < 24 || !/^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(label))
113
+ if (!safeText(label, 512) || !/^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(label))
94
114
  return { reason: 'insufficient_context' };
95
115
  const words = label.split('_');
96
- if (words.length < 6 || words.filter(word => /^[a-z]{2,}$/.test(word)).length < 3)
116
+ // Short labels need a concrete action, scope and object, not word padding.
117
+ // This is advice from the label alone, never authorization to perform it.
118
+ const concreteShortName = /^(?:cleanup|remove|prune)_merged_(?:worktrees|branches)$/.test(label) ||
119
+ /^(?:review|fix|test)_(?:failing|broken|flaky)_(?:tests|builds)$/.test(label);
120
+ if (!concreteShortName && (Buffer.byteLength(label) < 24 || words.length < 6 || words.filter(word => /^[a-z]{2,}$/.test(word)).length < 3))
97
121
  return { reason: 'insufficient_context' };
98
122
  const summary = `Task summary from visible task_name only; opaque message not inspected: ${words.join(' ')}`;
99
123
  if (Buffer.byteLength(summary) > Math.min(4000, maxBytes))
@@ -118,9 +142,9 @@ function boundedSummary(call, maxBytes) {
118
142
  }
119
143
  return { summary: prefix + clipped };
120
144
  }
121
- function bindCall(call, policy, policyFingerprint, catalog) {
122
- const binding = { schema_version: 1, input_digest: call.digest, payload_digest: call.payloadDigest, policy_fingerprint: policyFingerprint, catalog_fingerprint: catalog,
123
- request_id: hash(['aptly-auto-hook-v1', call.callKey, call.payloadDigest, policyFingerprint, catalog]) };
145
+ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
146
+ const binding = { ...(contextDigest ? { context_digest: contextDigest } : {}), schema_version: 1, input_digest: call.digest, payload_digest: call.payloadDigest, policy_fingerprint: policyFingerprint, catalog_fingerprint: catalog,
147
+ request_id: hash(['aptly-auto-hook-v1', call.callKey, call.payloadDigest, policyFingerprint, catalog, ...(contextDigest ? [contextDigest] : [])]) };
124
148
  const path = join(policy.state_directory, `hook-call-${call.callKey}.json`);
125
149
  let fd;
126
150
  try {
@@ -153,8 +177,9 @@ function bindCall(call, policy, policyFingerprint, catalog) {
153
177
  }
154
178
  }
155
179
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
156
- export async function automaticHook({ client, event, router, policyPath, signal, stillCurrent }) {
157
- const preserve = (reason, request_id) => ({ output: {}, observation: { status: 'preserved', reason, ...(request_id ? { request_id } : {}) } });
180
+ export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation }) {
181
+ const observation = initialHookObservation(client, event);
182
+ const preserve = (reason, request_id) => ({ output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } });
158
183
  try {
159
184
  const loaded = loadAutomaticHookPolicy(policyPath);
160
185
  if (!loaded.policy || !loaded.policy.enabled || !loaded.fingerprint)
@@ -165,10 +190,21 @@ export async function automaticHook({ client, event, router, policyPath, signal,
165
190
  const pinned = preservation(call);
166
191
  if (pinned)
167
192
  return preserve(pinned);
193
+ const hasModel = own(call.input, 'model'), hasEffort = effortKeys.some(key => own(call.input, key));
194
+ if (hasModel && (hasEffort || call.client === 'claude'))
195
+ return preserve('explicit_model');
196
+ const profiles = router.policy.profiles.filter(profile => profile.client === call.client && profilePreservesChoices(call.input, profile));
197
+ if (!profiles.length)
198
+ return preserve(hasModel ? 'explicit_model' : hasEffort ? 'explicit_effort' : 'no_candidates');
168
199
  // Synthetic fixture output must never select a native child's defaults.
169
200
  if (loaded.policy.mode === 'defaults' && router.policy.provider_id !== 'decisions')
170
201
  return preserve('synthetic_provider');
171
- const summary = boundedSummary(call, router.policy.max_summary_bytes);
202
+ const supplied = context?.();
203
+ if (supplied?.reason)
204
+ return preserve(supplied.reason);
205
+ const summary = supplied?.summary ? supplied : boundedSummary(call, router.policy.max_summary_bytes);
206
+ if (Buffer.byteLength(summary.summary ?? '') > Math.min(4000, router.policy.max_summary_bytes))
207
+ return preserve('insufficient_context');
172
208
  if (!summary.summary)
173
209
  return preserve(summary.reason ?? 'insufficient_context');
174
210
  if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
@@ -190,19 +226,40 @@ export async function automaticHook({ client, event, router, policyPath, signal,
190
226
  }
191
227
  if (own(router.state.requests, legacyId))
192
228
  return preserve('legacy_request_exists', legacyId);
229
+ const contextBeforePaid = context?.();
230
+ if (contextBeforePaid?.reason || contextBeforePaid?.fingerprint !== supplied?.fingerprint)
231
+ return preserve(contextBeforePaid?.reason ?? 'context_changed');
193
232
  const catalog = catalogFingerprint(router.policy);
194
- const bound = bindCall(call, loaded.policy, loaded.fingerprint, catalog);
233
+ const bound = bindCall(call, loaded.policy, loaded.fingerprint, catalog, supplied?.fingerprint);
195
234
  if (!bound.request_id)
196
235
  return preserve(bound.reason ?? 'automatic_state_unavailable');
197
236
  const request_id = bound.request_id;
198
237
  const snapshot = structuredClone(call.event);
238
+ observation.classification = 'evaluating';
239
+ observation.request_id = request_id;
240
+ try {
241
+ onObservation?.({ ...observation });
242
+ }
243
+ catch { /* Diagnostics do not change routing. */ }
244
+ // These flags describe selection of the remaining defaults only. Explicit
245
+ // values constrain the candidate tuples; history is rechecked before application.
199
246
  const recommendation = await router.advise({ request_id, client: call.client,
200
247
  task: { summary: summary.summary, operation: 'analysis', context_sufficient: true },
201
- eligible_profile_ids: router.policy.profiles.filter(profile => profile.client === call.client).map(profile => profile.id),
248
+ eligible_profile_ids: profiles.map(profile => profile.id),
202
249
  constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false },
203
250
  });
251
+ observation.classification = recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome';
252
+ const profile = validatedHookProfile(client, recommendation, router.policy);
253
+ if (profile && profiles.some(candidate => candidate.id === profile.id)) {
254
+ observation.recommendation = 'produced';
255
+ observation.profile_id = profile.id;
256
+ observation.application = 'blocked';
257
+ }
204
258
  if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
205
259
  return preserve('call_cancelled', request_id);
260
+ const currentContext = context?.();
261
+ if (currentContext?.reason || currentContext?.fingerprint !== supplied?.fingerprint)
262
+ return preserve(currentContext?.reason ?? 'context_changed', request_id);
206
263
  const current = readCall(client, event), policyNow = loadAutomaticHookPolicy(policyPath);
207
264
  if (!current || current.callKey !== call.callKey || current.digest !== call.digest || current.payloadDigest !== call.payloadDigest)
208
265
  return preserve('call_changed', request_id);
@@ -212,21 +269,31 @@ export async function automaticHook({ client, event, router, policyPath, signal,
212
269
  return preserve('catalog_changed', request_id);
213
270
  // The existing narrow catalog/tuple validator is reused. This local flag is an
214
271
  // operator-policy decision, never a claim about complete host-setting evidence.
215
- const candidate = hookOutput({ client, event: snapshot, recommendation, mode: 'apply', compatibilityVerified: true, policy: router.policy });
216
- if (!candidate.hookSpecificOutput || recommendation.status !== 'recommended') {
272
+ if (!profile || observation.recommendation !== 'produced') {
217
273
  const allowed = ['preserved_constraints', 'unsupported_profile', 'invalid_response', 'invalid_choice', 'provider_abstained', 'no_candidates', 'insufficient_context',
218
274
  'provider_needs_context', 'budget_exhausted', 'concurrency_limit', 'ledger_locked', 'request_conflict', 'outcome_unknown', 'ledger_error', 'timeout', 'refused',
219
275
  'truncated', 'invalid_json', 'unauthorized', 'rate_limited', 'network', 'provider_error', 'sensitive_input', 'invalid_input'];
220
276
  return preserve(allowed.includes(recommendation.reason) ? recommendation.reason : 'recommendation_unavailable', request_id);
221
277
  }
222
- const profile = router.policy.profiles.find(profile => profile.id === recommendation.profile_id && profile.client === call.client);
278
+ const blocked = applicationConstraint(call);
279
+ if (blocked) {
280
+ const kept = preserve(blocked, request_id);
281
+ const next = blocked === 'effort_argument_unsupported' ? 'The caller must review the native reasoning_effort argument spelling; Aptly never rewrites an explicit choice.' : 'Inherited model/effort updates are not verified for this host. Verify the host version and native contract before enabling them; task arguments cannot certify support. Aptly never changes history automatically.';
282
+ kept.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: `Aptly recommends ${profile.id}, but application is blocked (${blocked}). Original history and arguments are preserved; no child execution is observed. ${next}` } };
283
+ return kept;
284
+ }
285
+ const candidate = hookOutput({ client, event: snapshot, recommendation, mode: 'apply', compatibilityVerified: true, policy: router.policy, fillUnspecified: true });
286
+ if (!candidate.hookSpecificOutput)
287
+ return preserve('application_unsupported', request_id);
223
288
  if (loaded.policy.mode === 'advisory')
224
289
  return { output: { hookSpecificOutput: { hookEventName: 'PreToolUse',
225
290
  additionalContext: `Aptly suggests ${profile.model}${profile.reasoning_effort ? ` with ${profile.reasoning_effort} reasoning effort` : ''} for this task (${profile.id}). This is task advice; the host retains execution and permission decisions.` } },
226
- observation: { status: 'advisory', reason: 'operator_policy_advice', profile_id: profile.id, request_id } };
227
- return { output: candidate, observation: { status: 'applied', reason: 'operator_policy_defaults', profile_id: profile.id, request_id } };
291
+ observation: { ...observation, status: 'advisory', application: 'not_attempted', reason: 'operator_policy_advice', profile_id: profile.id, request_id } };
292
+ return { output: candidate, observation: { ...observation, status: 'arguments_updated', application: 'arguments_updated', reason: 'operator_policy_defaults', profile_id: profile.id, request_id } };
228
293
  }
229
294
  catch {
295
+ if (observation.classification === 'evaluating')
296
+ observation.classification = 'unknown';
230
297
  return preserve('automatic_hook_unavailable');
231
298
  }
232
299
  }
@@ -1,4 +1,4 @@
1
- import type { UnknownRecord, RoutingInput, RoutingPolicy } from './types.ts';
1
+ import type { UnknownRecord, RoutingInput, Profile, RoutingPolicy } from './types.ts';
2
2
  export interface HookOptions {
3
3
  client?: unknown;
4
4
  event?: unknown;
@@ -6,6 +6,7 @@ export interface HookOptions {
6
6
  mode?: string;
7
7
  compatibilityVerified?: boolean;
8
8
  policy?: RoutingPolicy;
9
+ fillUnspecified?: boolean;
9
10
  }
10
11
  export interface HookOutput {
11
12
  hookSpecificOutput?: {
@@ -17,4 +18,8 @@ export interface HookOutput {
17
18
  /** Extract only a task label and safe structural features, never prompt/message/transcript. */
18
19
  export declare function hookInput({ client, event, policy }?: HookOptions): RoutingInput | null;
19
20
  /** Native Hook JSON, defaulting to no permission or argument intervention. */
20
- export declare function hookOutput({ client, event, recommendation, mode, compatibilityVerified, policy }?: HookOptions): HookOutput;
21
+ export declare function hookOutput({ client, event, recommendation, mode, compatibilityVerified, policy, fillUnspecified }?: HookOptions): HookOutput;
22
+ export declare const effortKeys: readonly ['effort', 'reasoning_effort', 'model_reasoning_effort'];
23
+ /** Presence is a pin, not evidence of its source. Never replace a specified half. */
24
+ export declare function profilePreservesChoices(input: UnknownRecord, profile: Profile): boolean;
25
+ export declare function validatedHookProfile(client: unknown, recommendation: unknown, policy: RoutingPolicy): Profile | undefined;
package/dist/src/hook.js CHANGED
@@ -61,26 +61,19 @@ export function hookInput({ client, event, policy = defaultPolicy } = {}) {
61
61
  };
62
62
  }
63
63
  /** Native Hook JSON, defaulting to no permission or argument intervention. */
64
- export function hookOutput({ client, event, recommendation, mode = 'shadow', compatibilityVerified = false, policy = defaultPolicy } = {}) {
64
+ export function hookOutput({ client, event, recommendation, mode = 'shadow', compatibilityVerified = false, policy = defaultPolicy, fillUnspecified = false } = {}) {
65
65
  if (mode !== 'apply' || compatibilityVerified !== true)
66
66
  return {};
67
67
  const found = target(client, event);
68
68
  if (!found || !object(recommendation) || recommendation.status !== 'recommended')
69
69
  return {};
70
70
  const pins = constraints(found.client, found.input);
71
- if (['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits'].some(k => pins[k]))
71
+ if (pins.role_pinned || pins.fork_inherits || (!fillUnspecified && (pins.model_pinned || pins.effort_pinned)))
72
72
  return {};
73
- const profile = policy.profiles.find(p => p.client === client && p.id === recommendation.profile_id);
74
- if (!profile || !isSupportedProfile(profile) || recommendation.policy_version !== policy.version ||
75
- recommendation.catalog_version !== policy.catalog_version)
73
+ const profile = validatedHookProfile(client, recommendation, policy);
74
+ if (!profile)
76
75
  return {};
77
- // Select executable values solely from the trusted catalog. Reject conflicting
78
- // copies instead of letting a provider supply arbitrary model/effort strings.
79
- if (own(recommendation, 'model') || own(recommendation, 'reasoning_effort') || own(recommendation, 'effort'))
80
- return {};
81
- const suppliedProfile = recommendation.profile;
82
- if (!object(suppliedProfile) || Object.keys(suppliedProfile).length !== Object.keys(profile).length ||
83
- Object.entries(profile).some(([key, value]) => suppliedProfile[key] !== value))
76
+ if (fillUnspecified && !profilePreservesChoices(found.input, profile))
84
77
  return {};
85
78
  let updatedInput;
86
79
  try {
@@ -89,8 +82,9 @@ export function hookOutput({ client, event, recommendation, mode = 'shadow', com
89
82
  catch {
90
83
  return {};
91
84
  }
92
- updatedInput.model = profile.model;
93
- if (client === 'codex')
85
+ if (!own(found.input, 'model'))
86
+ updatedInput.model = profile.model;
87
+ if (client === 'codex' && !effortKeys.some(key => own(found.input, key)))
94
88
  updatedInput.reasoning_effort = profile.reasoning_effort;
95
89
  return { hookSpecificOutput: {
96
90
  hookEventName: 'PreToolUse',
@@ -100,3 +94,27 @@ export function hookOutput({ client, event, recommendation, mode = 'shadow', com
100
94
  updatedInput,
101
95
  } };
102
96
  }
97
+ export const effortKeys = ['effort', 'reasoning_effort', 'model_reasoning_effort'];
98
+ /** Presence is a pin, not evidence of its source. Never replace a specified half. */
99
+ export function profilePreservesChoices(input, profile) {
100
+ if (own(input, 'model') && input.model !== profile.model)
101
+ return false;
102
+ return effortKeys.every(key => !own(input, key) || (typeof input[key] === 'string' && profile.reasoning_effort === input[key]));
103
+ }
104
+ export function validatedHookProfile(client, recommendation, policy) {
105
+ if (!object(recommendation) || recommendation.status !== 'recommended')
106
+ return undefined;
107
+ const profile = policy.profiles.find(p => p.client === client && p.id === recommendation.profile_id);
108
+ if (!profile || !isSupportedProfile(profile) || recommendation.policy_version !== policy.version ||
109
+ recommendation.catalog_version !== policy.catalog_version)
110
+ return undefined;
111
+ // Select executable values solely from the trusted catalog. Reject conflicting
112
+ // copies instead of letting a provider supply arbitrary model/effort strings.
113
+ if (own(recommendation, 'model') || own(recommendation, 'reasoning_effort') || own(recommendation, 'effort'))
114
+ return undefined;
115
+ const suppliedProfile = recommendation.profile;
116
+ if (!object(suppliedProfile) || Object.keys(suppliedProfile).length !== Object.keys(profile).length ||
117
+ Object.entries(profile).some(([key, value]) => suppliedProfile[key] !== value))
118
+ return undefined;
119
+ return profile;
120
+ }
@@ -0,0 +1,34 @@
1
+ import type { AutomaticHookObservation } from './automatic-hook.ts';
2
+ /** Process-local, bounded diagnostics; absence is never proof that a host bypassed MCP. */
3
+ export declare class RoutingObservations {
4
+ private entries;
5
+ private now;
6
+ constructor(now?: () => number);
7
+ private prune;
8
+ record(value: AutomaticHookObservation): void;
9
+ begin(client: unknown, event: unknown): void;
10
+ lookup(client: unknown, event: unknown): {
11
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending';
12
+ preflight: 'observed';
13
+ correlation_id?: string;
14
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
15
+ recommendation: 'not_produced' | 'produced';
16
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
17
+ execution: 'not_observed';
18
+ constraint_provenance: 'unknown';
19
+ reason: string;
20
+ profile_id?: string;
21
+ request_id?: string;
22
+ scope: string;
23
+ retention_seconds: number;
24
+ capacity: number;
25
+ } | {
26
+ scope: string;
27
+ retention_seconds: number;
28
+ capacity: number;
29
+ preflight: string;
30
+ reason: string;
31
+ correlation_id?: string | undefined;
32
+ execution: string;
33
+ };
34
+ }
@@ -0,0 +1,30 @@
1
+ import { automaticCallId, initialHookObservation } from './automatic-hook.js';
2
+ /** Process-local, bounded diagnostics; absence is never proof that a host bypassed MCP. */
3
+ export class RoutingObservations {
4
+ entries = new Map();
5
+ now;
6
+ constructor(now = Date.now) { this.now = now; }
7
+ prune() {
8
+ for (const [id, entry] of this.entries)
9
+ if (this.now() - entry.at >= 600_000)
10
+ this.entries.delete(id);
11
+ }
12
+ record(value) {
13
+ this.prune();
14
+ if (!value.correlation_id)
15
+ return;
16
+ this.entries.delete(value.correlation_id);
17
+ this.entries.set(value.correlation_id, { at: this.now(), value: structuredClone(value) });
18
+ while (this.entries.size > 128)
19
+ this.entries.delete(this.entries.keys().next().value);
20
+ }
21
+ begin(client, event) { this.record(initialHookObservation(client, event)); }
22
+ lookup(client, event) {
23
+ this.prune();
24
+ const correlation_id = automaticCallId(client, event);
25
+ const found = correlation_id ? this.entries.get(correlation_id) : undefined;
26
+ return { scope: 'this_process_recent_calls', retention_seconds: 600, capacity: 128,
27
+ ...(found ? structuredClone(found.value) : { preflight: 'not_observed', reason: correlation_id ? 'no_matching_observation' : 'invalid_event',
28
+ ...(correlation_id ? { correlation_id } : {}), execution: 'not_observed' }) };
29
+ }
30
+ }