aptly 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.en.md +10 -10
  2. package/README.ja.md +10 -10
  3. package/README.md +10 -10
  4. package/README.zh-CN.md +10 -10
  5. package/dist/bin/aptly-observe.d.ts +2 -0
  6. package/dist/bin/aptly-observe.js +66 -0
  7. package/dist/bin/aptly.js +59 -17
  8. package/dist/src/cli-help.js +18 -11
  9. package/dist/src/cli-input.d.ts +19 -1
  10. package/dist/src/cli-input.js +23 -11
  11. package/dist/src/policy-source.d.ts +3 -0
  12. package/dist/src/policy-source.js +11 -0
  13. package/dist/src/server.d.ts +1 -1
  14. package/dist/src/server.js +44 -2
  15. package/dist/src/setup.d.ts +69 -0
  16. package/dist/src/setup.js +605 -6
  17. package/dist/src/statistics-codex.d.ts +23 -0
  18. package/dist/src/statistics-codex.js +121 -0
  19. package/dist/src/statistics-policy.d.ts +2 -0
  20. package/dist/src/statistics-policy.js +20 -0
  21. package/dist/src/statistics.d.ts +90 -0
  22. package/dist/src/statistics.js +472 -0
  23. package/dist/src/transmission-review-cli.d.ts +11 -0
  24. package/dist/src/transmission-review-cli.js +35 -0
  25. package/dist/src/update-notifier.js +1 -1
  26. package/dist/src/version.d.ts +1 -1
  27. package/dist/src/version.js +1 -1
  28. package/docs/ADVISORY_USAGE.md +1 -1
  29. package/docs/DRAFT_0_1_0.md +1 -1
  30. package/docs/guide/en/advanced.md +217 -0
  31. package/docs/guide/en/benchmarks.md +32 -0
  32. package/docs/guide/en/budget.md +45 -0
  33. package/docs/guide/en/configuration.md +104 -0
  34. package/docs/guide/en/installation.md +114 -0
  35. package/docs/guide/en/routing.md +61 -0
  36. package/docs/guide/en/statistics.md +43 -0
  37. package/docs/guide/en/transmission.md +71 -0
  38. package/docs/guide/en/troubleshooting.md +99 -0
  39. package/docs/guide/en.md +80 -477
  40. package/docs/guide/ja/advanced.md +217 -0
  41. package/docs/guide/ja/benchmarks.md +32 -0
  42. package/docs/guide/ja/budget.md +45 -0
  43. package/docs/guide/ja/configuration.md +104 -0
  44. package/docs/guide/ja/installation.md +114 -0
  45. package/docs/guide/ja/routing.md +61 -0
  46. package/docs/guide/ja/statistics.md +43 -0
  47. package/docs/guide/ja/transmission.md +71 -0
  48. package/docs/guide/ja/troubleshooting.md +99 -0
  49. package/docs/guide/ja.md +80 -477
  50. package/docs/guide/ko/advanced.md +217 -0
  51. package/docs/guide/ko/benchmarks.md +32 -0
  52. package/docs/guide/ko/budget.md +45 -0
  53. package/docs/guide/ko/configuration.md +104 -0
  54. package/docs/guide/ko/installation.md +114 -0
  55. package/docs/guide/ko/routing.md +61 -0
  56. package/docs/guide/ko/statistics.md +43 -0
  57. package/docs/guide/ko/transmission.md +71 -0
  58. package/docs/guide/ko/troubleshooting.md +99 -0
  59. package/docs/guide/ko.md +80 -477
  60. package/docs/guide/zh-CN/advanced.md +217 -0
  61. package/docs/guide/zh-CN/benchmarks.md +32 -0
  62. package/docs/guide/zh-CN/budget.md +45 -0
  63. package/docs/guide/zh-CN/configuration.md +104 -0
  64. package/docs/guide/zh-CN/installation.md +114 -0
  65. package/docs/guide/zh-CN/routing.md +61 -0
  66. package/docs/guide/zh-CN/statistics.md +43 -0
  67. package/docs/guide/zh-CN/transmission.md +71 -0
  68. package/docs/guide/zh-CN/troubleshooting.md +99 -0
  69. package/docs/guide/zh-CN.md +80 -477
  70. package/package.json +3 -2
