aptly 0.1.3 → 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
@@ -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
@@ -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
@@ -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
@@ -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
 
@@ -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
+ }
@@ -7,14 +7,17 @@ import { VERSION } from './version.js';
7
7
  import { hookInput, hookOutput } from './hook.js';
8
8
  import { resolveProvenance } from './provenance.js';
9
9
  import { loadConfiguration, loadHostContext } from './config.js';
10
- import { automaticHook, loadAutomaticHookPolicy } from './automatic-hook.js';
10
+ import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
+ import { SpawnContexts } from './spawn-context.js';
12
+ import { RoutingObservations } from './routing-observations.js';
11
13
  const taskSchema = z.object({ summary: z.string().min(1).max(4000), operation: z.enum(['read_only', 'write', 'review', 'analysis']), context_sufficient: z.boolean() }).strict();
12
14
  const constraintsSchema = z.object({ model_pinned: z.boolean().optional(), effort_pinned: z.boolean().optional(), role_pinned: z.boolean().optional(), fork_inherits: z.boolean().optional(), provenance_verified: z.boolean().optional() }).strict();
13
15
  const hookSchema = { client: z.enum(['codex', 'claude']), event: z.record(z.string(), z.unknown()) };
14
16
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
15
17
  export function createServer({ env = process.env } = {}) {
16
18
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
17
- let lastAutomaticHook = null;
19
+ const observations = new RoutingObservations();
20
+ const contexts = new SpawnContexts();
18
21
  const server = new McpServer({ name: 'aptly', version: VERSION });
19
22
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
20
23
  const evidence = (client, event) => {
@@ -29,8 +32,28 @@ export function createServer({ env = process.env } = {}) {
29
32
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
30
33
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
31
34
  credential_status: credentialStatus,
32
- automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, last_result: lastAutomaticHook },
35
+ automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported' },
33
36
  }));
37
+ server.registerTool('get_spawn_routing_observation', {
38
+ description: 'Look up one exact spawn event in this MCP process (128 calls, 10 minutes). No provider call. Missing records do not prove bypass; argument updates never prove native child execution.',
39
+ annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
40
+ }, async ({ client, event }) => content(observations.lookup(client, event)));
41
+ server.registerTool('prepare_spawn_context', {
42
+ description: 'Register a bounded untrusted description for an exact upcoming spawn event in this MCP process for five minutes. Requires enabled automatic policy. No provider call, file fetching, execution or permissions. The caller must know the real session/call IDs and exact original invocation; invented IDs do not connect to native Hooks.',
43
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
44
+ inputSchema: { ...hookSchema, description: z.string().max(4000) }
45
+ }, async ({ client, event, description }, extra) => {
46
+ const policy = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
47
+ if (!policy.policy?.enabled)
48
+ return content({ status: 'rejected', reason: policy.reason });
49
+ if (extra.signal.aborted)
50
+ return content({ status: 'rejected', reason: 'context_cancelled' });
51
+ return content(contexts.register(client, event, description, router.policy.max_summary_bytes));
52
+ });
53
+ server.registerTool('cancel_spawn_context', {
54
+ description: 'Revoke one exact registered spawn context in this process. Does not cancel native execution or undo a provider request.',
55
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, inputSchema: hookSchema
56
+ }, async ({ client, event }) => content(contexts.cancel(client, event)));
34
57
  server.registerTool('recommend_agent', {
35
58
  description: 'Recommend an allowlisted profile for a supplied task only; never inspects host settings, spawns, or authorizes an agent. Optional constraints describe caller-declared choices to preserve; omitted flags are not claims about current host settings. Decisions mode may incur a bounded classification request.', annotations,
36
59
  inputSchema: { request_id: z.string().min(1).max(96), client: z.enum(['codex', 'claude']), task: taskSchema, eligible_profile_ids: z.array(z.string()).min(1).max(20).optional(), constraints: constraintsSchema.optional() }
@@ -42,17 +65,20 @@ export function createServer({ env = process.env } = {}) {
42
65
  return content({ ...precedence, evidence_status: loaded.reason, configuration_status: config.error ?? 'ok', application: 'advisory_only' });
43
66
  });
44
67
  server.registerTool('route_spawn_hook', {
45
- description: 'Native PreToolUse Hook. An installed operator policy can select unpinned fresh-agent defaults through Decisions; otherwise the legacy evidence-gated path remains shadow by default. Explicit choices, role/fork/resume and failures preserve the call. Optional task never supplies policy.', annotations,
68
+ description: 'Native PreToolUse preflight for supported spawns. Installed policy evaluates unspecified defaults, including inherited calls; application preserves explicit choices, roles, resume and history. Incompatible history yields advice without rewriting. The host executes; optional task never supplies policy.', annotations,
46
69
  inputSchema: { ...hookSchema, task: taskSchema.optional() }
47
70
  }, async ({ client, event, task }, extra) => {
71
+ observations.begin(client, event);
48
72
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
49
- const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal });
50
- lastAutomaticHook = result.observation;
73
+ const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal, context: () => contexts.lookup(client, event), onObservation: value => observations.record(value) });
74
+ observations.record(result.observation);
51
75
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
52
76
  }
53
77
  const input = hookInput({ client, event, policy: router.policy });
54
- if (!input)
78
+ if (!input) {
79
+ observations.record({ ...initialHookObservation(client, event), status: 'preserved', reason: 'invalid_event' });
55
80
  return { content: [{ type: 'text', text: '{}' }] };
81
+ }
56
82
  const before = evidence(client, event);
57
83
  input.constraints = before.precedence.constraints;
58
84
  if (task)
@@ -65,6 +91,12 @@ export function createServer({ env = process.env } = {}) {
65
91
  before.config.context_path === after.config.context_path && before.precedence.status === 'eligible' && after.precedence.status === 'eligible' &&
66
92
  before.loaded.fingerprint === after.loaded.fingerprint && JSON.stringify(before.loaded.context) === JSON.stringify(after.loaded.context);
67
93
  const output = hookOutput({ client, event, recommendation, mode: apply ? 'apply' : 'shadow', compatibilityVerified: apply, policy: router.policy });
94
+ observations.record({ ...initialHookObservation(client, event), status: output.hookSpecificOutput ? 'arguments_updated' : 'preserved',
95
+ reason: output.hookSpecificOutput ? 'legacy_arguments_updated' : recommendation.status === 'recommended' ? 'legacy_application_blocked' : recommendation.reason,
96
+ classification: recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
97
+ recommendation: recommendation.status === 'recommended' ? 'produced' : 'not_produced',
98
+ application: output.hookSpecificOutput ? 'arguments_updated' : recommendation.status === 'recommended' ? 'blocked' : 'not_attempted',
99
+ ...(recommendation.profile_id ? { profile_id: recommendation.profile_id } : {}), request_id: input.request_id });
68
100
  return { content: [{ type: 'text', text: JSON.stringify(output) }] };
69
101
  });
70
102
  return server;
