aptly 0.1.9 → 0.1.10
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/dist/bin/aptly-observe.d.ts +2 -0
- package/dist/bin/aptly-observe.js +66 -0
- package/dist/bin/aptly.js +40 -3
- package/dist/src/cli-help.js +7 -2
- package/dist/src/server.js +34 -1
- package/dist/src/setup.d.ts +48 -0
- package/dist/src/setup.js +265 -3
- package/dist/src/statistics-codex.d.ts +23 -0
- package/dist/src/statistics-codex.js +121 -0
- package/dist/src/statistics-policy.d.ts +2 -0
- package/dist/src/statistics-policy.js +20 -0
- package/dist/src/statistics.d.ts +90 -0
- package/dist/src/statistics.js +472 -0
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/docs/guide/en.md +28 -0
- package/docs/guide/ja.md +28 -0
- package/docs/guide/ko.md +28 -0
- package/docs/guide/zh-CN.md +28 -0
- package/package.json +2 -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
|
+
}
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.1.
|
|
1
|
+
export declare const VERSION = "0.1.10";
|
package/dist/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = '0.1.
|
|
1
|
+
export const VERSION = '0.1.10';
|
package/docs/guide/en.md
CHANGED
|
@@ -282,6 +282,34 @@ Setting commands support `--client codex|claude|all`, hidden input and explicit
|
|
|
282
282
|
|
|
283
283
|
New pre-HTTP budget denials are not cached. Only verifiable known-unpaid legacy default-policy denials can be reevaluated with the same ID; completed recommendations, abstentions, context outcomes and `unknown` remain protected. Budget recovery does not extend the original five-minute retry reference or process lifetime and does not remove history or permission constraints. Arbitrary historical custom-policy digests are not guessed; do not bypass conflicts/unknowns with new IDs or ledger deletion.
|
|
284
284
|
|
|
285
|
+
<a id="execution-statistics"></a>
|
|
286
|
+
|
|
287
|
+
### Execution statistics (0.1.10 or later)
|
|
288
|
+
|
|
289
|
+
Execution statistics require Aptly 0.1.10 or later. Install a supported version or upgrade following [package updates](#package-updates), then use the examples below. An existing Aptly setup is required. Collection is initially POSIX-only; Windows collection is unsupported and normal Aptly use on Windows is unaffected.
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
aptly stats
|
|
293
|
+
aptly stats --today --client codex
|
|
294
|
+
aptly stats enable --client codex
|
|
295
|
+
aptly stats enable --client codex --codex-native-metadata
|
|
296
|
+
aptly stats disable --client codex
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
The command forms are `aptly stats [--today] [--client codex|claude|all]`, `aptly stats enable [--client] [--codex-native-metadata]` and `aptly stats disable [--client]`. Collection is off by default and postinstall does not enable it. Enable installs Aptly-owned command observers recorded separately in `stats-ownership.json`; it leaves the legacy receipt, MCP, launchers, keys, budget and transmission settings intact. Restart MCP and the host after enabling; for Codex, review native Hook trust in `/hooks`.
|
|
300
|
+
|
|
301
|
+
Disable turns collection off and removes only unchanged owned observers. Modified or custom observers are preserved with a warning; data and the key remain. `remove` validates and removes stats-owned definitions but keeps the data. Independently managed collectors and custom Hooks are not adopted automatically.
|
|
302
|
+
|
|
303
|
+
Private state uses `stats.sqlite`, `stats-config.json` and `stats-key` (an HMAC secret), separately from the budget ledger. Do not share the key. Records contain no task text, transcripts, raw IDs, paths, errors or credentials. Reading stats makes no API, key or credential-store calls, initializes nothing and runs no notifier.
|
|
304
|
+
|
|
305
|
+
The projection reports `model_match`, `model_mismatch`, `model_changed`, `unknown`, `pending`, `expired_pending` and `application_unconfirmed`; advisory is separate. `blocked`, `explicit_preserved` and `unbound` are excluded from denominators. Effective effort is never measured; configured effort is not actual effort. Claude aliases `haiku`, `sonnet`, `opus` and `fable` cannot be resolved to an actual canonical model and are `unknown`; only exact canonical models are supported, and observing a model does not guarantee all aliases match. These figures do not establish user acceptance or quality.
|
|
306
|
+
|
|
307
|
+
Direct advisory, retries and fresh unbound calls without native continuity are not joined by approximate timing. `--today` uses the UTC date when the binding was first created. Capacity is fixed at 10,000 delegations and 10,000 children, with no automatic pruning. Counts cover retained records, not lifetime totals; at capacity, new identities are dropped and the reached flag is set. Missing callbacks do not prove bypass. There are no token or cost rollups, live quota or savings figures.
|
|
308
|
+
|
|
309
|
+
Codex native metadata is off unless explicitly enabled. It reads SQLite native metadata by exact child ID only: no transcripts, repairs or app-server launch. Relocated `sqlite_home`, unsupported schemas or paths, and ambiguous joins yield unknown. A SQL read may update existing SHM read marks; it writes no rows or schema and does not intentionally create sidecars.
|
|
310
|
+
|
|
311
|
+
Collection is best effort: lost, delayed or capacity-dropped events can leave an incomplete model history. `model_match` means the retained evidence matches, not that every request used that model. Disabling Codex collection, removing setup or enabling without `--codex-native-metadata` revokes native metadata access. After changing the Node or package path, disable and re-enable collection to register current commands. An unavailable or corrupt store is preserved; review it locally rather than deleting the key or assuming zero usage.
|
|
312
|
+
|
|
285
313
|
<a id="outbound-data-and-disabling-automatic-sharing"></a>
|
|
286
314
|
|
|
287
315
|
### Decisions API transmission scope
|
package/docs/guide/ja.md
CHANGED
|
@@ -282,6 +282,34 @@ aptly budget status --client claude
|
|
|
282
282
|
|
|
283
283
|
HTTP 前の新しい予算拒否はキャッシュしません。検証可能な既存の既定ポリシーによる未課金の拒否だけを同じ ID で再評価し、完了した推薦・保留・文脈不足の結果と `unknown` は保持します。予算回復は元の retry 参照の 5 分やプロセス寿命を延長せず、履歴や権限の制約も解除しません。任意の過去の独自ポリシーの digest を推測せず、新しい ID や台帳削除で競合・不明結果を回避しないでください。
|
|
284
284
|
|
|
285
|
+
<a id="execution-statistics"></a>
|
|
286
|
+
|
|
287
|
+
### 実行統計(0.1.10 以降)
|
|
288
|
+
|
|
289
|
+
実行統計は Aptly 0.1.10 以降で利用できます。対応バージョンをインストールするか、[パッケージの更新](#パッケージの更新)に従ってアップグレードしてから次の例を使用してください。既存の Aptly 設定が必要です。初期の収集は POSIX のみ対応し、Windows の統計収集は未対応です。Windows での通常の Aptly 利用には影響しません。
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
aptly stats
|
|
293
|
+
aptly stats --today --client codex
|
|
294
|
+
aptly stats enable --client codex
|
|
295
|
+
aptly stats enable --client codex --codex-native-metadata
|
|
296
|
+
aptly stats disable --client codex
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
形式は `aptly stats [--today] [--client codex|claude|all]`、`aptly stats enable [--client] [--codex-native-metadata]`、`aptly stats disable [--client]` です。収集は既定で無効で、postinstall でも自動有効化しません。enable は Aptly 所有のコマンド観測器を設置し、別の `stats-ownership.json` に記録します。既存の receipt・MCP・launcher・キー・予算・送信設定は保持します。有効化後は MCP とホストを再起動し、Codex では `/hooks` で native Hook の信頼を確認してください。
|
|
300
|
+
|
|
301
|
+
disable は収集を無効にし、変更されていない所有観測器だけを削除します。変更済みやカスタムの観測器は警告して保持し、データとキーも残します。`remove` は統計所有の定義を検証・削除しますが、データは保持します。個別に管理される収集器やカスタム Hook は自動的に取り込みません。
|
|
302
|
+
|
|
303
|
+
非公開の状態は予算台帳とは別の `stats.sqlite`、`stats-config.json`、`stats-key`(HMAC 秘密鍵)を使用します。鍵を共有しないでください。記録にタスク原文・会話記録・生 ID・パス・エラー・資格情報は含まれません。統計の読み取りは API・キー・資格情報ストアにアクセスせず、初期化や通知も行いません。
|
|
304
|
+
|
|
305
|
+
集計は `model_match`、`model_mismatch`、`model_changed`、`unknown`、`pending`、`expired_pending`、`application_unconfirmed` を示し、advisory は別に扱います。`blocked`、`explicit_preserved`、`unbound` は分母から除外します。実際の effort は測定せず、設定された effort は実際の値ではありません。Claude のエイリアス `haiku`、`sonnet`、`opus`、`fable` は実際の正規モデルに解決できず `unknown` です。正確な正規モデルのみ対応し、モデルの観測は全エイリアスの一致を保証しません。ユーザーの受容や品質を示す数値ではありません。
|
|
306
|
+
|
|
307
|
+
直接 advisory・retry・native の連続性がない新規 unbound 呼び出しを曖昧な時刻で結合しません。`--today` はバインディングの初回作成日の UTC 日付を使います。容量は委任 10,000 件と 子 10,000 件に固定され、自動削除はありません。件数は保持レコードの値であり、生涯累計ではありません。容量到達時は新規 ID を破棄し、到達フラグを表示します。コールバックの欠落はバイパスの証拠ではありません。トークン・コストの集計、ライブ割当量や節約額はありません。
|
|
308
|
+
|
|
309
|
+
Codex native メタデータは明示オプションがない限り無効です。正確な子 ID で SQLite の native メタデータだけを読み、会話記録の取得・修復・app-server の起動はしません。移動された `sqlite_home`、未対応のスキーマ・パス、曖昧な結合は unknown です。SQL 読み取りで既存 SHM の読み取りマークが更新される場合がありますが、行・スキーマを書き込まず、sidecar を意図的に作成しません。
|
|
310
|
+
|
|
311
|
+
収集はベストエフォートです。イベントの欠落・遅延・容量超過により、モデル履歴が不完全になる場合があります。`model_match`は保持された証拠の一致であり、すべてのリクエストで同じモデルを使用した証明ではありません。Codexの収集無効化、設定削除、または`--codex-native-metadata`なしの有効化でnativeメタデータへの同意も解除されます。Nodeやパッケージのパスを変更した場合は、収集を無効化して再度有効化し、コマンドを更新してください。利用不能・破損したストアは保持されます。キーを削除したり使用量をゼロと判断したりせず、ローカルで確認してください。
|
|
312
|
+
|
|
285
313
|
<a id="外部送信と自動共有の無効化"></a>
|
|
286
314
|
|
|
287
315
|
### Decisions API への送信範囲
|
package/docs/guide/ko.md
CHANGED
|
@@ -282,6 +282,34 @@ aptly budget status --client claude
|
|
|
282
282
|
|
|
283
283
|
새 HTTP 전 예산 거절은 캐시하지 않습니다. 검증 가능한 기존 기본 정책의 미지불 거절만 같은 ID로 다시 평가하며, 성공·보류·문맥 부족의 완료 결과와 `unknown`은 유지합니다. 한도 회복은 원래 retry 참조의 5분 만료나 프로세스 수명을 연장하지 않고 이력·권한 제약도 해제하지 않습니다. 임의의 과거 커스텀 정책 digest를 추측해 재사용하지 않으며 충돌·불명 결과를 새 ID나 원장 삭제로 우회하지 마십시오.
|
|
284
284
|
|
|
285
|
+
<a id="execution-statistics"></a>
|
|
286
|
+
|
|
287
|
+
### 실행 통계 (0.1.10부터)
|
|
288
|
+
|
|
289
|
+
실행 통계는 Aptly 0.1.10부터 지원합니다. 0.1.10 이상을 설치하거나 [패키지 업데이트](#패키지-업데이트) 안내에 따라 업그레이드한 뒤 아래 예제를 사용하십시오. 기존 Aptly 설정이 필요합니다. 초기 수집은 POSIX에서만 지원하며 Windows 통계 수집은 미지원입니다. Windows의 일반 Aptly 사용에는 영향이 없습니다.
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
aptly stats
|
|
293
|
+
aptly stats --today --client codex
|
|
294
|
+
aptly stats enable --client codex
|
|
295
|
+
aptly stats enable --client codex --codex-native-metadata
|
|
296
|
+
aptly stats disable --client codex
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
명령 형식은 `aptly stats [--today] [--client codex|claude|all]`, `aptly stats enable [--client] [--codex-native-metadata]`, `aptly stats disable [--client]`입니다. 수집은 기본적으로 꺼져 있고 postinstall에서도 자동 활성화하지 않습니다. enable은 Aptly 소유 명령 관찰자를 설치하고 별도의 `stats-ownership.json`에 기록하며 기존 receipt·MCP·launcher·키·예산·전송 설정은 유지합니다. 활성화 후 MCP와 호스트를 재시작하고 Codex에서는 `/hooks`의 native Hook 신뢰를 검토하십시오.
|
|
300
|
+
|
|
301
|
+
disable은 수집을 끄고 변경되지 않은 소유 관찰자만 제거합니다. 수정되거나 사용자 정의된 관찰자는 경고와 함께 보존하며 데이터와 키도 유지합니다. `remove`는 통계 소유 정의를 검증·제거하지만 데이터는 유지합니다. 별도로 관리하는 수동 관찰자나 사용자 정의 Hook은 자동 채택하지 않습니다.
|
|
302
|
+
|
|
303
|
+
비공개 상태는 예산 원장과 별개의 `stats.sqlite`, `stats-config.json`, `stats-key`(HMAC 비밀키)를 사용합니다. 키를 공유하지 마십시오. 기록에는 작업 원문·대화 기록·원시 ID·경로·오류·자격 증명이 없습니다. 통계 조회는 API·키·자격 저장소에 접근하지 않고 초기화나 알림도 실행하지 않습니다.
|
|
304
|
+
|
|
305
|
+
집계는 `model_match`, `model_mismatch`, `model_changed`, `unknown`, `pending`, `expired_pending`, `application_unconfirmed`를 표시하며 advisory는 별도로 표시합니다. `blocked`, `explicit_preserved`, `unbound`는 분모에서 제외합니다. 실제 적용 effort는 측정하지 않으며 설정 effort는 실제 effort가 아닙니다. Claude 별칭 `haiku`, `sonnet`, `opus`, `fable`는 실제 정식 모델로 해석할 수 없어 `unknown`입니다. 정확한 정식 모델만 지원하며 모델 관측이 모든 별칭의 일치를 보장하지 않습니다. 사용자 수용이나 품질을 증명하는 수치가 아닙니다.
|
|
306
|
+
|
|
307
|
+
직접 advisory·retry·native 연속성이 없는 새 unbound 호출은 대략적인 시간으로 결합하지 않습니다. `--today`는 바인딩 최초 생성일의 UTC 날짜를 사용합니다. 용량은 위임 10,000건과 자식 10,000건으로 고정되며 자동 정리하지 않습니다. 집계는 전체 누적이 아닌 보존된 기록 기준입니다. 용량 도달 시 새 ID를 버리고 도달 플래그를 표시합니다. 콜백 누락은 우회를 증명하지 않습니다. 토큰·비용 합계, 실시간 할당량이나 절감액은 제공하지 않습니다.
|
|
308
|
+
|
|
309
|
+
Codex native 메타데이터는 명시적 옵션이 없으면 꺼져 있습니다. 정확한 자식 ID로 SQLite native 메타데이터만 읽으며 대화 기록 조회·복구·app-server 실행은 하지 않습니다. 이전된 `sqlite_home`, 미지원 스키마·경로, 모호한 결합은 unknown입니다. SQL 읽기가 기존 SHM 읽기 표시를 갱신할 수 있지만 행·스키마를 쓰거나 sidecar를 의도적으로 생성하지 않습니다.
|
|
310
|
+
|
|
311
|
+
수집은 최선 노력 방식이므로 누락·지연·용량 초과로 모델 이력이 불완전할 수 있습니다. `model_match`는 보존된 증거의 일치이며 모든 요청이 해당 모델을 사용했다는 뜻이 아닙니다. Codex 수집 해제·설정 제거 또는 `--codex-native-metadata` 없는 활성화는 native 메타데이터 접근 동의도 해제합니다. Node나 패키지 경로가 바뀌면 수집을 해제한 뒤 다시 활성화하여 명령을 갱신하십시오. 사용할 수 없거나 손상된 저장소는 보존합니다. 키를 삭제하거나 사용량이 0이라고 판단하지 말고 로컬에서 검토하십시오.
|
|
312
|
+
|
|
285
313
|
<a id="외부-전송과-자동-공유-끄기"></a>
|
|
286
314
|
|
|
287
315
|
### Decisions API 전송 범위
|
package/docs/guide/zh-CN.md
CHANGED
|
@@ -282,6 +282,34 @@ aptly budget status --client claude
|
|
|
282
282
|
|
|
283
283
|
HTTP 之前产生的新预算拒绝不会缓存。只有可验证的既有默认策略中确定未付费的拒绝才会用同一 ID 重新评估,保留已完成的推荐、保留选择、上下文结果与 `unknown`。预算恢复不会延长原 retry 引用的 5 分钟期限或进程寿命,也不会解除历史或权限限制。不猜测任意历史自定义策略的 digest;请勿用新 ID 或删除账本绕过冲突及未知结果。
|
|
284
284
|
|
|
285
|
+
<a id="execution-statistics"></a>
|
|
286
|
+
|
|
287
|
+
### 执行统计(0.1.10 起)
|
|
288
|
+
|
|
289
|
+
执行统计从 Aptly 0.1.10 起提供。请安装支持的版本,或按照[软件包更新](#软件包更新)升级后使用以下示例。需要已有 Aptly 设置。初期仅支持 POSIX 数据收集,Windows 统计收集不受支持;Windows 上的常规 Aptly 使用不受影响。
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
aptly stats
|
|
293
|
+
aptly stats --today --client codex
|
|
294
|
+
aptly stats enable --client codex
|
|
295
|
+
aptly stats enable --client codex --codex-native-metadata
|
|
296
|
+
aptly stats disable --client codex
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
命令形式为 `aptly stats [--today] [--client codex|claude|all]`、`aptly stats enable [--client] [--codex-native-metadata]` 和 `aptly stats disable [--client]`。收集默认关闭,postinstall 也不会自动启用。enable 安装 Aptly 所有的命令观察器,并记录在独立的 `stats-ownership.json`;既有 receipt、MCP、launcher、密钥、预算和传输设置保持不变。启用后请重启 MCP 和宿主;Codex 还需在 `/hooks` 审核 native Hook 信任。
|
|
300
|
+
|
|
301
|
+
disable 关闭收集,只移除未修改的自有观察器。已修改或自定义的观察器会保留并给出警告;数据和密钥也会保留。`remove` 验证并移除统计功能拥有的定义,但保留数据。不会自动接管单独管理的收集器或自定义 Hook。
|
|
302
|
+
|
|
303
|
+
私有状态使用与预算账本分开的 `stats.sqlite`、`stats-config.json` 和 `stats-key`(HMAC 密钥)。请勿分享密钥。记录不包含任务原文、对话记录、原始 ID、路径、错误或凭据。读取统计不调用 API、不访问密钥或凭据存储,也不初始化或运行通知。
|
|
304
|
+
|
|
305
|
+
统计显示 `model_match`、`model_mismatch`、`model_changed`、`unknown`、`pending`、`expired_pending` 和 `application_unconfirmed`;advisory 单独显示。`blocked`、`explicit_preserved` 和 `unbound` 不计入分母。实际 effort 始终不测量,配置的 effort 并非实际值。Claude 别名 `haiku`、`sonnet`、`opus`、`fable` 无法解析为实际规范模型,因此为 `unknown`。仅支持精确的规范模型,观察到模型也不保证所有别名匹配。这些数字不能证明用户接受程度或质量。
|
|
306
|
+
|
|
307
|
+
直接 advisory、retry 和没有 native 连续性的新 unbound 调用不会按近似时间关联。`--today` 使用绑定首次创建时的 UTC 日期。容量固定为 10,000 条委派和 10,000 个 子项,不自动清理。计数只涵盖保留记录,并非历史总数;容量满时丢弃新身份并标记已达上限。缺少回调不能证明绕过。没有 token 或成本汇总、实时配额或节省金额。
|
|
308
|
+
|
|
309
|
+
Codex native 元数据默认关闭,只有显式选项才启用。它仅按精确子 ID 读取 SQLite native 元数据,不读取对话记录、不修复,也不启动 app-server。迁移过的 `sqlite_home`、不支持的 schema 或路径及有歧义的关联均为 unknown。SQL 读取可能更新现有 SHM 读取标记,但不写入行或 schema,也不主动创建 sidecar。
|
|
310
|
+
|
|
311
|
+
收集采用尽力而为方式。事件丢失、延迟或容量超限可能导致模型历史不完整。`model_match`仅表示保留证据一致,并不证明每次请求都使用该模型。禁用 Codex 收集、移除设置或不带 `--codex-native-metadata` 重新启用,均会撤销 native 元数据访问同意。Node 或软件包路径更改后,请禁用再启用收集以更新命令。不可用或损坏的存储会被保留;请在本地检查,不要删除密钥或推断使用量为零。
|
|
312
|
+
|
|
285
313
|
<a id="对外传输与关闭自动共享"></a>
|
|
286
314
|
|
|
287
315
|
### Decisions API 传输范围
|