@@ -0,0 +1,472 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { closeSync, existsSync, fstatSync, lstatSync, openSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { isAbsolute, join } from 'node:path';
5
+ import { assertPrivateStatePath, readRegularFile } from './files.js';
6
+ import { isRecord } from './types.js';
7
+ export const STATISTICS_CONFIG_FILE = 'stats-config.json';
8
+ export const STATISTICS_KEY_FILE = 'stats-key';
9
+ export const STATISTICS_DATABASE_FILE = 'stats.sqlite';
10
+ export const STATISTICS_DB_FILE = STATISTICS_DATABASE_FILE;
11
+ export const STATISTICS_CONFIG_VERSION = 1;
12
+ const require = createRequire(import.meta.url);
13
+ const APP_ID = 0x41505354;
14
+ const CAPACITY = 10_000;
15
+ const hashPattern = /^[a-f0-9]{64}$/;
16
+ const validClient = (v) => v === 'codex' || v === 'claude';
17
+ const id = (v) => typeof v === 'string' && v.length > 0 && v.length <= 1024 && !v.includes('\0') && !v.includes('${');
18
+ const secretLike = (v) => /(?:sk-|bearer(?:[ _.:-]|$)|api[_-]?key|access[_-]?token|secret[_-]?key)/i.test(v);
19
+ const model = (v) => typeof v === 'string' && !secretLike(v) && /^(?:(?:gpt|claude)-[a-z0-9][a-z0-9.-]{0,79}|haiku|sonnet|opus|fable)$/.test(v);
20
+ const safeToken = (v) => typeof v === 'string' && !secretLike(v) && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,95}$/.test(v);
21
+ const effort = (v) => typeof v === 'string' && /^(none|minimal|low|medium|high|xhigh|max|ultra)$/.test(v);
22
+ const ignored = (reason) => ({ status: 'ignored', reason });
23
+ export function parseStatisticsConfig(value) {
24
+ if (!isRecord(value) || value.schema_version !== 1 || !Array.isArray(value.enabled_clients) || value.enabled_clients.length > 2 ||
25
+ !value.enabled_clients.every(validClient) || new Set(value.enabled_clients).size !== value.enabled_clients.length ||
26
+ Object.keys(value).some(k => !['schema_version', 'enabled_clients', 'codex_native_metadata', 'codex_home'].includes(k)) ||
27
+ (value.codex_native_metadata !== undefined && typeof value.codex_native_metadata !== 'boolean') ||
28
+ (value.codex_home !== undefined && (typeof value.codex_home !== 'string' || !isAbsolute(value.codex_home) || value.codex_home.includes('\0'))) ||
29
+ (value.codex_native_metadata === true && value.codex_home === undefined))
30
+ return null;
31
+ return value;
32
+ }
33
+ export function serializeStatisticsConfig(value) {
34
+ if (!parseStatisticsConfig(value))
35
+ throw new Error('statistics_config_invalid');
36
+ return JSON.stringify(value, null, 2) + '\n';
37
+ }
38
+ export function loadStatisticsConfig(options) {
39
+ try {
40
+ const path = join(options.stateDirectory, STATISTICS_CONFIG_FILE);
41
+ privateFile(path);
42
+ return parseStatisticsConfig(JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 8192 }).toString('utf8')));
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ export function statisticsHash(key, domain, client, value) {
49
+ if (!hashPattern.test(key) || !id(value) || !validClient(client))
50
+ throw new Error('statistics_hash_invalid');
51
+ return createHmac('sha256', Buffer.from(key, 'hex')).update(JSON.stringify(['aptly-stats-v1', domain, client, value])).digest('hex');
52
+ }
53
+ export function loadStatisticsHash(options) {
54
+ try {
55
+ privateFile(join(options.stateDirectory, STATISTICS_KEY_FILE));
56
+ const key = readRegularFile(join(options.stateDirectory, STATISTICS_KEY_FILE), { privateFile: true, maxBytes: 65 }).toString('utf8');
57
+ if (!/^[a-f0-9]{64}\n$/.test(key))
58
+ return null;
59
+ return (domain, client, value) => statisticsHash(key.trim(), domain, client, value);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ function privateFile(path, absent = false) {
66
+ assertPrivateStatePath(path);
67
+ try {
68
+ const stat = lstatSync(path);
69
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (process.platform !== 'win32' && (stat.mode & 0o077)))
70
+ throw new Error('statistics_private_file');
71
+ return stat;
72
+ }
73
+ catch (error) {
74
+ if (absent && isRecord(error) && error.code === 'ENOENT')
75
+ return;
76
+ throw error;
77
+ }
78
+ }
79
+ function checkSidecars(path) {
80
+ if (existsSync(path + '-wal') || existsSync(path + '-shm'))
81
+ throw new Error('statistics_wal_unsupported');
82
+ privateFile(path + '-journal', true);
83
+ }
84
+ function initialize(path) {
85
+ // Exclusive reservation never overwrites an existing file and has no hard-link
86
+ // publication window. Incomplete/crashed initialization is deliberately left
87
+ // unavailable for manual review; observers never remove or reinitialize it.
88
+ let fd;
89
+ try {
90
+ fd = openSync(path, 'wx', 0o600);
91
+ }
92
+ catch (error) {
93
+ if (isRecord(error) && error.code === 'EEXIST')
94
+ return;
95
+ throw error;
96
+ }
97
+ const reserved = fstatSync(fd);
98
+ closeSync(fd);
99
+ const before = privateFile(path);
100
+ if (reserved.dev !== before.dev || reserved.ino !== before.ino)
101
+ throw new Error('statistics_identity_changed');
102
+ const { DatabaseSync: Database } = require('node:sqlite');
103
+ const db = new Database(path);
104
+ try {
105
+ const after = privateFile(path);
106
+ if (before.dev !== after.dev || before.ino !== after.ino)
107
+ throw new Error('statistics_identity_changed');
108
+ db.exec(`PRAGMA busy_timeout=50; PRAGMA journal_mode=DELETE; BEGIN IMMEDIATE;
109
+ PRAGMA application_id=${APP_ID}; PRAGMA user_version=1;
110
+ CREATE TABLE delegations(id TEXT PRIMARY KEY, client TEXT NOT NULL, session TEXT, created INTEGER NOT NULL, data TEXT NOT NULL);
111
+ CREATE TABLE children(id TEXT PRIMARY KEY, client TEXT NOT NULL, session TEXT NOT NULL, created INTEGER NOT NULL, data TEXT NOT NULL);
112
+ CREATE TABLE metadata(key TEXT PRIMARY KEY, value INTEGER NOT NULL);
113
+ INSERT INTO metadata VALUES ('capacity_reached',0); COMMIT;`);
114
+ }
115
+ finally {
116
+ db.close();
117
+ }
118
+ }
119
+ function connection(options, write) {
120
+ const path = join(options.stateDirectory, STATISTICS_DATABASE_FILE);
121
+ if (!write && !existsSync(path))
122
+ return null;
123
+ assertPrivateStatePath(path);
124
+ if (!existsSync(path)) {
125
+ if (!write)
126
+ return null;
127
+ initialize(path);
128
+ }
129
+ const before = privateFile(path);
130
+ checkSidecars(path);
131
+ const { DatabaseSync: Database } = require('node:sqlite');
132
+ const db = new Database(path, { readOnly: !write, enableDoubleQuotedStringLiterals: false });
133
+ try {
134
+ const after = privateFile(path);
135
+ if (before.dev !== after.dev || before.ino !== after.ino)
136
+ throw new Error('statistics_identity_changed');
137
+ db.exec('PRAGMA busy_timeout=50');
138
+ if (db.prepare('PRAGMA application_id').get()?.application_id !== APP_ID || db.prepare('PRAGMA user_version').get()?.user_version !== 1 ||
139
+ db.prepare('PRAGMA journal_mode').get()?.journal_mode !== 'delete')
140
+ throw new Error('statistics_database_invalid');
141
+ if (write)
142
+ db.exec('PRAGMA max_page_count=8192; PRAGMA secure_delete=ON; BEGIN IMMEDIATE');
143
+ return db;
144
+ }
145
+ catch (error) {
146
+ db.close();
147
+ throw error;
148
+ }
149
+ }
150
+ function rows(db, table) {
151
+ return db.prepare(`SELECT * FROM ${table} ORDER BY created,id`).all().map(row => ({ ...row, data: JSON.parse(String(row.data)) }));
152
+ }
153
+ function limit(value) { if (value === undefined)
154
+ return CAPACITY; if (!Number.isInteger(value) || value < 1 || value > CAPACITY)
155
+ throw new Error('statistics_capacity_invalid'); return value; }
156
+ function get(db, table, key) { const row = db.prepare(`SELECT data FROM ${table} WHERE id=?`).get(key); return row ? JSON.parse(String(row.data)) : null; }
157
+ function save(db, table, key, client, session, data, options) {
158
+ if (get(db, table, key) !== null) {
159
+ db.prepare(`UPDATE ${table} SET data=? WHERE id=?`).run(JSON.stringify(data), key);
160
+ return;
161
+ }
162
+ const cap = limit(table === 'delegations' ? options.maxDelegations : options.maxChildren);
163
+ if (Number(db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n) >= cap) {
164
+ db.prepare("UPDATE metadata SET value=1 WHERE key='capacity_reached'").run();
165
+ return;
166
+ }
167
+ db.prepare(`INSERT INTO ${table}(id,client,session,created,data) VALUES(?,?,?,?,?)`).run(key, client, session, Math.floor((options.now ?? Date.now)()), JSON.stringify(data));
168
+ }
169
+ function transact(options, client, fn) {
170
+ if (!loadStatisticsConfig(options)?.enabled_clients.includes(client))
171
+ return ignored('collection_disabled');
172
+ const hash = loadStatisticsHash(options);
173
+ if (!hash)
174
+ return { status: 'unavailable', reason: 'statistics_key_unavailable' };
175
+ let db = null;
176
+ try {
177
+ db = connection(options, true);
178
+ fn(db, hash);
179
+ db.exec('COMMIT');
180
+ return { status: 'recorded' };
181
+ }
182
+ catch {
183
+ if (db)
184
+ try {
185
+ db.exec('ROLLBACK');
186
+ }
187
+ catch { }
188
+ return { status: 'unavailable', reason: 'statistics_store_unavailable' };
189
+ }
190
+ finally {
191
+ try {
192
+ db?.close();
193
+ }
194
+ catch { }
195
+ }
196
+ }
197
+ const combined = (hash, client, kind, session, value) => hash(kind, client, JSON.stringify([hash('session', client, session), hash(kind, client, value)]));
198
+ function expectedValue(input, hash) {
199
+ const e = input.expected;
200
+ if (!e || !safeToken(e.profileId) || !model(e.model) || (e.effort !== undefined && !effort(e.effort)) || (e.catalogVersion !== undefined && !id(e.catalogVersion)))
201
+ return;
202
+ return { profileId: e.profileId, model: e.model, ...(e.effort ? { effort: e.effort } : {}), ...(e.catalogVersion ? { catalogHash: hash('request', input.client, e.catalogVersion) } : {}) };
203
+ }
204
+ export function recordStatisticsRecommendation(options, input) {
205
+ if (!validClient(input.client) || !['auto', 'advisory', 'blocked', 'explicit_preserved', 'unbound'].includes(input.disposition))
206
+ return ignored('invalid_recommendation');
207
+ const bound = id(input.sessionId) && id(input.toolUseId) && input.disposition !== 'unbound';
208
+ if (!bound && !id(input.requestId))
209
+ return ignored('missing_binding');
210
+ return transact(options, input.client, (db, hash) => {
211
+ const key = bound ? combined(hash, input.client, 'tool', input.sessionId, input.toolUseId) : hash('request', input.client, input.requestId);
212
+ const value = get(db, 'delegations', key) ?? {};
213
+ const disposition = bound ? input.disposition : 'unbound';
214
+ const expected = expectedValue(input, hash);
215
+ if (['auto', 'advisory'].includes(disposition) && !expected)
216
+ throw new Error('statistics_expected_invalid');
217
+ if (value.disposition && (value.disposition !== disposition || JSON.stringify(value.expected) !== JSON.stringify(expected)))
218
+ value.conflict = true;
219
+ else {
220
+ value.disposition = disposition;
221
+ value.expected = expected;
222
+ }
223
+ save(db, 'delegations', key, input.client, bound ? hash('session', input.client, input.sessionId) : '', value, options);
224
+ });
225
+ }
226
+ function union(values, value) { return [...new Set([...(values ?? []), value])].sort(); }
227
+ function modelEvidence(child, value) { if (model(value)) {
228
+ const next = union(child.models, value);
229
+ if (next.length > 16)
230
+ child.conflict = true;
231
+ else
232
+ child.models = next;
233
+ }
234
+ else
235
+ child.unknownModel = true; }
236
+ function toolResponse(value) {
237
+ if (isRecord(value))
238
+ return value;
239
+ if (typeof value === 'string' && Buffer.byteLength(value) <= 32768)
240
+ try {
241
+ const parsed = JSON.parse(value);
242
+ return isRecord(parsed) ? parsed : null;
243
+ }
244
+ catch { }
245
+ return null;
246
+ }
247
+ export function observeStatistics(options, input, bridge) {
248
+ const { client, event } = input;
249
+ if (!validClient(client) || !isRecord(event) || !id(event.session_id))
250
+ return ignored('invalid_event');
251
+ const session = event.session_id;
252
+ const name = event.hook_event_name;
253
+ const tool = name === 'PostToolUse';
254
+ if (tool && event.tool_use_id !== undefined && event.tool_call_id !== undefined && event.tool_use_id !== event.tool_call_id)
255
+ return ignored('conflicting_tool_binding');
256
+ const toolId = event.tool_use_id ?? event.tool_call_id;
257
+ const phase = name === 'SubagentStart' ? 'start' : name === 'SubagentStop' ? 'stop' : client === 'codex' && name === 'PostModelRequest' ? 'request' : null;
258
+ if (tool && (!id(toolId) || !(client === 'claude' ? event.tool_name === 'Agent' || event.tool_name === 'Task' : event.tool_name === 'collaborationspawn_agent' || event.tool_name === 'spawn_agent' || event.tool_name === 'collaboration.spawn_agent')))
259
+ return ignored('unsupported_tool');
260
+ if (!tool && (!phase || !id(event.agent_id)))
261
+ return ignored('unsupported_event');
262
+ return transact(options, client, (db, hash) => {
263
+ const sessionHash = hash('session', client, session);
264
+ if (tool) {
265
+ const response = toolResponse(event.tool_response);
266
+ const key = combined(hash, client, 'tool', session, toolId);
267
+ const value = get(db, 'delegations', key) ?? {};
268
+ value.toolObserved = true;
269
+ const actualChild = client === 'claude' ? response?.agentId : response?.agent_id;
270
+ if (id(actualChild)) {
271
+ const childKey = combined(hash, client, 'child', session, actualChild);
272
+ if (value.child && value.child !== childKey)
273
+ value.conflict = true;
274
+ else
275
+ value.child = childKey;
276
+ }
277
+ if (client === 'codex' && id(response?.task_name)) {
278
+ const path = hash('task_path', client, response.task_name);
279
+ if (value.path && value.path !== path)
280
+ value.conflict = true;
281
+ else
282
+ value.path = path;
283
+ }
284
+ // Fingerprint only allowed model/effort fields, never retain original arguments.
285
+ const args = isRecord(event.tool_input) ? event.tool_input : null;
286
+ const actualModel = args?.model;
287
+ const actualEffort = args?.reasoning_effort !== undefined ? args.reasoning_effort : args?.effort;
288
+ const conflictingEfforts = args && args.reasoning_effort !== undefined && args.effort !== undefined && args.reasoning_effort !== args.effort;
289
+ if (response && !conflictingEfforts && model(actualModel) && (actualEffort === undefined || effort(actualEffort)))
290
+ value.applied = union(value.applied, JSON.stringify([actualModel, actualEffort ?? null]));
291
+ else
292
+ value.appliedUnknown = true;
293
+ if ((value.applied?.length ?? 0) > 4) {
294
+ value.applied = value.applied.slice(0, 4);
295
+ value.conflict = true;
296
+ }
297
+ save(db, 'delegations', key, client, sessionHash, value, options);
298
+ if (client === 'claude' && value.child && response) {
299
+ const child = get(db, 'children', value.child) ?? {};
300
+ if (response.status === 'completed') {
301
+ child.complete = true;
302
+ modelEvidence(child, response.resolvedModel);
303
+ if (Array.isArray(response.modelsUsed)) {
304
+ if (response.modelsUsed.length > 16)
305
+ child.conflict = true;
306
+ for (const m of response.modelsUsed.slice(0, 16))
307
+ modelEvidence(child, m);
308
+ }
309
+ else if (response.modelsUsed !== undefined)
310
+ child.unknownModel = true;
311
+ }
312
+ else if (response.status === 'async_launched')
313
+ child.started = true;
314
+ save(db, 'children', value.child, client, sessionHash, child, options);
315
+ }
316
+ }
317
+ else {
318
+ const key = combined(hash, client, 'child', session, event.agent_id);
319
+ const value = get(db, 'children', key) ?? {};
320
+ if (phase === 'start')
321
+ value.started = true;
322
+ if (phase === 'stop')
323
+ value.stopped = true;
324
+ if (phase === 'request' && event.status === 'completed' && (event.error === null || event.error === undefined)) {
325
+ value.complete = true;
326
+ modelEvidence(value, event.model);
327
+ }
328
+ if (bridge && client === 'codex') {
329
+ if (!hashPattern.test(bridge.parentSessionHash) || !hashPattern.test(bridge.taskPathHash) || bridge.parentSessionHash !== sessionHash)
330
+ value.conflict = true;
331
+ else if (value.path && value.path !== bridge.taskPathHash)
332
+ value.conflict = true;
333
+ else
334
+ value.path = bridge.taskPathHash;
335
+ }
336
+ save(db, 'children', key, client, sessionHash, value, options);
337
+ }
338
+ });
339
+ }
340
+ const emptyCounts = () => ({ model_match: 0, model_mismatch: 0, model_changed: 0, unknown: 0, pending: 0, expired_pending: 0, application_unconfirmed: 0 });
341
+ function confirmed(d) { return !d.appliedUnknown && !!d.expected && d.applied?.length === 1 && d.applied[0] === JSON.stringify([d.expected.model, d.expected.effort ?? null]); }
342
+ function modelState(d, c, ambiguous, created, now) {
343
+ if (d.conflict || ambiguous || c?.conflict)
344
+ return 'unknown';
345
+ if (d.disposition === 'auto' && !confirmed(d))
346
+ return !d.toolObserved && !c ? (now - created > 86400000 ? 'expired_pending' : 'pending') : 'application_unconfirmed';
347
+ if (!c?.complete)
348
+ return c?.stopped ? 'unknown' : now - created > 86400000 ? 'expired_pending' : 'pending';
349
+ if ((c.models?.length ?? 0) > 1)
350
+ return 'model_changed';
351
+ if (c.unknownModel || !c.models?.length || !d.expected)
352
+ return 'unknown';
353
+ const expected = d.expected.model, actual = c.models[0];
354
+ // No family-prefix guessing: aliases are not versioned execution evidence.
355
+ if (['haiku', 'sonnet', 'opus', 'fable'].includes(expected) || ['haiku', 'sonnet', 'opus', 'fable'].includes(actual))
356
+ return 'unknown';
357
+ return expected === actual ? 'model_match' : 'model_mismatch';
358
+ }
359
+ export function readStatistics(options, filter = {}) {
360
+ const now = (options.now ?? Date.now)();
361
+ const output = { status: 'ok', scope: 'retained_records', semantics: 'retained_routing_records_not_user_acceptance_or_execution_total', observation_completeness: 'best_effort_not_full_execution_history', today_basis: 'UTC_binding_creation', filter: { client: filter.client ?? 'all', today: filter.today === true },
362
+ collection: { codex: false, claude: false }, capacity: { delegations: limit(options.maxDelegations), children: limit(options.maxChildren), reached: false },
363
+ delegations: 0, auto: emptyCounts(), advisory: emptyCounts(), blocked: 0, explicit_preserved: 0, unbound: 0,
364
+ effort_actual_unknown: 0, application_confirmed: 0, unknown_alias_count: 0, model_observed: 0, model_comparable: 0, model_match_denominator: 0, observation_denominator: 0,
365
+ usage_scope: 'not_collected', model_alias_scope: 'exact_canonical_model_ids_only', counts_are_lifetime: false };
366
+ const config = loadStatisticsConfig(options);
367
+ for (const client of config?.enabled_clients ?? [])
368
+ output.collection[client] = true;
369
+ let db = null;
370
+ try {
371
+ db = connection(options, false);
372
+ if (!db)
373
+ return output;
374
+ // All projection inputs must come from one SQLite snapshot. Separate implicit
375
+ // SELECT transactions can otherwise combine old bindings with new child facts.
376
+ db.exec('BEGIN');
377
+ output.capacity.reached = db.prepare("SELECT value FROM metadata WHERE key='capacity_reached'").get()?.value === 1;
378
+ const delegates = rows(db, 'delegations');
379
+ const children = rows(db, 'children');
380
+ // Index retained metadata once: a bounded store must also have bounded query work.
381
+ const childrenById = new Map(children.map(row => [row.id, row]));
382
+ const childrenByPath = new Map();
383
+ const delegationsByPath = new Map();
384
+ const delegationsByChild = new Map();
385
+ const pathKey = (client, session, path) => JSON.stringify([client, session, path]);
386
+ for (const child of children)
387
+ if (child.data.path) {
388
+ const key = pathKey(child.client, child.session, child.data.path);
389
+ const list = childrenByPath.get(key) ?? [];
390
+ list.push(child);
391
+ childrenByPath.set(key, list);
392
+ }
393
+ for (const row of delegates) {
394
+ if (row.data.path) {
395
+ const key = pathKey(row.client, row.session, row.data.path);
396
+ const set = delegationsByPath.get(key) ?? new Set();
397
+ set.add(row.id);
398
+ delegationsByPath.set(key, set);
399
+ }
400
+ if (row.data.child) {
401
+ const set = delegationsByChild.get(row.data.child) ?? new Set();
402
+ set.add(row.id);
403
+ delegationsByChild.set(row.data.child, set);
404
+ }
405
+ }
406
+ const today = new Date(now).toISOString().slice(0, 10);
407
+ for (const row of delegates) {
408
+ const d = row.data;
409
+ if (!d.disposition || (filter.client && filter.client !== 'all' && row.client !== filter.client) || (filter.today && new Date(row.created).toISOString().slice(0, 10) !== today))
410
+ continue;
411
+ output.delegations++;
412
+ if (d.disposition === 'unbound' || d.disposition === 'blocked' || d.disposition === 'explicit_preserved') {
413
+ output[d.disposition]++;
414
+ continue;
415
+ }
416
+ const direct = d.child ? childrenById.get(d.child) : undefined;
417
+ const matches = d.child ? (direct && direct.client === row.client && direct.session === row.session ? [direct] : []) : d.path ? childrenByPath.get(pathKey(row.client, row.session, d.path)) ?? [] : [];
418
+ const child = matches.length === 1 ? matches[0] : undefined;
419
+ // A reused canonical path or child cannot retroactively certify either call.
420
+ const contenders = new Set();
421
+ const add = (ids) => { for (const id of ids ?? [])
422
+ if (id !== row.id)
423
+ contenders.add(id); };
424
+ if (d.path)
425
+ add(delegationsByPath.get(pathKey(row.client, row.session, d.path)));
426
+ if (d.child)
427
+ add(delegationsByChild.get(d.child));
428
+ if (child) {
429
+ add(delegationsByChild.get(child.id));
430
+ if (child.data.path)
431
+ add(delegationsByPath.get(pathKey(row.client, row.session, child.data.path)));
432
+ }
433
+ const pathConflict = !!(d.path && child?.data.path && d.path !== child.data.path);
434
+ const childPathAmbiguous = !!(child?.data.path && (childrenByPath.get(pathKey(row.client, row.session, child.data.path))?.length ?? 0) > 1);
435
+ const otherPathChild = !!(d.child && d.path && childrenByPath.get(pathKey(row.client, row.session, d.path))?.some(other => other.id !== d.child));
436
+ const ambiguous = matches.length > 1 || contenders.size > 0 || pathConflict || childPathAmbiguous || otherPathChild;
437
+ const validEvidence = !ambiguous && !d.conflict && !!child && !child.data.conflict && child.data.complete === true && !child.data.unknownModel && !!child.data.models?.length;
438
+ const state = modelState(d, child?.data, ambiguous, row.created, now);
439
+ output[d.disposition][state]++;
440
+ output.effort_actual_unknown++;
441
+ if (state === 'unknown' && validEvidence && child.data.models.length === 1 && d.expected &&
442
+ (d.disposition !== 'auto' || confirmed(d)) && [d.expected.model, child.data.models[0]].some(m => ['haiku', 'sonnet', 'opus', 'fable'].includes(m)))
443
+ output.unknown_alias_count++;
444
+ if (d.disposition === 'auto') {
445
+ output.observation_denominator++;
446
+ if (confirmed(d) && !d.conflict)
447
+ output.application_confirmed++;
448
+ if (validEvidence)
449
+ output.model_observed++;
450
+ if (state === 'model_match' || state === 'model_mismatch') {
451
+ output.model_comparable++;
452
+ output.model_match_denominator++;
453
+ }
454
+ }
455
+ }
456
+ return output;
457
+ }
458
+ catch {
459
+ output.status = 'unavailable';
460
+ return output;
461
+ }
462
+ finally {
463
+ try {
464
+ db?.exec('ROLLBACK');
465
+ }
466
+ catch { }
467
+ try {
468
+ db?.close();
469
+ }
470
+ catch { }
471
+ }
472
+ }
@@ -0,0 +1,11 @@
1
+ import { type SetupOptions, type SetupResult } from './setup.ts';
2
+ import { type TransmissionPromptCandidate, type TransmissionReviewChoice } from './cli-input.ts';
3
+ interface ReviewDependencies {
4
+ interactive?: boolean;
5
+ readChoice?: (candidates: readonly TransmissionPromptCandidate[]) => Promise<TransmissionReviewChoice>;
6
+ }
7
+ /** CLI-only orchestration: never called by MCP, Hooks, updater or read-only commands. */
8
+ export declare function runTransmissionReview(options?: SetupOptions, forceReview?: boolean, dependencies?: ReviewDependencies): Promise<SetupResult>;
9
+ /** Preserve the completed base setup result while exposing the separate review outcome. */
10
+ export declare function reviewAfterSetup(base: SetupResult, options?: SetupOptions, dependencies?: ReviewDependencies): Promise<SetupResult>;
11
+ export {};
@@ -0,0 +1,35 @@
1
+ import { prepareTransmissionReview } from './setup.js';
2
+ import { canPromptTransmission, readTransmissionReviewChoice } from './cli-input.js';
3
+ /** CLI-only orchestration: never called by MCP, Hooks, updater or read-only commands. */
4
+ export async function runTransmissionReview(options = {}, forceReview = false, dependencies = {}) {
5
+ const interactive = dependencies.interactive ?? canPromptTransmission();
6
+ if (forceReview && !interactive)
7
+ throw new Error('set_interactive_input_required');
8
+ const prepared = prepareTransmissionReview({ ...options, forceReview });
9
+ if (prepared.result.status !== 'complete' || !prepared.candidates.length || !interactive)
10
+ return prepared.result;
11
+ const choice = await (dependencies.readChoice ?? readTransmissionReviewChoice)(prepared.candidates);
12
+ return prepared.apply(choice);
13
+ }
14
+ /** Preserve the completed base setup result while exposing the separate review outcome. */
15
+ export async function reviewAfterSetup(base, options = {}, dependencies = {}) {
16
+ if (base.status !== 'complete')
17
+ return base;
18
+ const clients = base.clients.filter(c => c.status === 'configured' || c.status === 'unchanged').map(c => c.client);
19
+ if (!clients.length)
20
+ return base;
21
+ const review = await runTransmissionReview({ ...options, clients }, false, dependencies);
22
+ return { status: review.status === 'partial' ? 'partial' : base.status, clients: base.clients.map(previous => {
23
+ const next = review.clients.find(c => c.client === previous.client);
24
+ if (!next)
25
+ return previous;
26
+ let codes = [...new Set([...previous.codes, ...next.codes])];
27
+ if (next.transmission_review === 'complete')
28
+ codes = codes.filter(c => c !== 'transmission_review_required');
29
+ if (next.transmission !== undefined && next.transmission !== 'unselected')
30
+ codes = codes.filter(c => c !== 'transmission_selection_required');
31
+ if (next.transmission_source !== undefined && next.transmission_source !== 'legacy')
32
+ codes = codes.filter(c => c !== 'legacy_transmission_excerpt');
33
+ return { ...previous, ...next, status: next.status === 'unchanged' ? previous.status : next.status, codes };
34
+ }) };
35
+ }
@@ -23,7 +23,7 @@ function newer(candidate, current) {
23
23
  }
24
24
  function eligible(o) {
25
25
  return o.stdinIsTTY && o.stderrIsTTY && o.stdoutIsTTY !== false && !o.env.CI && o.env.APTLY_NO_UPDATE_NOTIFIER !== '1' && !!version(o.currentVersion) &&
26
- ['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !o.args.includes('--check') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
26
+ ['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !o.args.includes('--check') && !o.args.includes('--dry-run') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
27
27
  }
28
28
  function directory(path) {
29
29
  if (!isAbsolute(path))
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.9";
1
+ export declare const VERSION = "0.1.11";
@@ -1 +1 @@
1
- export const VERSION = '0.1.9';
1
+ export const VERSION = '0.1.11';
@@ -191,6 +191,6 @@ live 분류는 비용이 발생할 수 있어요. 원장은 요청 전에 예약
191
191
  - `ledger_locked`이면 같은 원장을 쓰는 기존 서버·명령이 아직 실행 중인지 먼저 확인해요. 실행 중인 프로세스의 lock은 삭제하지 않아요. crash가 확인돼도 원장을 보존하고, 관련 프로세스가 모두 끝난 것을 확인한 뒤 그 원장의 stale lock만 운영자가 별도로 처리해요. 자동 lock 삭제·원장 초기화 기능은 없어요.
192
192
  - 인증·429·timeout을 수정한 뒤에도 이전 요청이 unknown이면 새 ID로 무조건 재시도하지 않아요. 이 규칙은 실패 메시지가 안전한 코드로만 반환돼 원시 API 오류를 볼 수 없는 경우에도 같아요.
193
193
 
194
- 진단 자료가 필요하면 `report --format both --output-dir reports`로 로컬 첨부 파일을 만들고 검토해요. 키가 존재한다는 진단은 API 인증 성공을 뜻하지 않아요. [진단 안내](REPORTING.md), [공개 준비](RELEASING.md)를 참고해요.
194
+ 진단 자료가 필요하면 `report --format both --output-dir reports`로 로컬 첨부 파일을 만들고 검토해요. 키가 존재한다는 진단은 API 인증 성공을 뜻하지 않아요. [진단 안내](https://github.com/abruption/aptly/blob/9d1f7d6449290fee961ccaead0be1d032a88e809/docs/REPORTING.md), [공개 준비](https://github.com/abruption/aptly/blob/9d1f7d6449290fee961ccaead0be1d032a88e809/docs/RELEASING.md)를 참고해요.
195
195
 
196
196
  설치용 npm archive에는 이 사용 안내를 동봉해요. 설계·호환성·과거 검증 등 다른 문서는 source archive에서 확인해요.
@@ -52,4 +52,4 @@ Hook 추가 전 후보·모델 정보 초안은 Node 무료 회귀 **226/226**,
52
52
 
53
53
  후보·모델 정보 초안 작업에서는 새 후보의 유료 Decisions 호출·실제 child 실행·호스트 내부 실험을 하지 않았어요. 설치·자동 Hook 후속 작업의 실제 검증 상태는 해당 후보의 기록을 확인해요. 문서나 합성 시험만으로 native 적용 성공을 주장하지 않아요. 새 세 단계의 업무별 품질·토큰 절감·비용 최적성은 아직 평가하지 않았어요. 비용 관련 기본값은 사용자 요청한 프리셋이며 측정된 최저 비용 순위가 아니에요.
54
54
 
55
- 과거 Node 193개 회귀·실제 Decisions 11회·초기 범주 8/8 기록은 **이전 네 프로필 카탈로그**의 검증이에요. 이를 이번 여섯 기본 프로필이나 새 환경변수·cache의 검증으로 바꾸어 표시하지 않아요. 그 기록은 [이전 실제 결과](ADVISORY_RESULTS.md)에 보존해요.
55
+ 과거 Node 193개 회귀·실제 Decisions 11회·초기 범주 8/8 기록은 **이전 네 프로필 카탈로그**의 검증이에요. 이를 이번 여섯 기본 프로필이나 새 환경변수·cache의 검증으로 바꾸어 표시하지 않아요. 그 기록은 [이전 실제 결과](https://github.com/abruption/aptly/blob/9d1f7d6449290fee961ccaead0be1d032a88e809/docs/ADVISORY_RESULTS.md)에 보존해요.