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/src/setup.js CHANGED
@@ -2,7 +2,7 @@ import { lstatSync, readFileSync, mkdirSync, chmodSync, openSync, writeFileSync,
2
2
  import { homedir } from 'node:os';
3
3
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { randomUUID } from 'node:crypto';
5
+ import { randomUUID, randomBytes, createHash } from 'node:crypto';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { parse } from 'smol-toml';
8
8
  import { resolveCatalog } from './catalog.js';
@@ -11,6 +11,7 @@ import { Router, defaultPolicy } from './core.js';
11
11
  import { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
12
12
  import { assertPrivateStatePath } from './files.js';
13
13
  import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
14
+ import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatistics } from './statistics.js';
14
15
  const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
15
16
  const stringify = (value) => JSON.stringify(value, null, 2) + '\n';
16
17
  const fail = (code) => { throw new Error(code); };
@@ -358,8 +359,11 @@ function prepare(options, client, removing, edit) {
358
359
  privatePermissions(privateFile.path, 'private_file_permissions');
359
360
  observations.push(mcp, hooks, policy, manifest);
360
361
  const oldOwner = manifest.before === null ? undefined : ownership(json(manifest.before), client);
361
- if (removing && !oldOwner)
362
+ if (removing && !oldOwner) {
363
+ if (read(join(privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null)
364
+ fail('statistics_observers_present');
362
365
  return { changes, observations, dirs, result: { client, status: 'skipped', codes: ['no_owned_setup'] } };
366
+ }
363
367
  const hookValue = hook(client), hooksObject = json(hooks.before), entries = hooksArray(hooksObject);
364
368
  const config = client === 'codex' ? toml(mcp.before ?? '') : json(mcp.before), servers = map(config, client === 'codex' ? 'mcp_servers' : 'mcpServers');
365
369
  if (removing) {
@@ -409,6 +413,7 @@ function prepare(options, client, removing, edit) {
409
413
  policy.after = null;
410
414
  manifest.after = null;
411
415
  result.status = 'removed';
416
+ appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations);
412
417
  }
413
418
  else {
414
419
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
@@ -710,7 +715,7 @@ function execute(options, removing, edit, captured) {
710
715
  }
711
716
  return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
712
717
  }
713
- const codes = new Set(['unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
718
+ const codes = new Set(['statistics_requires_setup', 'statistics_policy_conflict', 'statistics_config_invalid', 'statistics_ownership_invalid', 'statistics_observers_present', 'statistics_key_missing', 'statistics_shared_state', 'statistics_platform_unsupported', 'statistics_invalid_options', 'statistics_observer_missing', 'unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
714
719
  function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
715
720
  export function setupHosts(options = {}) { return execute(options, false); }
716
721
  /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
@@ -894,3 +899,260 @@ export function showBudgetStatus(options = {}) {
894
899
  });
895
900
  return { status: clients.some(client => client.status === 'error') ? 'partial' : 'complete', clients };
896
901
  }
902
+ const STATISTICS_OWNERSHIP_FILE = 'stats-ownership.json';
903
+ function statisticsOwner(value, client) {
904
+ const valid = ['PostToolUse', 'PostModelRequest', 'SubagentStart', 'SubagentStop'];
905
+ if (value.schema_version !== 1 || value.kind !== 'aptly-statistics-ownership' || value.client !== client || typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory) || !object(value.hooks) || Object.keys(value.hooks).some(k => !valid.includes(k)) || Object.values(value.hooks).some(v => !object(v) || !Array.isArray(v.hooks)) || value.hooks_fingerprint !== createHash('sha256').update(JSON.stringify(value.hooks)).digest('hex'))
906
+ fail('statistics_ownership_invalid');
907
+ return value;
908
+ }
909
+ function statisticEntries(value, event, create = false) {
910
+ if (value.hooks === undefined && !create)
911
+ return [];
912
+ const events = map(value, 'hooks');
913
+ if (events[event] === undefined) {
914
+ if (!create)
915
+ return [];
916
+ events[event] = [];
917
+ }
918
+ if (!Array.isArray(events[event]))
919
+ fail('hook_shape_conflict');
920
+ return events[event];
921
+ }
922
+ function statisticsPolicy(options, client, requireRegistration = true) {
923
+ const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
924
+ if (requireRegistration) {
925
+ const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
926
+ const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
927
+ if (!object(entry))
928
+ fail('statistics_requires_setup');
929
+ if (entry.env?.APTLY_HOOK_POLICY_PATH !== policyPath)
930
+ fail('statistics_policy_conflict');
931
+ }
932
+ const loaded = loadAutomaticHookPolicy(policyPath);
933
+ if (!loaded.policy)
934
+ fail('statistics_requires_setup');
935
+ return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory };
936
+ }
937
+ function statisticsHooks(root, client, policyPath) {
938
+ const observer = join(root, 'dist', 'bin', 'aptly-observe.js');
939
+ if (read(observer).text === null)
940
+ fail('statistics_observer_missing');
941
+ for (const path of [process.execPath, observer, policyPath])
942
+ if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
943
+ fail('statistics_invalid_options');
944
+ const quote = (v) => "'" + v.replaceAll("'", "'\\''") + "'";
945
+ const command = [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
946
+ const handler = { type: 'command', command, timeout: 5, statusMessage: 'Aptly local execution statistics' };
947
+ const events = client === 'codex' ? ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'] : ['PostToolUse', 'SubagentStart', 'SubagentStop'];
948
+ return Object.fromEntries(events.map(event => [event, { ...(event === 'PostToolUse' ? { matcher: client === 'codex' ? '^(spawn_agent|collaborationspawn_agent|collaboration\\.spawn_agent)$' : '^(Agent|Task)$' } : {}), hooks: [{ ...handler }] }]));
949
+ }
950
+ function statisticsSnapshot(path) { const value = read(path); if (value.text !== null) {
951
+ privatePermissions(path, 'private_file_permissions');
952
+ if (lstatSync(path).nlink !== 1)
953
+ fail('unsafe_configuration_file');
954
+ } return { path, before: value.text, after: value.text, mode: value.mode }; }
955
+ function statisticsConfig(snapshot) {
956
+ if (snapshot.before === null)
957
+ return { schema_version: 1, enabled_clients: [] };
958
+ const value = parseStatisticsConfig(json(snapshot.before));
959
+ if (!value)
960
+ fail('statistics_config_invalid');
961
+ return value;
962
+ }
963
+ function possibleStatisticsObserver(entry) {
964
+ return object(entry) && Array.isArray(entry.hooks) && entry.hooks.some((h) => object(h) && h.type === 'command' && (h.statusMessage === 'Aptly local execution statistics' || (typeof h.command === 'string' && h.command.includes('aptly-observe.js'))));
965
+ }
966
+ function clearCodexMetadata(state, client) { if (client === 'codex') {
967
+ delete state.codex_native_metadata;
968
+ delete state.codex_home;
969
+ } }
970
+ function appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations) {
971
+ const paths = resolved(options, client), receipt = statisticsSnapshot(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
972
+ observations.push(receipt);
973
+ const stateDirectory = statisticsPolicy(options, client, false).stateDirectory;
974
+ const owned = receipt.before === null ? undefined : statisticsOwner(json(receipt.before), client);
975
+ if (owned && owned.state_directory !== stateDirectory)
976
+ fail('statistics_ownership_invalid');
977
+ const config = statisticsSnapshot(join(stateDirectory, STATISTICS_CONFIG_FILE));
978
+ observations.push(config);
979
+ if (owned) {
980
+ for (const [event, entry] of Object.entries(owned.hooks)) {
981
+ const list = statisticEntries(hooksObject, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
982
+ if (matches.length > 1 || (!matches.length && list.some(possibleStatisticsObserver)))
983
+ fail('managed_hook_changed');
984
+ for (let n = list.length - 1; n >= 0; n--)
985
+ if (isDeepStrictEqual(list[n], entry))
986
+ list.splice(n, 1);
987
+ }
988
+ receipt.after = null;
989
+ hooks.after = stringify(hooksObject);
990
+ }
991
+ if (config.before !== null) {
992
+ const state = statisticsConfig(config);
993
+ state.enabled_clients = state.enabled_clients.filter(c => c !== client);
994
+ clearCodexMetadata(state, client);
995
+ config.after = serializeStatisticsConfig(state);
996
+ }
997
+ for (const snap of [config, receipt])
998
+ if (snap.before !== snap.after)
999
+ changes.push(snap);
1000
+ }
1001
+ /** Explicit collection controls; legacy routing receipt and model/credential settings stay untouched. */
1002
+ export function setStatisticsCollection(enabled, options = {}) {
1003
+ const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
1004
+ if (typeof enabled !== 'boolean' || !clients.length || clients.some(c => !['codex', 'claude'].includes(c)) || options.automatic || options.mode || options.transmission || options.selectUnselectedOnly || (!enabled && options.codexNativeMetadata !== undefined) || options.codexNativeMetadata && !clients.includes('codex'))
1005
+ return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
1006
+ if (process.platform === 'win32')
1007
+ return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
1008
+ const states = new Set();
1009
+ const plans = clients.map(client => {
1010
+ try {
1011
+ if (!enabled) {
1012
+ const base = resolved(options, client);
1013
+ if (read(join(base.privateDir, 'auto-policy.json')).text === null && read(join(base.privateDir, STATISTICS_OWNERSHIP_FILE)).text === null && read(join(base.privateDir, 'state', STATISTICS_CONFIG_FILE)).text === null)
1014
+ return { changes: [], observations: [], dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
1015
+ }
1016
+ const paths = statisticsPolicy(options, client, enabled);
1017
+ if (enabled) {
1018
+ try {
1019
+ assertPrivateStatePath(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
1020
+ assertPrivateStatePath(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
1021
+ }
1022
+ catch {
1023
+ fail('private_directory_permissions');
1024
+ }
1025
+ }
1026
+ if (states.has(paths.stateDirectory))
1027
+ fail('statistics_shared_state');
1028
+ states.add(paths.stateDirectory);
1029
+ const observations = [], changes = [];
1030
+ const snap = (path, privateFile = true) => { const result = privateFile ? statisticsSnapshot(path) : (() => { const v = read(path); return { path, before: v.text, after: v.text, mode: v.mode }; })(); observations.push(result); return result; };
1031
+ const policy = snap(paths.policyPath);
1032
+ if (enabled) {
1033
+ snap(paths.mcpPath, false);
1034
+ const routingReceipt = snap(join(paths.privateDir, 'setup-ownership.json'));
1035
+ if (routingReceipt.before === null)
1036
+ fail('statistics_requires_setup');
1037
+ ownership(json(routingReceipt.before), client);
1038
+ }
1039
+ const hooks = snap(paths.hooksPath, false), config = snap(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
1040
+ let receipt, unreadableReceipt = false;
1041
+ try {
1042
+ receipt = snap(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
1043
+ }
1044
+ catch (error) {
1045
+ if (enabled || safeCode(error) !== 'private_file_permissions')
1046
+ throw error;
1047
+ unreadableReceipt = true;
1048
+ }
1049
+ if (!enabled && !unreadableReceipt && receipt.before === null && config.before === null)
1050
+ return { changes, observations, dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
1051
+ const key = enabled ? snap(join(paths.stateDirectory, STATISTICS_KEY_FILE)) : undefined;
1052
+ const value = json(hooks.before), originalHooks = structuredClone(value), state = statisticsConfig(config);
1053
+ let old, invalidReceipt = unreadableReceipt;
1054
+ if (receipt && receipt.before !== null)
1055
+ try {
1056
+ old = statisticsOwner(json(receipt.before), client);
1057
+ }
1058
+ catch (error) {
1059
+ if (enabled)
1060
+ throw error;
1061
+ invalidReceipt = true;
1062
+ }
1063
+ if (old && old.state_directory !== paths.stateDirectory) {
1064
+ if (enabled)
1065
+ fail('statistics_ownership_invalid');
1066
+ old = undefined;
1067
+ invalidReceipt = true;
1068
+ }
1069
+ let modified = invalidReceipt;
1070
+ if (old)
1071
+ for (const [event, entry] of Object.entries(old.hooks)) {
1072
+ const list = statisticEntries(value, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
1073
+ if (!matches.length) {
1074
+ if (enabled)
1075
+ fail('managed_hook_changed');
1076
+ if (list.some(possibleStatisticsObserver))
1077
+ modified = true;
1078
+ continue;
1079
+ }
1080
+ if (matches.length > 1) {
1081
+ if (enabled)
1082
+ fail('managed_hook_changed');
1083
+ modified = true;
1084
+ continue;
1085
+ }
1086
+ for (let n = list.length - 1; n >= 0; n--)
1087
+ if (isDeepStrictEqual(list[n], entry))
1088
+ list.splice(n, 1);
1089
+ }
1090
+ if (enabled) {
1091
+ if (key.before === null) {
1092
+ try {
1093
+ lstatSync(join(paths.stateDirectory, STATISTICS_DB_FILE));
1094
+ fail('statistics_key_missing');
1095
+ }
1096
+ catch (error) {
1097
+ if (error.code !== 'ENOENT')
1098
+ throw error;
1099
+ }
1100
+ key.after = randomBytes(32).toString('hex') + '\n';
1101
+ }
1102
+ else if (!/^[a-f0-9]{64}\n$/.test(key.before))
1103
+ fail('statistics_key_missing');
1104
+ state.enabled_clients = [...new Set([...state.enabled_clients, client])];
1105
+ if (client === 'codex')
1106
+ clearCodexMetadata(state, client);
1107
+ if (client === 'codex' && options.codexNativeMetadata) {
1108
+ if (state.codex_home !== undefined && state.codex_home !== paths.dir)
1109
+ fail('statistics_config_invalid');
1110
+ state.codex_native_metadata = true;
1111
+ state.codex_home = paths.dir;
1112
+ }
1113
+ const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
1114
+ const entries = statisticsHooks(root, client, paths.policyPath);
1115
+ for (const [event, entry] of Object.entries(entries)) {
1116
+ const list = statisticEntries(value, event, true);
1117
+ if (list.some(possibleStatisticsObserver))
1118
+ fail('statistics_observers_present');
1119
+ list.push(entry);
1120
+ }
1121
+ receipt.after = stringify({ schema_version: 1, kind: 'aptly-statistics-ownership', client, state_directory: paths.stateDirectory, hooks: entries, hooks_fingerprint: createHash('sha256').update(JSON.stringify(entries)).digest('hex') });
1122
+ }
1123
+ else {
1124
+ state.enabled_clients = state.enabled_clients.filter(c => c !== client);
1125
+ clearCodexMetadata(state, client);
1126
+ if (receipt)
1127
+ receipt.after = invalidReceipt ? receipt.before : null;
1128
+ }
1129
+ config.after = serializeStatisticsConfig(state);
1130
+ if (!isDeepStrictEqual(value, originalHooks))
1131
+ hooks.after = stringify(value);
1132
+ for (const item of [config, ...(key ? [key] : []), hooks, ...(receipt ? [receipt] : [])])
1133
+ if (item.before !== item.after)
1134
+ changes.push(item);
1135
+ const codes = [enabled ? 'statistics_enabled' : 'statistics_disabled', ...(modified ? ['statistics_observers_retained_modified'] : []), ...(enabled && client === 'codex' ? ['requires_hook_review'] : []), ...(enabled ? ['mcp_restart_required'] : [])];
1136
+ return { changes, observations, dirs: [], result: { client, status: changes.length ? 'configured' : 'unchanged', codes, ...(enabled && client === 'codex' ? { requires_hook_review: true } : {}) } };
1137
+ }
1138
+ catch (error) {
1139
+ return { changes: [], observations: [], dirs: [], result: errorResult(client, error) };
1140
+ }
1141
+ });
1142
+ if (enabled && plans.some(p => p.result.status === 'error'))
1143
+ return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
1144
+ return execute(options, false, undefined, plans);
1145
+ }
1146
+ /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
1147
+ export function showStatistics(options = {}, today = false) {
1148
+ const clients = options.clients ?? ['codex', 'claude'];
1149
+ if (process.platform === 'win32')
1150
+ return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
1151
+ return { clients: clients.map(client => { try {
1152
+ const path = statisticsPolicy(options, client);
1153
+ return { client, ...readStatistics({ stateDirectory: path.stateDirectory }, { client, today }) };
1154
+ }
1155
+ catch (error) {
1156
+ return { client, status: safeCode(error), collection: 'disabled' };
1157
+ } }) };
1158
+ }
@@ -0,0 +1,23 @@
1
+ /** The callback is supplied by the statistics store and uses its private installation key. */
2
+ export type CodexBridgeHash = (domain: 'session' | 'task_path', client: 'codex', value: string) => string;
3
+ export type CodexBridge = {
4
+ status: 'matched';
5
+ parentSessionHash: string;
6
+ taskPathHash: string;
7
+ } | {
8
+ status: 'unknown';
9
+ reason: 'metadata_unavailable';
10
+ };
11
+ /**
12
+ * Read exactly one native child metadata row. No transcript, model, or effort is read.
13
+ * Existing SQLite SHM read marks can change during a read; files are never repaired or created intentionally.
14
+ * The caller must pass only its explicit operator-selected home, never Hook-supplied paths.
15
+ * Pre/post identity checks cannot eliminate a malicious same-account path replacement race.
16
+ */
17
+ export declare function resolveCodexStatisticsBridge(options: {
18
+ codexHome: string;
19
+ childId: string;
20
+ parentId: string;
21
+ hash: CodexBridgeHash;
22
+ env?: NodeJS.ProcessEnv;
23
+ }): CodexBridge;
@@ -0,0 +1,121 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { parse } from 'smol-toml';
5
+ import { assertNoRedirectedAncestors, readRegularFile } from './files.js';
6
+ const unknown = { status: 'unknown', reason: 'metadata_unavailable' };
7
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
8
+ const pathPattern = /^\/root(?:\/[a-z0-9_]+)+$/;
9
+ const own = (s) => typeof process.getuid === 'function' && s.uid === process.getuid();
10
+ function safeFile(path) {
11
+ assertNoRedirectedAncestors(path);
12
+ const s = lstatSync(path);
13
+ if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || !own(s) || (s.mode & 0o022))
14
+ throw new Error('unsafe');
15
+ return { dev: s.dev, ino: s.ino };
16
+ }
17
+ function same(a, b) { return a.dev === b.dev && a.ino === b.ino; }
18
+ function optionalFile(path) {
19
+ try {
20
+ return safeFile(path);
21
+ }
22
+ catch (e) {
23
+ if (e.code === 'ENOENT')
24
+ return null;
25
+ throw e;
26
+ }
27
+ }
28
+ function header(path, identity) {
29
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
30
+ try {
31
+ const s = fstatSync(fd), bytes = Buffer.alloc(20);
32
+ if (!s.isFile() || s.nlink !== 1 || !own(s) || (s.mode & 0o022) || !same(identity, s) || readSync(fd, bytes, 0, 20, 0) !== 20 ||
33
+ bytes.subarray(0, 16).toString('binary') !== 'SQLite format 3\0' || bytes[18] !== bytes[19] || ![1, 2].includes(bytes[18]))
34
+ throw new Error('unsafe');
35
+ return bytes[18];
36
+ }
37
+ finally {
38
+ closeSync(fd);
39
+ }
40
+ }
41
+ function canonicalPath(value) {
42
+ return typeof value === 'string' && value.length <= 1024 && pathPattern.test(value) && !value.split('/').slice(2).includes('root');
43
+ }
44
+ /**
45
+ * Read exactly one native child metadata row. No transcript, model, or effort is read.
46
+ * Existing SQLite SHM read marks can change during a read; files are never repaired or created intentionally.
47
+ * The caller must pass only its explicit operator-selected home, never Hook-supplied paths.
48
+ * Pre/post identity checks cannot eliminate a malicious same-account path replacement race.
49
+ */
50
+ export function resolveCodexStatisticsBridge(options) {
51
+ try {
52
+ if (process.platform === 'win32' || typeof options?.hash !== 'function' || !uuid.test(options.childId) || !uuid.test(options.parentId) ||
53
+ typeof options.codexHome !== 'string' || !isAbsolute(options.codexHome) || resolve(options.codexHome) !== options.codexHome ||
54
+ (options.env ?? process.env).CODEX_SQLITE_HOME)
55
+ return unknown;
56
+ const home = options.codexHome;
57
+ assertNoRedirectedAncestors(home);
58
+ const directory = lstatSync(home);
59
+ if (!directory.isDirectory() || !own(directory) || (directory.mode & 0o022))
60
+ return unknown;
61
+ const config = join(home, 'config.toml'), configIdentity = optionalFile(config);
62
+ let configBytes;
63
+ if (configIdentity) {
64
+ configBytes = readRegularFile(config, { maxBytes: 1024 * 1024 });
65
+ const parsed = parse(new TextDecoder('utf-8', { fatal: true }).decode(configBytes));
66
+ if (Object.hasOwn(parsed, 'sqlite_home') || !same(configIdentity, safeFile(config)))
67
+ return unknown;
68
+ }
69
+ const dbPath = join(home, 'state_5.sqlite'), dbIdentity = safeFile(dbPath);
70
+ const walPath = `${dbPath}-wal`, shmPath = `${dbPath}-shm`, journalPath = `${dbPath}-journal`;
71
+ const wal = optionalFile(walPath), shm = optionalFile(shmPath);
72
+ if (optionalFile(journalPath))
73
+ return unknown;
74
+ const mode = header(dbPath, dbIdentity);
75
+ if ((mode === 2 && (!wal || !shm)) || (mode === 1 && (wal || shm)))
76
+ return unknown;
77
+ let db;
78
+ let row;
79
+ try {
80
+ db = new DatabaseSync(dbPath, { readOnly: true, allowExtension: false });
81
+ db.exec('PRAGMA query_only = ON; PRAGMA trusted_schema = OFF');
82
+ const schema = db.prepare("SELECT type FROM sqlite_schema WHERE name = 'threads'").all();
83
+ if (schema.length !== 1 || schema[0].type !== 'table')
84
+ return unknown;
85
+ const columns = db.prepare('PRAGMA table_info(threads)').all();
86
+ for (const [name, pk, notnull] of [['id', 1, 0], ['source', 0, 1], ['agent_path', 0, 0]]) {
87
+ const found = columns.filter(c => c.name === name);
88
+ if (found.length !== 1 || found[0].type !== 'TEXT' || found[0].pk !== pk || found[0].notnull !== notnull)
89
+ return unknown;
90
+ }
91
+ const rows = db.prepare('SELECT id, source, agent_path FROM threads WHERE id = ? LIMIT 2').all(options.childId);
92
+ if (rows.length !== 1)
93
+ return unknown;
94
+ row = rows[0];
95
+ }
96
+ finally {
97
+ db?.close();
98
+ }
99
+ const directoryAfter = lstatSync(home);
100
+ if (!same(dbIdentity, safeFile(dbPath)) || !same(directory, directoryAfter) || !own(directoryAfter) || (directoryAfter.mode & 0o022) ||
101
+ (wal ? !same(wal, safeFile(walPath)) : optionalFile(walPath) !== null) ||
102
+ (shm ? !same(shm, safeFile(shmPath)) : optionalFile(shmPath) !== null) || optionalFile(journalPath) ||
103
+ (configIdentity ? !same(configIdentity, safeFile(config)) || !configBytes.equals(readRegularFile(config, { maxBytes: 1024 * 1024 })) : optionalFile(config) !== null))
104
+ return unknown;
105
+ if (!row || row.id !== options.childId || typeof row.source !== 'string' || row.source.length > 65536 || !canonicalPath(row.agent_path))
106
+ return unknown;
107
+ const source = JSON.parse(row.source);
108
+ if (!source || typeof source !== 'object')
109
+ return unknown;
110
+ const spawn = source.subagent?.thread_spawn;
111
+ if (!spawn || spawn.parent_thread_id !== options.parentId || spawn.agent_path !== row.agent_path)
112
+ return unknown;
113
+ const parentSessionHash = options.hash('session', 'codex', options.parentId), taskPathHash = options.hash('task_path', 'codex', row.agent_path);
114
+ if (!/^[a-f0-9]{64}$/.test(parentSessionHash) || !/^[a-f0-9]{64}$/.test(taskPathHash))
115
+ return unknown;
116
+ return { status: 'matched', parentSessionHash, taskPathHash };
117
+ }
118
+ catch {
119
+ return unknown;
120
+ }
121
+ }
@@ -0,0 +1,2 @@
1
+ /** Metadata-only policy reader; deliberately has no provider or credential dependency. */
2
+ export declare function statisticsState(path: unknown): string | null;
@@ -0,0 +1,20 @@
1
+ import { isAbsolute, join } from 'node:path';
2
+ import { assertPrivateStatePath, readRegularFile } from './files.js';
3
+ import { isRecord } from './types.js';
4
+ /** Metadata-only policy reader; deliberately has no provider or credential dependency. */
5
+ export function statisticsState(path) {
6
+ try {
7
+ assertPrivateStatePath(path);
8
+ const value = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'));
9
+ if (!isRecord(value) || ![1, 2].includes(value.schema_version) || value.kind !== 'aptly-auto-hook' || value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' || !['defaults', 'advisory'].includes(String(value.mode)) || typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
10
+ return null;
11
+ const keys = ['schema_version', 'kind', 'mode', 'issuer', 'enabled', 'state_directory', ...(value.schema_version === 2 ? ['transmission'] : [])];
12
+ if (Object.keys(value).length !== keys.length || Object.keys(value).some(k => !keys.includes(k)) || value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(String(value.transmission)))
13
+ return null;
14
+ assertPrivateStatePath(join(value.state_directory, '.stats-check'));
15
+ return value.state_directory;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
@@ -0,0 +1,90 @@
1
+ import { type Client } from './types.ts';
2
+ export declare const STATISTICS_CONFIG_FILE = "stats-config.json";
3
+ export declare const STATISTICS_KEY_FILE = "stats-key";
4
+ export declare const STATISTICS_DATABASE_FILE = "stats.sqlite";
5
+ export declare const STATISTICS_DB_FILE = "stats.sqlite";
6
+ export declare const STATISTICS_CONFIG_VERSION = 1;
7
+ export interface StatisticsConfig {
8
+ schema_version: 1;
9
+ enabled_clients: Client[];
10
+ codex_native_metadata?: boolean;
11
+ codex_home?: string;
12
+ }
13
+ export interface StatisticsOptions {
14
+ stateDirectory: string;
15
+ now?: () => number;
16
+ maxDelegations?: number;
17
+ maxChildren?: number;
18
+ }
19
+ export type StatisticsHash = (domain: 'session' | 'tool' | 'child' | 'task_path' | 'request', client: Client, value: string) => string;
20
+ export interface StatisticsBridge {
21
+ parentSessionHash: string;
22
+ taskPathHash: string;
23
+ }
24
+ export interface StatisticsRecommendation {
25
+ client: Client;
26
+ sessionId?: string;
27
+ toolUseId?: string;
28
+ requestId?: string;
29
+ disposition: 'auto' | 'advisory' | 'blocked' | 'explicit_preserved' | 'unbound';
30
+ expected?: {
31
+ profileId: string;
32
+ model: string;
33
+ effort?: string;
34
+ catalogVersion?: string;
35
+ };
36
+ }
37
+ export type StatisticsResult = {
38
+ status: 'recorded' | 'ignored' | 'unavailable';
39
+ reason?: string;
40
+ };
41
+ export declare function parseStatisticsConfig(value: unknown): StatisticsConfig | null;
42
+ export declare function serializeStatisticsConfig(value: StatisticsConfig): string;
43
+ export declare function loadStatisticsConfig(options: StatisticsOptions): StatisticsConfig | null;
44
+ export declare function statisticsHash(key: string, domain: Parameters<StatisticsHash>[0], client: Client, value: string): string;
45
+ export declare function loadStatisticsHash(options: StatisticsOptions): StatisticsHash | null;
46
+ export declare function recordStatisticsRecommendation(options: StatisticsOptions, input: StatisticsRecommendation): StatisticsResult;
47
+ export declare function observeStatistics(options: StatisticsOptions, input: {
48
+ client: Client;
49
+ event: unknown;
50
+ }, bridge?: StatisticsBridge): StatisticsResult;
51
+ export type ModelState = 'model_match' | 'model_mismatch' | 'model_changed' | 'unknown' | 'pending' | 'expired_pending' | 'application_unconfirmed';
52
+ export declare function readStatistics(options: StatisticsOptions, filter?: {
53
+ client?: Client | 'all';
54
+ today?: boolean;
55
+ }): {
56
+ status: string;
57
+ scope: string;
58
+ semantics: string;
59
+ observation_completeness: string;
60
+ today_basis: string;
61
+ filter: {
62
+ client: "all" | Client;
63
+ today: boolean;
64
+ };
65
+ collection: {
66
+ codex: boolean;
67
+ claude: boolean;
68
+ };
69
+ capacity: {
70
+ delegations: number;
71
+ children: number;
72
+ reached: boolean;
73
+ };
74
+ delegations: number;
75
+ auto: Record<ModelState, number>;
76
+ advisory: Record<ModelState, number>;
77
+ blocked: number;
78
+ explicit_preserved: number;
79
+ unbound: number;
80
+ effort_actual_unknown: number;
81
+ application_confirmed: number;
82
+ unknown_alias_count: number;
83
+ model_observed: number;
84
+ model_comparable: number;
85
+ model_match_denominator: number;
86
+ observation_denominator: number;
87
+ usage_scope: string;
88
+ model_alias_scope: string;
89
+ counts_are_lifetime: boolean;
90
+ };