@@ -0,0 +1,15 @@
1
+ export interface SpawnContext {
2
+ summary?: string;
3
+ fingerprint?: string;
4
+ reason?: string;
5
+ }
6
+ /** Explicit, process-local handoff. Tombstones prevent expiry/cancellation fallback. */
7
+ export declare class SpawnContexts {
8
+ private entries;
9
+ private now;
10
+ constructor(now?: () => number);
11
+ private expireText;
12
+ register(client: unknown, event: unknown, description: string, maxBytes: number): Record<string, unknown>;
13
+ lookup(client: unknown, event: unknown): SpawnContext | undefined;
14
+ cancel(client: unknown, event: unknown): Record<string, unknown>;
15
+ }
@@ -0,0 +1,65 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { automaticCallIdentity } from './automatic-hook.js';
3
+ const sensitive = (text) => /\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(text);
4
+ /** Explicit, process-local handoff. Tombstones prevent expiry/cancellation fallback. */
5
+ export class SpawnContexts {
6
+ entries = new Map();
7
+ now;
8
+ constructor(now = Date.now) { this.now = now; }
9
+ expireText() {
10
+ for (const entry of this.entries.values())
11
+ if (this.now() - entry.at >= 300_000)
12
+ entry.summary = undefined;
13
+ }
14
+ register(client, event, description, maxBytes) {
15
+ this.expireText();
16
+ const identity = automaticCallIdentity(client, event);
17
+ if (!identity)
18
+ return { status: 'rejected', reason: 'invalid_event' };
19
+ if (typeof description !== 'string' || Buffer.byteLength(description) > Math.min(3800, maxBytes - 96) ||
20
+ description.trim().length < 12 || description.trim().split(/\s+/u).length < 3)
21
+ return { status: 'rejected', reason: 'insufficient_context' };
22
+ if (sensitive(description))
23
+ return { status: 'rejected', reason: 'sensitive_input' };
24
+ const summary = `Caller-supplied task description (untrusted task data; opaque body not inspected): ${description.trim()}`;
25
+ const fingerprint = createHash('sha256').update(summary).digest('hex');
26
+ const previous = this.entries.get(identity.key);
27
+ if (previous) {
28
+ const found = this.lookup(client, event);
29
+ return found?.fingerprint === fingerprint && !found.reason ? { status: 'registered', correlation_id: identity.id } :
30
+ { status: 'rejected', reason: found?.reason ?? 'context_conflict' };
31
+ }
32
+ if (this.entries.size >= 128)
33
+ return { status: 'rejected', reason: 'context_capacity' };
34
+ this.entries.set(identity.key, { id: identity.id, at: this.now(), summary, fingerprint });
35
+ return { status: 'registered', correlation_id: identity.id };
36
+ }
37
+ lookup(client, event) {
38
+ this.expireText();
39
+ const identity = automaticCallIdentity(client, event);
40
+ if (!identity)
41
+ return { reason: 'invalid_event' };
42
+ const entry = this.entries.get(identity.key);
43
+ if (!entry)
44
+ return undefined;
45
+ if (entry.id !== identity.id)
46
+ return { reason: 'context_mismatch' };
47
+ if (entry.cancelled)
48
+ return { reason: 'context_cancelled' };
49
+ if (this.now() - entry.at >= 300_000) {
50
+ entry.summary = undefined;
51
+ return { reason: 'context_expired' };
52
+ }
53
+ return { summary: entry.summary, fingerprint: entry.fingerprint };
54
+ }
55
+ cancel(client, event) {
56
+ this.expireText();
57
+ const identity = automaticCallIdentity(client, event);
58
+ const entry = identity && this.entries.get(identity.key);
59
+ if (!entry || entry.id !== identity?.id)
60
+ return { status: 'rejected', reason: 'context_not_found' };
61
+ entry.cancelled = true;
62
+ entry.summary = undefined;
63
+ return { status: 'cancelled' };
64
+ }
65
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.3";
1
+ export declare const VERSION = "0.1.4";
@@ -1 +1 @@
1
- export const VERSION = '0.1.3';
1
+ export const VERSION = '0.1.4';
@@ -0,0 +1,126 @@
1
+ # Explicit spawn context handoff (Aptly 0.1.4)
2
+
3
+ Available from Aptly 0.1.4, following the pre-spawn routing changes in #60.
4
+ It does not decode opaque messages, inspect conversations or modify host
5
+ internals. It provides an explicit caller protocol, not an automatic description
6
+ producer for the shipped Hook templates.
7
+
8
+ ## Supported caller contract
9
+
10
+ A caller/integration that knows the **real upcoming** client, session ID, native
11
+ call ID and exact original invocation can call these tools on the same MCP
12
+ server process, in order:
13
+
14
+ 1. `prepare_spawn_context({client, event, description})`: register a short
15
+ description before the installed PreToolUse Hook runs. Check for
16
+ `status: "registered"`. Registration makes no provider request.
17
+ 2. The existing Hook calls `route_spawn_hook({client, event})` with that exact
18
+ event. It can use the registered description instead of the label/excerpt.
19
+ 3. `get_spawn_routing_observation({client, event})` reports the result separately
20
+ from native application/execution. Use `cancel_spawn_context({client, event})`
21
+ to revoke the association if the intended spawn is abandoned.
22
+
23
+ Do not manually route and then invoke an unrelated native call: an MCP response
24
+ does not prove that a host Hook intercepted or updated it. The caller description
25
+ is untrusted task data, not permissions, policy, host capability or verified user
26
+ intent. Explicit pins, roles, resume and inherited history remain protected.
27
+
28
+ The shipped Hook templates do not produce descriptions or preassign native call
29
+ IDs. If an integration cannot obtain the exact event before preflight, or connects
30
+ to a different MCP process, this handoff cannot be used. In particular, a parent
31
+ agent cannot invent IDs or add unsupported fields to a native spawn to make this
32
+ work. Such paths retain the existing label/excerpt behavior. No automatic
33
+ integration with the original Mac host is claimed.
34
+
35
+ ## What to describe and what is shared
36
+
37
+ Use purpose, bounded scope, expected output, constraints and relevant complexity.
38
+ For example:
39
+
40
+ > Inspect three synthetic merged branches and their worktrees. Return a short
41
+ > table proposing which could be cleaned up. Do not delete files or run commands.
42
+ > No repository contents are needed.
43
+
44
+ Only this description, prefixed as caller-supplied untrusted task data, is sent as
45
+ task text. The existing client/catalog/provider contract is also sent. Neither
46
+ the opaque body, original label, history, event metadata, files nor raw errors are
47
+ added. References can supplement the description; URLs are not fetched and do
48
+ not substitute for describing the task.
49
+
50
+ Descriptions are at most `min(3800, max_summary_bytes - 96)` UTF-8 bytes, with a
51
+ small minimum length/word check. The prefixed summary must also satisfy
52
+ `min(4000, max_summary_bytes)`. Known key/Bearer patterns are rejected; this is
53
+ not complete secret detection or anonymization. Review text before registration.
54
+ An enabled automatic policy is required; `enabled: false` blocks registration
55
+ and transmission even if an association already exists.
56
+
57
+ ## Association, expiry and costs
58
+
59
+ The process keeps at most 128 immutable associations. Five-minute expiry starts
60
+ at first registration; a duplicate does not extend it. Changed payloads for the
61
+ same client/session/call are rejected, not rebound. Cancellation and expiry
62
+ leave tombstones until process exit; capacity rejects new registrations rather
63
+ than evicting a binding and silently falling back. Expired text is discarded
64
+ when the store is accessed; nothing is enumerated or written to disk as text.
65
+ A restart loses the handoff. The persistent paid-call binding still prevents a
66
+ context-free request from replacing an already evaluated context-bound call.
67
+
68
+ A summary hash joins the existing immutable input/policy/catalog binding before
69
+ classification. Duplicate calls use the same request/cache identity and budgets;
70
+ changed or missing context cannot replace it. Context is checked before and
71
+ after the asynchronous provider call. Expiry/cancellation prevents output but
72
+ cannot refund or erase a provider request already sent. Revocation does not
73
+ cancel native execution; the host controls execution.
74
+
75
+ There is no richer-summary retry mechanism in this change. Register before the
76
+ first evaluation. If a label-only or description-bound evaluation already
77
+ started, adding/changing the description fails closed (`call_conflict`);
78
+ unknown paid outcomes remain unknown. Do not change IDs to bypass this guard.
79
+ A future deliberate re-evaluation workflow needs its own explicit association
80
+ and accounting design.
81
+
82
+ ## Outcomes and evidence
83
+
84
+ - `insufficient_context`: local description/size/context checks failed.
85
+ - `provider_needs_context`: a valid provider abstention; its rationale is not
86
+ inferred, and useful-looking text does not guarantee a recommendation.
87
+ - `inherited_context_application_unverified`: advice can be available while
88
+ the native model/history update remains unverified and blocked.
89
+
90
+ Automated tests use synthetic opaque strings, injected providers, mocked
91
+ Decisions HTTP and in-memory MCP transport. They verify shared summaries,
92
+ identity, cancellation, bounds and cache/unknown protections. The separate
93
+ native observation below does not turn those fixtures into native evidence.
94
+
95
+ ### Bounded native protocol verification — 2026-11-06
96
+
97
+ A macOS Codex CLI 0.167.0 test used product commit
98
+ `efae8211f6d92b9a9619886c80792d4e1b737d4d`. The installed Hook was enabled and
99
+ trusted without changing its trust settings. A test-only MCP transport adapter
100
+ captured the real host event, registered the description on the same product
101
+ server, and then forwarded the original `route_spawn_hook` request. It did not
102
+ invent IDs, decode the opaque body, alter Hook responses or patch host code.
103
+
104
+ The safe synthetic description requested extraction of a nonsecret marker
105
+ from earlier conversation history and output of `[1, 2, 3]`, with no tools,
106
+ files, network access, settings changes or real worktree deletion. An HTTP
107
+ boundary recorder confirmed exactly one forwarded Decisions request whose task
108
+ text was the labelled description, with no opaque body or native event fields.
109
+ Registration and observation correlation matched the actual invocation.
110
+
111
+ The provider selected `codex-simple` (`gpt-6-luna` / `max`). Application remained
112
+ blocked as `inherited_context_application_unverified` for `fork_turns: "all"`.
113
+ The native child's final context remained `gpt-6.1-sol` / `low`, matching the
114
+ parent. Parent linkage, exact copying of the marker-bearing parent user payload,
115
+ and the child's final marker/list response were independently checked.
116
+
117
+ This is one protocol and payload verification, not a provider-quality benchmark,
118
+ a causal comparison with label-only advice, or successful application of the
119
+ recommended model. The test used two parent turns and one child; temporary
120
+ files were removed and persistent host configuration was unchanged.
121
+
122
+ This validates a caller that can capture the exact event before product
123
+ preflight. The adapter does not ship an automatic description producer, and
124
+ ordinary parent agents still cannot invent the required IDs. PR #60's separate
125
+ history/model application acceptance and merge order must be resolved before
126
+ merging this dependent change. No richer-summary retry workflow is enabled.
package/docs/guide/en.md CHANGED
@@ -203,16 +203,17 @@ aptly remove --client all
203
203
 
204
204
  ## Automatic Hook
205
205
 
206
- Connected, eligible calls automatically pass through `route_spawn_hook` → Decisions. The `defaults` policy lets an operator authorize Aptly's choice to take precedence over host defaults within this scope. It is not a claim that all host configuration sources have been observed.
206
+ **The following preflight, recommendation and observation behavior requires Aptly 0.1.4 or later.** The installed `PreToolUse` matcher routes supported Codex `spawn_agent` / `collaborationspawn_agent` / `Agent` and Claude Code `Agent` calls to local `route_spawn_hook` before native execution. The host must load and trust this Hook and connect its MCP server. Aptly cannot enforce interception in an unconfigured or unsupported host, or when MCP is unavailable; native execution remains the host's responsibility.
207
207
 
208
- | Host | Calls eligible for automatic selection |
209
- |---|---|
210
- | Codex | Fresh, general-purpose calls with no explicit model, effort, fixed role, or resume target, and `fork_turns: "none"` |
211
- | Claude Code | Calls with `subagent_type: "general-purpose"` and no explicit model, effort, fixed role, resume target, or inherited history |
208
+ Local preflight checks explicit fields, roles/resume, policy, cache and budget. A new paid Decisions request is not required for every spawn. Model-only or effort-only Codex selections restrict candidates to matching allowlisted tuples; only the unspecified field can be filled. Both specified fields, unsupported values, fixed roles and resumed identities are preserved without classification. Input fields do not establish whether a choice came from the user or a host default.
209
+
210
+ Unspecified model/effort with `fork_turns: "all"` or omitted fork now reaches recommendation. It does **not** authorize history changes: Codex model/effort application still requires explicit `fork_turns: "none"`. Otherwise the Hook reports `inherited_context_application_unverified` and preserves the original arguments. Other history fields produce `history_semantics_unverified`; Claude application remains limited to general-purpose calls without history constraints. A recommendation may therefore be produced without being applied.
211
+
212
+ For opaque Codex messages, a concrete short task name such as `cleanup_merged_worktrees` can supply label-only advice. The short-name allowlist covers cleanup/remove/prune + merged + worktrees/branches, and review/fix/test + failing/broken/flaky + tests/builds; other names retain the descriptive six-word check. The body is never decoded or sent. This does not establish missing task details or permission to clean up. Inherited application is unverified for the target host, not universally impossible; public source support alone cannot certify the installed runtime.
212
213
 
213
- Explicit choices, roles, fork and resume settings, approvals, sandboxing, and MCP permissions are preserved. Fixture results never automatically change the default model. Insufficient context, unsupported responses, cancellation, or a changed call preserve the original arguments. Each call is bound to its input, policy, and catalog, and checked again after an asynchronous response.
214
+ For genuinely independent work, the caller can intentionally choose a fresh child and provide sufficient standalone task context. Aptly never changes `all` to `none`, removes history or rewrites a specified model/effort. [Synthetic inherited and fresh examples](../../examples/spawn-preflight.codex.json) show the distinct requests; they are not automatic retries. Never retry an uncertain paid call with a new ID.
214
215
 
215
- The CLI without additional configuration, and existing manual configurations, default to fixture / shadow. The older host-evidence-based path without an automatic policy is distinct from the installed default-selection policy. Host-internal patches remain on hold and are not a prerequisite for direct recommendations.
216
+ `defaults` enables compatible argument updates; `advisory` supplies advice only. Inherited calls and partially specified calls may now share the same bounded task excerpt with Decisions even when application is blocked; history is not a privacy opt-out. Disabled policy, insufficient context, budget limits, failure and cancellation preserve execution constraints. Input, policy and catalog bindings, duplicate suppression and unknown-outcome protection remain in place. Fixture recommendations never rewrite native defaults. The strict evidence-based path without an automatic policy remains separate; host-internal patches stay paused.
216
217
 
217
218
  | MCP tool | Purpose |
218
219
  |---|---|
@@ -220,6 +221,9 @@ The CLI without additional configuration, and existing manual configurations, de
220
221
  | `recommend_agent` | Returns a direct recommendation for a task summary |
221
222
  | `get_routing_precedence` | Explains preserved choices and unverified configuration sources for a call |
222
223
  | `route_spawn_hook` | Selects defaults for eligible calls or passes advice only, according to the installed policy |
224
+ | `get_spawn_routing_observation` | Looks up one exact Hook invocation; never proves native execution |
225
+ | `prepare_spawn_context` | Registers a bounded description for one exact upcoming invocation |
226
+ | `cancel_spawn_context` | Revokes the description association, not native execution or a request already sent |
223
227
 
224
228
  ### Outbound data and disabling automatic sharing
225
229
 
@@ -235,6 +239,12 @@ For control over the shared summary, disable automatic sharing and write only th
235
239
 
236
240
  The ledger and Hook bindings store request metadata, hashes, and cached results, not task excerpts. Aptly diagnostics also exclude raw task text. The local Hook's `updatedInput` retains the original task so the host can continue execution. Aptly does not control the host's own transcript or log retention.
237
241
 
242
+ ### Explicit description for opaque spawns (0.1.4+)
243
+
244
+ An integration that knows the real upcoming session/call IDs and exact original event can call `prepare_spawn_context({client, event, description})` on the same MCP process before the Hook. Describe purpose, scope, expected output, constraints and complexity; URLs alone do not fetch content. Only the bounded description and fixed prefix replace the task excerpt, not history, files or the opaque body. `cancel_spawn_context({client, event})` revokes it. Registration needs enabled automatic policy; `enabled: false` prevents sharing. Known-secret filters are incomplete.
245
+
246
+ Associations last five minutes, are immutable, and are limited to 128 per process. Changed, expired or cancelled associations block routing; an already evaluated call cannot acquire a richer-summary retry or new paid identity. A caller unable to obtain the actual upcoming event cannot use this handoff; shipped Hooks do not create descriptions or call IDs. Local `insufficient_context`, provider `provider_needs_context`, and native `inherited_context_application_unverified` are distinct. The [handoff contract](../SPAWN_CONTEXT.md) records a bounded native description-handoff check. It does not establish automatic description production or execution of the recommended model.
247
+
238
248
  ## Direct recommendations
239
249
 
240
250
  The `recommend_agent` MCP tool and CLI `recommend` accept a task summary and recommend a profile. They do not spawn subagents. Pass this JSON as MCP tool arguments, or save it to a file and provide it to the CLI through standard input.
@@ -310,9 +320,9 @@ Refresh only reads the fixed [Claude model documentation](https://code.claude.co
310
320
 
311
321
  ## Providing context
312
322
 
313
- When Codex passes a subagent `message` to the Hook as ciphertext, Aptly does not read or decrypt its body. It uses only a sufficiently descriptive plaintext `task_name` as a summary. Describe the task and its scope, for example `sort_supplied_numbers_3_1_2_ascending_without_tools`. Short or ambiguous names preserve the original model. Claude Code calls and calls that expose a plaintext body use a summary of the provided body.
323
+ When Codex passes a subagent `message` to the Hook as ciphertext, Aptly does not read or decrypt its body. It uses only a sufficiently descriptive plaintext `task_name` as a summary. Describe the task and its scope, for example `sort_supplied_numbers_3_1_2_ascending_without_tools`. Unsupported or ambiguous task names preserve the original model. Claude Code calls and calls that expose a plaintext body use a summary of the provided body.
314
324
 
315
- Use `automatic_hook.last_result` in `get_routing_capabilities` to check the last application or preservation reason for that MCP process. `null` means it has not yet processed an automatic Hook call. Task bodies and personal configuration values are not returned.
325
+ Use `get_spawn_routing_observation` with the same `client` and exact original Hook `event` to query one invocation. It returns a redacted correlation ID, preflight, classification/cache outcome, recommendation, argument-update or blocked application, and `execution: not_observed`. `arguments_updated` only describes emitted Hook arguments, never an observed child model. Records are limited to 128 calls and 10 minutes in this MCP process; `not_observed` can also mean another process, restart, expiry, eviction or mismatched input. It does not prove global Hook bypass. The process-wide `automatic_hook.last_result` is removed. No raw task, path, session ID or credential is returned.
316
326
 
317
327
  For direct recommendations, you can include repository and file URLs alongside a summary of the scope, size, and constraints derived from reading the documents. Sending a URL string differs from providing document contents. Aptly's classification request code does not fetch repository URLs or retrieve their contents. The caller performs any required retrieval and summarization.
318
328
 
package/docs/guide/ja.md CHANGED
@@ -203,16 +203,17 @@ aptly remove --client all
203
203
 
204
204
  ## 自動 Hook
205
205
 
206
- 接続済みの対象呼び出しは、`route_spawn_hook` → Decisions を自動で経由します。`defaults` は、対象範囲でホストのデフォルトモデルより Aptly の選択を優先することを、運用者が許可するポリシーです。このポリシーは、ホストのすべての設定元を確認したことを示すものではありません。
206
+ **以下の事前確認・推薦・観測の動作は Aptly 0.1.4 以降で利用できます。** インストールした `PreToolUse` matcher は Codex の `spawn_agent` / `collaborationspawn_agent` / `Agent` と Claude Code の `Agent` を、native 実行前にローカルの `route_spawn_hook` へ渡します。ホストによる Hook の読み込み・信頼承認と MCP 接続が必要です。未設定・未対応のホストや MCP 接続失敗時まで Aptly が介入を強制することはできず、実行はホストが担当します。
207
207
 
208
- | ホスト | 自動選択の対象 |
209
- |---|---|
210
- | Codex | モデル・effort・固定ロール・resume の指定がなく、`fork_turns: "none"` の新しい汎用呼び出し |
211
- | Claude Code | モデル・effort・固定ロール・resume・履歴継承の指定がない、`subagent_type: "general-purpose"` の呼び出し |
208
+ ローカルの事前確認で明示フィールド・ロール・resume・ポリシー・キャッシュ・予算を評価します。呼び出しごとに新しい有料 Decisions 要求が必要なわけではありません。Codex のモデルまたは effort だけが指定された場合は、一致する許可済みの組み合わせに候補を絞り、未指定フィールドだけを補います。両方の指定、未対応値、固定ロール、resume は分類せず保持します。入力だけからユーザー指定かホストのデフォルトかを断定しません。
209
+
210
+ モデル・effort が未指定なら `fork_turns: "all"` や fork の省略も推薦を評価します。ただし**履歴は変更しません**。Codex のモデル・effort 適用には明示的な `fork_turns: "none"` が必要です。それ以外は `inherited_context_application_unverified` として元の引数を保持します。他の履歴フィールドは `history_semantics_unverified` で適用を止め、Claude の適用も履歴制約のない汎用呼び出しに限ります。推薦の生成と適用は別です。
211
+
212
+ Codex の本文が不透明な場合、`cleanup_merged_worktrees` のような具体的な短い作業名だけでも推薦できます。短い名前は cleanup/remove/prune + merged + worktrees/branches、または review/fix/test + failing/broken/flaky + tests/builds の組み合わせに限定し、他は従来の6単語チェックを維持します。本文は復号も送信もしません。詳細条件や削除権限は推測しません。履歴継承時の適用は対象ホストで未検証であり、全バージョンで不可能という意味ではありません。公開ソースだけでは実行環境の対応を確認できません。
212
213
 
213
- 明示的な指定とロール・fork・resume、承認・サンドボックス・MCP 権限は保持します。fixture の結果でデフォルトモデルを自動変更することはありません。コンテキスト不足・未対応の応答・キャンセル・呼び出しの変更がある場合は、元の引数を変更しません。同じ呼び出しの入力・ポリシー・カタログを結び付け、非同期応答後に再確認します。
214
+ 独立した作業の場合だけ、呼び出し側が十分な単独のタスク情報を渡し、新しい子を明示的に選択してください。Aptly は `all` を `none` に変更せず、履歴の削除や明示モデル・effort の上書きもしません。[合成の継承・新規子の例](../../examples/spawn-preflight.codex.json)は別々の要求であり、自動再試行ではありません。結果不明の有料呼び出しを新しい ID で再試行しないでください。
214
215
 
215
- 別途設定せずに実行する CLI と既存の手動設定は、fixture / shadow がデフォルトです。ホスト設定の証拠(host-evidence)に基づく従来の経路は、自動ポリシーがない場合のものです。インストールしたデフォルト値選択ポリシーとは区別してください。ホスト内部のパッチは保留中で、直接推薦の前提条件ではありません。
216
+ `defaults` は互換性のある引数更新を、`advisory` は推薦だけを許可します。継承や一部だけ指定した呼び出しも、適用できなくても制限付きタスク抜粋を Decisions に送信する場合があります。履歴継承は共有の無効化ではありません。ポリシー無効・文脈不足・予算制限・失敗・キャンセルでは実行制約を保持します。入力・ポリシー・カタログの結合、重複防止、結果不明の保護を維持し、fixture の推薦で native のデフォルトを変更しません。自動ポリシーのない strict 証拠経路は別であり、ホスト内部のパッチは引き続き保留です。
216
217
 
217
218
  | MCP ツール | 用途 |
218
219
  |---|---|
@@ -220,6 +221,9 @@ aptly remove --client all
220
221
  | `recommend_agent` | タスク要約から直接推薦を取得します |
221
222
  | `get_routing_precedence` | 呼び出しを保持する根拠と、未確認の設定元を説明します |
222
223
  | `route_spawn_hook` | インストールしたポリシーに応じて、対象呼び出しのデフォルト値を選択するか、推薦だけを伝えます |
224
+ | `get_spawn_routing_observation` | 一致する Hook 呼び出しを照会し、native 実行を証明しません |
225
+ | `prepare_spawn_context` | 正確に一致する予定呼び出しに上限付きの説明を登録します |
226
+ | `cancel_spawn_context` | 説明の対応付けを取り消します。native 実行や送信済みリクエストは取り消しません |
223
227
 
224
228
  ### 外部送信と自動共有の無効化
225
229
 
@@ -235,6 +239,12 @@ Decisions には `client`、`task.summary`、`task.operation`、`task.context_su
235
239
 
236
240
  台帳と Hook バインディングにはリクエストのメタデータ・ハッシュ・キャッシュ結果を保存し、タスクの抜粋は保存しません。Aptly の診断にもタスク原文を含めません。ただし、ローカルの Hook の `updatedInput` は、ホストが実行を続けられるよう元のタスクを保持します。ホスト自身の会話やログの保存は Aptly の制御対象ではありません。
237
241
 
242
+ ### 不透明な呼び出しへの明示的な説明(0.1.4 以降)
243
+
244
+ 実際の予定セッション・呼び出し ID と元のイベントを知る連携は、Hook の前に同じ MCP プロセスで `prepare_spawn_context({client, event, description})` を呼べます。目的・範囲・出力・制約・複雑さを短く記述してください。URL の内容は取得しません。上限付き説明と固定接頭文だけが抜粋を置き換え、履歴・ファイル・不透明な本文は送信しません。`cancel_spawn_context({client, event})` で取り消せます。有効な自動ポリシーが必要で、`enabled: false` は共有を止めます。既知の秘密パターン検査は完全ではありません。
245
+
246
+ 対応付けは5分間有効で変更不可、プロセスごとに最大128件です。入力変更・期限切れ・取消時は分類を止め、評価済みの呼び出しを説明変更で有料再試行しません。実際の予定イベントを取得できない呼び出し元は利用できません。標準 Hook は説明や呼び出し ID を作成しません。ローカルの `insufficient_context`、プロバイダーの `provider_needs_context`、適用時の `inherited_context_application_unverified` は別の結果です。限定的な native 説明受け渡しの検証は[契約](../SPAWN_CONTEXT.md)に記録しています。この検証は、説明の自動生成や推薦モデルの実行を証明するものではありません。
247
+
238
248
  ## 直接推薦
239
249
 
240
250
  `recommend_agent` MCP と CLI の `recommend` は、タスク要約を受け取ってプロファイルを推薦します。子エージェントを直接生成することはありません。以下の JSON を MCP ツールの引数として渡すか、ファイルに保存して CLI の標準入力に渡してください。
@@ -310,9 +320,9 @@ export APTLY_MODEL_INFO_PATH=/absolute/private-aptly-state/model-info.json
310
320
 
311
321
  ## コンテキストの提供
312
322
 
313
- Codex が子エージェントの `message` を暗号文として Hook に渡す環境では、本文を読み取ったり復号したりしません。この場合は、十分に具体的な平文の `task_name` だけを要約として使用します。たとえば `sort_supplied_numbers_3_1_2_ascending_without_tools` のように、タスクの種類と範囲を表します。短い名前や曖昧な名前の場合は、元のモデルを保持します。Claude Code と平文の本文が渡される呼び出しでは、提供された本文の要約を使用します。
323
+ Codex が子エージェントの `message` を暗号文として Hook に渡す環境では、本文を読み取ったり復号したりしません。この場合は、十分に具体的な平文の `task_name` だけを要約として使用します。たとえば `sort_supplied_numbers_3_1_2_ascending_without_tools` のように、タスクの種類と範囲を表します。未対応または曖昧なタスク名の場合は、元のモデルを保持します。Claude Code と平文の本文が渡される呼び出しでは、提供された本文の要約を使用します。
314
324
 
315
- `get_routing_capabilities` の `automatic_hook.last_result` で、その MCP プロセスによる最後の適用・保持の理由を確認できます。`null` は、まだ自動 Hook の処理記録がないことを意味します。タスクの本文や個人の設定値は返しません。
325
+ 同じ `client` と元の Hook `event` を指定して `get_spawn_routing_observation` で対象呼び出しを照会します。ハッシュ化した相関 ID と、事前確認・分類/キャッシュ結果・推薦・引数更新/適用停止・`execution: not_observed` を区別して返します。`arguments_updated` は Hook が出力した引数だけを意味し、実際の子モデルの観測ではありません。記録は当該 MCP プロセスの直近 128 件・10 分に限られます。`not_observed` は別プロセス・再起動・期限切れ・削除・入力不一致でも発生し、全体の Hook 迂回を証明しません。プロセス共通の `automatic_hook.last_result` は削除します。タスク原文・パス・セッション ID・資格情報は返しません。
316
326
 
317
327
  直接推薦では、リポジトリ・ファイルの URL と、ドキュメントを読んで整理したタスクの範囲・規模・制約を、要約に含めて提供できます。URL の文字列を送ることと、ドキュメントの本文を提供することは異なります。現在の Aptly の分類リクエスト処理コードは、リポジトリ URL を GET したり、ドキュメントを収集したりしません。必要なドキュメントの取得と要約は、呼び出し元が行います。
318
328
 
package/docs/guide/ko.md CHANGED
@@ -203,16 +203,17 @@ aptly remove --client all
203
203
 
204
204
  ## 자동 Hook
205
205
 
206
- 연결된 대상 호출은 `route_spawn_hook` → Decisions를 자동 경유합니다. `defaults`는 해당 범위에서 호스트 기본 모델보다 Aptly의 선택을 우선하도록 운영자가 허용하는 정책입니다. 호스트의 모든 설정 출처를 관측했다는 선언은 아닙니다.
206
+ **다음 사전 검사·추천·관측 동작은 Aptly 0.1.4부터 지원합니다.** 설치한 `PreToolUse` matcher는 Codex의 `spawn_agent` / `collaborationspawn_agent` / `Agent`와 Claude Code의 `Agent` 호출을 native 실행 전에 로컬 `route_spawn_hook`으로 전달합니다. 호스트가 Hook을 로드·신뢰하고 MCP를 연결해야 합니다. 미설정·미지원 호스트나 MCP 연결 실패까지 Aptly가 가로채도록 강제할 수는 없으며, 실행은 호스트가 담당합니다.
207
207
 
208
- | 호스트 | 자동 선택 대상 |
209
- |---|---|
210
- | Codex | 모델·effort·고정 역할·resume을 지정하지 않고 `fork_turns: "none"`인 새 일반 호출 |
211
- | Claude Code | 모델·effort·고정 역할·resume·이력 상속을 지정하지 않은 `subagent_type: "general-purpose"` 호출 |
208
+ 로컬 사전 검사에서 명시 필드·역할·resume·정책·캐시·예산을 평가합니다. 매번 유료 Decisions 요청이 필요한 것은 아닙니다. Codex에서 모델이나 effort만 지정하면 일치하는 허용 튜플로 후보를 제한하고 미지정 필드만 채웁니다. 둘 다 지정하거나 값이 미지원인 경우, 고정 역할과 resume은 분류 없이 보존합니다. 입력 필드만으로 사용자 선택인지 호스트 기본값인지 단정하지 않습니다.
209
+
210
+ 모델·effort가 미지정이면 `fork_turns: "all"`이나 fork 생략도 추천을 평가합니다. **이력 변경은 허용하지 않습니다.** Codex의 모델·effort 적용에는 명시적인 `fork_turns: "none"`이 필요합니다. 그 외에는 `inherited_context_application_unverified`을 알리고 원래 인자를 보존합니다. 다른 이력 필드는 `history_semantics_unverified`로 적용을 차단하며, Claude 적용도 이력 제약 없는 일반 호출로 한정합니다. 추천 성공과 실제 적용은 다릅니다.
211
+
212
+ Codex 본문이 불투명할 때 `cleanup_merged_worktrees`처럼 구체적인 짧은 작업명만으로도 추천할 수 있습니다. 짧은 이름은 cleanup/remove/prune + merged + worktrees/branches 또는 review/fix/test + failing/broken/flaky + tests/builds 조합만 허용하며, 나머지는 기존 6단어 검사를 유지합니다. 본문은 복호화하거나 전송하지 않습니다. 작업의 세부 조건이나 삭제 권한을 추론하지 않습니다. 이력 상속 상태의 적용은 대상 호스트에서 미검증이며, 모든 버전에서 불가능하다는 뜻은 아닙니다. 공개 소스만으로 설치된 런타임의 지원을 확정하지 않습니다.
212
213
 
213
- 명시 선택과 역할·fork·resume, 승인·샌드박스·MCP 권한은 보존합니다. fixture 결과로 기본 모델을 자동 변경하지 않습니다. 불충분한 맥락·지원하지 않는 응답·취소·변경된 호출에서는 기존 인자를 유지합니다. 각 호출의 입력·정책·후보 정보가 일치하는지 확인하고, 비동기 응답 후 다시 확인합니다.
214
+ 독립적인 작업일 때만 호출자가 충분한 독립 작업 맥락을 제공하고 새 자식을 명시적으로 선택하십시오. Aptly는 `all`을 `none`으로 바꾸거나 이력을 제거하거나 명시한 모델·effort를 덮어쓰지 않습니다. [합성 상속·새 자식 예제](../../examples/spawn-preflight.codex.json)는 별개의 호출이며 자동 재시도가 아닙니다. 결과 불명인 유료 호출을 새 ID로 재시도하지 마십시오.
214
215
 
215
- 별도 설정 없이 실행하는 CLI와 기존 수동 설정은 fixture / shadow가 기본입니다. 자동 정책이 없는 기존 호스트 설정 증거에 기반한 경로와 설치한 기본값 선택 정책은 구분합니다. 호스트 내부 패치는 보류 상태이며 직접 추천의 선행 조건이 아닙니다.
216
+ `defaults`는 호환되는 인자 변경을, `advisory`는 추천만 허용합니다. 상속 호출과 일부 필드만 지정한 호출도 적용 차단 여부와 관계없이 제한된 작업 발췌문을 Decisions에 전송할 수 있습니다. 이력 상속은 공유 거부 설정이 아닙니다. 정책 비활성화·맥락 부족·예산 제한·실패·취소에서는 실행 제약을 보존합니다. 입력·정책·카탈로그 결합, 중복 방지와 결과 불명 보호는 유지하며 fixture 추천으로 native 기본값을 바꾸지 않습니다. 자동 정책 없는 strict 증거 경로는 별개이며 호스트 내부 패치는 계속 보류합니다.
216
217
 
217
218
  | MCP 도구 | 용도 |
218
219
  |---|---|
@@ -220,6 +221,9 @@ aptly remove --client all
220
221
  | `recommend_agent` | 작업 요약으로 프로필 추천을 받습니다 |
221
222
  | `get_routing_precedence` | 호출의 보존 근거와 미확인 설정 출처를 설명합니다 |
222
223
  | `route_spawn_hook` | 설치한 정책에 따라 대상 호출의 기본값을 선택하거나 추천만 전달합니다 |
224
+ | `get_spawn_routing_observation` | 정확히 일치하는 Hook 호출을 조회하며 native 실행을 증명하지 않습니다 |
225
+ | `prepare_spawn_context` | 정확한 예정 호출에 제한된 설명을 등록합니다 |
226
+ | `cancel_spawn_context` | 등록한 설명의 연결을 취소하며 native 실행이나 이미 전송된 요청을 취소하지 않습니다 |
223
227
 
224
228
  ### 외부 전송과 자동 공유 끄기
225
229
 
@@ -235,6 +239,12 @@ Decisions에는 `client`, `task.summary`, `task.operation`, `task.context_suffic
235
239
 
236
240
  원장과 Hook 바인딩에는 요청 메타데이터·해시·캐시 결과를 저장하며 작업 발췌문을 저장하지 않습니다. Aptly의 진단 결과에도 원문을 넣지 않습니다. 다만 로컬 호스트가 실행을 이어가도록 Hook의 `updatedInput`에는 원래 작업이 유지됩니다. 호스트 자체의 대화·로그 저장은 Aptly가 제어하지 않습니다.
237
241
 
242
+ ### 불투명 호출에 명시적 설명 전달 (0.1.4부터)
243
+
244
+ 실제 예정된 세션·호출 ID와 원래 이벤트를 아는 연동은 Hook 전에 같은 MCP 프로세스에 `prepare_spawn_context({client, event, description})`를 호출할 수 있습니다. 목적·범위·결과물·제약·복잡도를 짧게 적으세요. URL의 내용은 가져오지 않습니다. 제한된 설명과 고정 접두문만 작업 발췌문을 대체하며, 이력·파일·불투명 본문은 보내지 않습니다. `cancel_spawn_context({client, event})`로 취소합니다. 자동 정책이 활성화되어야 하며 `enabled: false`는 공유를 차단합니다. 알려진 비밀 패턴 검사만으로 완전한 보호를 보장하지 않습니다.
245
+
246
+ 연결은 5분간 유효하고 변경할 수 없으며 프로세스당 최대 128개입니다. 입력 변경·만료·취소 시 분류를 중단하고, 이미 평가한 호출에 설명을 바꿔 유료 재시도하지 않습니다. 실제 예정 이벤트를 알 수 없는 호출자는 사용할 수 없습니다. 기본 Hook은 설명이나 호출 ID를 만들지 않습니다. 로컬 `insufficient_context`, 공급자 `provider_needs_context`, 실제 적용의 `inherited_context_application_unverified`는 서로 다릅니다. 제한된 native 설명 전달 검증은 [전달 계약](../SPAWN_CONTEXT.md)에 기록했습니다. 이 검증은 기본 설명의 자동 생성이나 추천 모델의 실행을 증명하지 않습니다.
247
+
238
248
  ## 직접 추천
239
249
 
240
250
  `recommend_agent` MCP와 CLI `recommend`는 작업 요약을 받아 프로필을 추천합니다. 자식을 직접 생성하지 않습니다. 아래 JSON을 MCP 도구 인자로 전달하거나 파일에 저장해 CLI의 표준 입력으로 제공하십시오.
@@ -310,9 +320,9 @@ export APTLY_MODEL_INFO_PATH=/absolute/private-aptly-state/model-info.json
310
320
 
311
321
  ## 맥락 전달
312
322
 
313
- Codex가 자식 `message`를 암호문으로 Hook에 전달하는 환경에서는 본문을 읽거나 해독하지 않습니다. 이 경우 충분히 구체적인 평문 `task_name`만 요약으로 사용합니다. 예를 들어 `sort_supplied_numbers_3_1_2_ascending_without_tools`처럼 작업 종류와 범위를 설명하십시오. 짧거나 모호한 이름은 원래 모델을 유지합니다. Claude Code와 평문 본문이 전달되는 호출은 제공된 본문 요약을 사용합니다.
323
+ Codex가 자식 `message`를 암호문으로 Hook에 전달하는 환경에서는 본문을 읽거나 해독하지 않습니다. 이 경우 충분히 구체적인 평문 `task_name`만 요약으로 사용합니다. 예를 들어 `sort_supplied_numbers_3_1_2_ascending_without_tools`처럼 작업 종류와 범위를 설명하십시오. 지원하지 않거나 모호한 작업명은 원래 모델을 유지합니다. Claude Code와 평문 본문이 전달되는 호출은 제공된 본문 요약을 사용합니다.
314
324
 
315
- `get_routing_capabilities`의 `automatic_hook.last_result`에서 해당 MCP 프로세스가 마지막으로 기본값을 적용하거나 원래 호출을 유지한 사유를 확인할 수 있습니다. `null`은 아직 자동 Hook 처리 기록이 없다는 뜻입니다. 작업 본문이나 개인 설정 값은 반환하지 않습니다.
325
+ 동일한 `client`와 원래 Hook `event`로 `get_spawn_routing_observation`을 호출해 해당 호출을 조회하십시오. 식별자는 해시로 반환하며 사전 검사, 분류·캐시 결과, 추천, 인자 변경·적용 차단과 `execution: not_observed`를 구분합니다. `arguments_updated`는 Hook 출력 인자만 뜻하며 실제 자식 모델 관측이 아닙니다. 기록은 해당 MCP 프로세스의 최근 128개·10분으로 제한합니다. `not_observed`는 다른 프로세스·재시작·만료·퇴출·입력 불일치 때문일 수도 있으므로 전체 Hook 우회를 증명하지 않습니다. 프로세스 공용 `automatic_hook.last_result`는 제거합니다. 원문 작업·경로·세션 ID·자격 값은 반환하지 않습니다.
316
326
 
317
327
  직접 추천에는 저장소·파일 URL과 문서를 읽고 정리한 작업 범위·규모·제약을 요약에 함께 제공할 수 있습니다. URL 문자열을 보내는 것과 문서 본문을 제공하는 것은 다릅니다. 현재 Aptly의 분류 요청 처리 코드는 저장소 URL을 GET하거나 문서를 수집하지 않습니다. 필요한 문서 조회와 요약은 호출자가 수행합니다.
318
328
 
@@ -203,16 +203,17 @@ aptly remove --client all
203
203
 
204
204
  ## 自动 Hook
205
205
 
206
- 已连接的目标调用会自动经过 `route_spawn_hook` → Decisions。`defaults` 是由操作者明确允许的策略,可在上述范围内优先采用 Aptly 的选择,而非宿主的默认模型。这并不表示已观测到宿主的全部配置来源。
206
+ **以下预检、推荐和观测行为需要 Aptly 0.1.4 或更高版本。** 已安装的 `PreToolUse` matcher 会在原生执行前,将 Codex 的 `spawn_agent` / `collaborationspawn_agent` / `Agent` 和 Claude Code 的 `Agent` 交给本地 `route_spawn_hook`。宿主必须加载并信任 Hook,且连接 MCP。Aptly 无法强制拦截未配置、不支持的宿主或 MCP 不可用的情况;执行仍由宿主负责。
207
207
 
208
- | 宿主 | 自动选择的适用范围 |
209
- |---|---|
210
- | Codex | 未指定模型、effort、固定角色或 resume,且 `fork_turns: "none"` 的新建通用调用 |
211
- | Claude Code | 未指定模型、effort、固定角色、resume 或历史继承,且 `subagent_type: "general-purpose"` 的调用 |
208
+ 本地预检评估显式字段、角色、resume、策略、缓存和预算。不是每次调用都需要新的付费 Decisions 请求。Codex 只指定模型或 effort 时,候选仅限于匹配的允许组合,只填写未指定字段。两者都指定、不支持的值、固定角色和 resume 均在本地保留,不进行分类。仅凭输入无法断定某个字段来自用户还是宿主默认值。
209
+
210
+ 模型和 effort 未指定时,`fork_turns: "all"` 或省略 fork 也会评估推荐,但**不会改变历史**。Codex 应用模型和 effort 仍要求显式 `fork_turns: "none"`,否则报告 `inherited_context_application_unverified` 并保留原始参数。其他历史字段以 `history_semantics_unverified` 阻止应用;Claude 也只对没有历史约束的通用调用应用推荐。生成推荐不等于已应用。
211
+
212
+ Codex 正文不透明时,`cleanup_merged_worktrees` 等具体的短任务名也可用于仅基于名称的推荐。短名称仅允许 cleanup/remove/prune + merged + worktrees/branches,或 review/fix/test + failing/broken/flaky + tests/builds 组合;其他名称仍须通过原有的六词检查。不会解密或发送正文,也不会推断任务细节或删除权限。继承历史时的应用在目标主机上尚未验证,并非所有版本都不支持;公开源码不能证明已安装运行时的支持情况。
212
213
 
213
- 明确指定的选择、角色、fork、resume、审批、沙箱与 MCP 权限设置均会保留。fixture 结果不会自动修改默认模型。如果上下文不足、响应不受支持、调用被取消或已发生变化,则保留现有参数。系统会将输入、策略和候选配置集合与同一次调用绑定,并在收到异步响应后重新确认。
214
+ 仅对独立任务,由调用方提供充分的独立任务上下文并明确选择新子代理。Aptly 不会将 `all` 改成 `none`,删除历史或覆盖显式模型和 effort。[合成的继承与新子代理示例](../../examples/spawn-preflight.codex.json)是不同请求,不是自动重试。不要用新 ID 重试结果不明的付费调用。
214
215
 
215
- 未额外配置的 CLI 与现有手动配置默认使用 fixture / shadow。请区分未启用自动策略、依据宿主配置来源证据进行判断的既有路径,与安装后用于选择默认值的策略。宿主内部补丁工作处于暂停状态,不是直接推荐的前提条件。
216
+ `defaults` 允许兼容的参数更新,`advisory` 只提供建议。继承调用和部分指定的调用即使无法应用推荐,也可能向 Decisions 发送受限任务摘录;继承历史不是关闭共享的方式。策略关闭、上下文不足、预算限制、失败及取消时均保留执行约束。输入、策略和候选绑定、去重及未知结果保护保持不变,fixture 推荐不改写原生默认值。没有自动策略时的 strict 证据路径仍是独立路径;宿主内部补丁继续暂停。
216
217
 
217
218
  | MCP 工具 | 用途 |
218
219
  |---|---|
@@ -220,6 +221,9 @@ aptly remove --client all
220
221
  | `recommend_agent` | 根据任务摘要获取直接推荐 |
221
222
  | `get_routing_precedence` | 解释调用的保留依据与未确认的配置来源 |
222
223
  | `route_spawn_hook` | 根据已安装的策略选择目标调用的默认值,或仅传递推荐 |
224
+ | `get_spawn_routing_observation` | 查询完全匹配的 Hook 调用,不证明原生执行 |
225
+ | `prepare_spawn_context` | 为完全匹配的待执行调用注册受限说明 |
226
+ | `cancel_spawn_context` | 撤销说明关联,不取消原生执行或已发送的请求 |
223
227
 
224
228
  ### 对外传输与关闭自动共享
225
229
 
@@ -235,6 +239,12 @@ Decisions 会收到 `client`、`task.summary`、`task.operation`、`task.context
235
239
 
236
240
  账本与 Hook 绑定保存请求元数据、哈希和缓存结果,不保存任务摘录。Aptly 诊断也不包含任务原文。但本地 Hook 的 `updatedInput` 会保留原任务,以便宿主继续执行。宿主自身的会话和日志保留不受 Aptly 控制。
237
241
 
242
+ ### 为不透明调用提供明确说明(0.1.4 起)
243
+
244
+ 知道真实的待执行会话、调用 ID 和原始事件的集成,可在 Hook 前向同一 MCP 进程调用 `prepare_spawn_context({client, event, description})`。简述目的、范围、预期输出、约束和复杂度;不会抓取 URL 内容。只有受限说明和固定前缀替代任务摘录,不会发送历史、文件或不透明正文。使用 `cancel_spawn_context({client, event})` 撤销。必须启用自动策略;`enabled: false` 阻止共享。已知秘密模式检查并非完整保护。
245
+
246
+ 关联有效期为五分钟,不可修改,每个进程最多128项。输入变化、过期或撤销会阻止分类;不能通过修改说明对已评估调用进行付费重试。无法获取真实待执行事件的调用方不能使用此路径;默认 Hook 不生成说明或调用 ID。本地 `insufficient_context`、提供方 `provider_needs_context` 和应用阶段 `inherited_context_application_unverified` 是不同结果。有限的原生说明交接验证记录于[交接契约](../SPAWN_CONTEXT.md)。此验证不表示会自动生成说明或执行推荐的模型。
247
+
238
248
  ## 直接推荐
239
249
 
240
250
  `recommend_agent` MCP 与 CLI 的 `recommend` 接收任务摘要并推荐执行配置,不会直接创建子代理。请将以下 JSON 作为 MCP 工具参数传递,或保存为文件并通过 CLI 的标准输入提供。
@@ -310,9 +320,9 @@ export APTLY_MODEL_INFO_PATH=/absolute/private-aptly-state/model-info.json
310
320
 
311
321
  ## 提供上下文
312
322
 
313
- 在 Codex 将子代理 `message` 以密文传递给 Hook 的环境中,Aptly 不会读取或解密正文。此时只使用足够具体的明文 `task_name` 作为摘要,例如用 `sort_supplied_numbers_3_1_2_ascending_without_tools` 说明任务类型与范围。名称过短或含糊时保留原有模型。对于 Claude Code 或传递明文正文的调用,则使用所提供正文的摘要。
323
+ 在 Codex 将子代理 `message` 以密文传递给 Hook 的环境中,Aptly 不会读取或解密正文。此时只使用足够具体的明文 `task_name` 作为摘要,例如用 `sort_supplied_numbers_3_1_2_ascending_without_tools` 说明任务类型与范围。不受支持或含糊的任务名称会保留原有模型。对于 Claude Code 或传递明文正文的调用,则使用所提供正文的摘要。
314
324
 
315
- 通过 `get_routing_capabilities` 的 `automatic_hook.last_result`,可查看该 MCP 进程最后一次应用或保留的原因。`null` 表示尚无自动 Hook 处理记录。该诊断不会返回任务正文或个人配置值。
325
+ 使用相同的 `client` 和原始 Hook `event` 调用 `get_spawn_routing_observation`,查询对应调用。它返回哈希关联 ID,并区分预检、分类/缓存结果、推荐、参数更新/应用受阻,以及 `execution: not_observed`。`arguments_updated` 只表示 Hook 输出的参数,不是实际子代理模型的观测。记录仅保留在当前 MCP 进程,最多 128 条、10 分钟。`not_observed` 也可能源于其他进程、重启、过期、淘汰或输入不匹配,不能证明全局绕过 Hook。进程级 `automatic_hook.last_result` 已移除,不返回原始任务、路径、会话 ID 或凭据。
316
326
 
317
327
  直接推荐的摘要可以同时包含仓库、文件 URL,以及阅读文档后整理的任务范围、规模和约束。发送 URL 字符串与提供文档正文不同。目前 Aptly 的分类请求处理代码不会向仓库 URL 发起 GET 请求,也不会获取文档正文。所需的文档读取和摘要由调用方完成。
318
328
 
@@ -0,0 +1,30 @@
1
+ {
2
+ "inherited_request": {
3
+ "client": "codex",
4
+ "event": {
5
+ "hook_event_name": "PreToolUse",
6
+ "session_id": "synthetic-session",
7
+ "tool_use_id": "synthetic-inherited-call",
8
+ "tool_name": "spawn_agent",
9
+ "tool_input": {
10
+ "task_name": "sort_supplied_numbers_without_tools",
11
+ "message": "Sort the supplied numbers [3, 1, 2] in ascending order. Return only the sorted list.",
12
+ "fork_turns": "all"
13
+ }
14
+ }
15
+ },
16
+ "intentional_independent_request": {
17
+ "client": "codex",
18
+ "event": {
19
+ "hook_event_name": "PreToolUse",
20
+ "session_id": "synthetic-session",
21
+ "tool_use_id": "synthetic-independent-call",
22
+ "tool_name": "spawn_agent",
23
+ "tool_input": {
24
+ "task_name": "sort_supplied_numbers_without_tools",
25
+ "message": "This independent task requires no prior conversation. Sort [3, 1, 2] in ascending order and return only the sorted list. No files or tools are needed.",
26
+ "fork_turns": "none"
27
+ }
28
+ }
29
+ }
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aptly",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -38,6 +38,7 @@
38
38
  "LICENSE",
39
39
  "docs/guide/",
40
40
  "docs/ADVISORY_USAGE.md",
41
+ "docs/SPAWN_CONTEXT.md",
41
42
  "docs/DRAFT_0_1_0.md"
42
43
  ],
43
44
  "exports": {