@eyeauras/insight-cli 0.6.4 → 0.7.0

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 (116) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +9 -7
  3. package/dist/src/activity-audit.d.ts +123 -0
  4. package/dist/src/activity-audit.js +310 -0
  5. package/dist/src/audit-commands.d.ts +10 -0
  6. package/dist/src/audit-commands.js +85 -0
  7. package/dist/src/audit-retention.d.ts +38 -0
  8. package/dist/src/audit-retention.js +106 -0
  9. package/dist/src/cli.js +11 -3
  10. package/dist/src/contexts.d.ts +29 -8
  11. package/dist/src/contexts.js +455 -90
  12. package/dist/src/cross-peer.d.ts +20 -0
  13. package/dist/src/cross-peer.js +53 -0
  14. package/dist/src/debugger-results.d.ts +2 -1
  15. package/dist/src/debugger-results.js +9 -4
  16. package/dist/src/debugger.js +3 -2
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/internal-timing.d.ts +8 -2
  20. package/dist/src/internal-timing.js +50 -7
  21. package/dist/src/lifecycle.d.ts +1 -1
  22. package/dist/src/native-merge-patches.js +20 -2
  23. package/dist/src/research.d.ts +11 -3
  24. package/dist/src/research.js +31 -4
  25. package/dist/src/storage-gc.js +429 -196
  26. package/dist/src/tool-runtime/run.js +24 -11
  27. package/dist/src/tool-runtime/supervisor.js +51 -9
  28. package/dist/src/transport.js +19 -10
  29. package/dist/src/workspace.d.ts +45 -1
  30. package/dist/src/workspace.js +135 -7
  31. package/package.json +1 -1
  32. package/references/agent-setup.md +11 -3
  33. package/references/debugger.md +5 -3
  34. package/references/extensions-and-sync.md +7 -6
  35. package/references/managed-runtime.md +4 -3
  36. package/references/native/InsightNativeCheckout.java +174 -15
  37. package/references/native/NATIVE-MERGE-NOTICE.txt +5 -1
  38. package/references/native-workflows.md +5 -3
  39. package/references/query-semantics.md +3 -2
  40. package/references/recovery.md +6 -0
  41. package/references/research.md +33 -2
  42. package/references/setup.md +9 -2
  43. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  44. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  45. package/skill-bundle/insight-binary/SKILL.md +1 -1
  46. package/skill-bundle/insight-capture/SKILL.md +1 -1
  47. package/skill-bundle/insight-cli/SKILL.md +9 -7
  48. package/skill-bundle/insight-cli/references/agent-setup.md +11 -3
  49. package/skill-bundle/insight-cli/references/managed-runtime.md +4 -3
  50. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  51. package/skill-bundle/insight-cli/references/setup.md +9 -2
  52. package/skill-bundle/insight-die/SKILL.md +1 -1
  53. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  54. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  55. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  56. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  57. package/skill-bundle/insight-frida/SKILL.md +1 -1
  58. package/skill-bundle/insight-ghidra/SKILL.md +4 -3
  59. package/skill-bundle/insight-ghidra/references/debugger.md +5 -3
  60. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +7 -6
  61. package/skill-bundle/insight-ghidra/references/managed-runtime.md +4 -3
  62. package/skill-bundle/insight-ghidra/references/native-workflows.md +5 -3
  63. package/skill-bundle/insight-ghidra/references/query-semantics.md +3 -2
  64. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  65. package/skill-bundle/insight-ghidra/references/research.md +33 -2
  66. package/skill-bundle/insight-ghidra/references/setup.md +9 -2
  67. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  68. package/skill-bundle/insight-interop/SKILL.md +1 -1
  69. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  70. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  71. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  72. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  73. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  74. package/skill-bundle/insight-overview/SKILL.md +1 -1
  75. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  76. package/skill-bundle/insight-re/SKILL.md +7 -1
  77. package/skill-bundle/insight-re/references/recovery.md +6 -0
  78. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  79. package/skill-bundle/insight-strace/SKILL.md +1 -1
  80. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  81. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  82. package/skill-bundle/manifest.json +1 -1
  83. package/skills/insight-artifacts/SKILL.md +1 -1
  84. package/skills/insight-artifacts/references/recovery.md +6 -0
  85. package/skills/insight-binary/SKILL.md +1 -1
  86. package/skills/insight-capture/SKILL.md +1 -1
  87. package/skills/insight-die/SKILL.md +1 -1
  88. package/skills/insight-dnspy/SKILL.md +1 -1
  89. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  90. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  91. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  92. package/skills/insight-frida/SKILL.md +1 -1
  93. package/skills/insight-ghidra/SKILL.md +4 -3
  94. package/skills/insight-ghidra/references/debugger.md +5 -3
  95. package/skills/insight-ghidra/references/extensions-and-sync.md +7 -6
  96. package/skills/insight-ghidra/references/managed-runtime.md +4 -3
  97. package/skills/insight-ghidra/references/native-workflows.md +5 -3
  98. package/skills/insight-ghidra/references/query-semantics.md +3 -2
  99. package/skills/insight-ghidra/references/recovery.md +6 -0
  100. package/skills/insight-ghidra/references/research.md +33 -2
  101. package/skills/insight-ghidra/references/setup.md +9 -2
  102. package/skills/insight-ilspy/SKILL.md +1 -1
  103. package/skills/insight-interop/SKILL.md +1 -1
  104. package/skills/insight-lldb/SKILL.md +1 -1
  105. package/skills/insight-llvm/SKILL.md +1 -1
  106. package/skills/insight-managed-heap/SKILL.md +1 -1
  107. package/skills/insight-managed-metadata/SKILL.md +1 -1
  108. package/skills/insight-mitmproxy/SKILL.md +1 -1
  109. package/skills/insight-overview/SKILL.md +1 -1
  110. package/skills/insight-procmon/SKILL.md +1 -1
  111. package/skills/insight-re/SKILL.md +7 -1
  112. package/skills/insight-re/references/recovery.md +6 -0
  113. package/skills/insight-sevenzip/SKILL.md +1 -1
  114. package/skills/insight-strace/SKILL.md +1 -1
  115. package/skills/insight-tshark/SKILL.md +1 -1
  116. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":1,"artifact":"ce6f430f05ce42ee60d9d43ddf0f5bb7eeaeaa4406e3af9a2e809837901f85aa"}
1
+ {"version":1,"artifact":"49ed891cefff58d12359131fb56461982e403b544ff7a15e74661553b6219e00"}
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: insight-cli
3
3
  description: Choose and prepare reverse-engineering capabilities from the insight-cli toolbox for binary, managed-code and runtime investigations. Use to discover the appropriate tool or its packaged skill before installing native runtimes.
4
4
  ---
5
5
 
6
- # insight-cli 0.6.4
6
+ # insight-cli 0.7.0
7
7
 
8
8
  If local help/status reports AppData or IPC access denied, retry that **read-only probe**
9
9
  with the agent host's normal permission escalation, then use that route for later authorized
@@ -23,10 +23,12 @@ in the agent's long-lived runtime. Reuse it across calls to avoid repeated front
23
23
  runtime is not needed to discover what a tool does.
24
24
  2. Use `insight-cli tools show <tool> --json` for tasks, supported inputs/platforms,
25
25
  dependencies and its skill path. Read that skill before preparing or using the tool.
26
- 3. Select a profile for execution. Run the selected application's `status` and generated
27
- `--help`. `install` prepares its private runtime; archives/offline and external paths
28
- are tool-specific and described in its skill. Update permission is required for tool
29
- preparation/execution and saved changes: `insight-cli permissions grant Update`.
26
+ 3. Select a profile for execution and read the selected capability's generated `--help`.
27
+ If `tools show` reports `runtime.statusCommand`, run that advertised readiness probe.
28
+ Follow its skill for any `install`, archives/offline or external-path setup. Capabilities
29
+ with `runtime.required: false` follow their own skill without separate runtime preparation.
30
+ Update permission is required for tool preparation/execution and saved changes:
31
+ `insight-cli permissions grant Update`.
30
32
  4. Answer the question with focused queries and ordinary project files. Follow results to
31
33
  useful detail; a large raw dump is not an interpretation. External tools remain welcome.
32
34
  5. Preserve completed files with `insight-cli artifacts save <path> --json` when a retained
@@ -48,6 +50,6 @@ Reuse existing session/target selectors before opening another copy. Read [setup
48
50
  for explicit later analysis and passive first-open progress (`ghidra progress`).
49
51
 
50
52
  Use generated help as the syntax authority. Catalog metadata describes shipped capabilities;
51
- profile runtime readiness comes from the selected tool's `status`. Unavailable profile/IPC
52
- access means execution readiness is unknown. Preserve work and diagnose access before trying
53
+ profile runtime readiness comes from its advertised `runtime.statusCommand`, when present.
54
+ Unavailable profile/IPC access means execution readiness is unknown. Preserve work and diagnose access before trying
53
55
  again; stopping a shared owner does not grant a denied agent access to it.
@@ -0,0 +1,123 @@
1
+ import { type AuditPolicy } from './audit-retention.js';
2
+ export { auditLimits } from './audit-retention.js';
3
+ export declare function auditHash(value: string): string;
4
+ export declare function auditErrorCode(error: unknown): string;
5
+ export interface AuditRecord extends Record<string, unknown> {
6
+ schema: 1;
7
+ sequence: number;
8
+ operationId: string;
9
+ command: string;
10
+ event: string;
11
+ at: string;
12
+ }
13
+ interface AuditSnapshot {
14
+ storeId: string | null;
15
+ count: number;
16
+ oldestSequence: number | null;
17
+ newestSequence: number | null;
18
+ prunedEvents: number;
19
+ }
20
+ export interface AuditPage extends AuditSnapshot {
21
+ schema: 1;
22
+ items: AuditRecord[];
23
+ hasMore: boolean;
24
+ nextBefore: number | null;
25
+ }
26
+ export interface AuditFilter {
27
+ limit?: number;
28
+ before?: number;
29
+ operationId?: string;
30
+ command?: string;
31
+ session?: string;
32
+ target?: string;
33
+ request?: string;
34
+ traceId?: string;
35
+ event?: string;
36
+ since?: number;
37
+ until?: number;
38
+ failures?: boolean;
39
+ }
40
+ /** Independent operational history, never recovery authority. No argument/result serialization. */
41
+ export declare class AuditStore {
42
+ readonly directory: string;
43
+ readonly path: string;
44
+ private readonly initialPolicy;
45
+ constructor(directory: string, limits?: {
46
+ events: number;
47
+ days: number;
48
+ databaseBytes?: number;
49
+ });
50
+ private open;
51
+ private insert;
52
+ append(operationId: string, command: string, event: string, raw?: unknown, scope?: unknown): void;
53
+ private metadata;
54
+ private snapshot;
55
+ list(filter?: AuditFilter): AuditPage;
56
+ status(): {
57
+ bytes: number | undefined;
58
+ retention: {
59
+ events: number;
60
+ days: number;
61
+ databaseBytes: number;
62
+ eventBytes: number;
63
+ sweepIntervalMs: number;
64
+ };
65
+ maintenance: {
66
+ autoVacuum: number;
67
+ journalMode: string;
68
+ sharedByProfile: boolean;
69
+ policy: AuditPolicy;
70
+ lastSweepMs: number;
71
+ runs: number;
72
+ lastRemoved: number;
73
+ schemaVersion: number;
74
+ } | {
75
+ autoVacuum: number;
76
+ journalMode: string;
77
+ sharedByProfile: boolean;
78
+ runs: number;
79
+ lastSweepMs: number;
80
+ lastRemoved: number;
81
+ schemaVersion: number;
82
+ };
83
+ unfinished: {
84
+ operationId: string;
85
+ command: string;
86
+ startedAtMs: number;
87
+ pid: unknown;
88
+ }[];
89
+ unfinishedMeaning: string;
90
+ storeId: string | null;
91
+ count: number;
92
+ oldestSequence: number | null;
93
+ newestSequence: number | null;
94
+ prunedEvents: number;
95
+ initialized: boolean;
96
+ } | {
97
+ initialized: boolean;
98
+ storeId: null;
99
+ count: number;
100
+ oldestSequence: null;
101
+ newestSequence: null;
102
+ prunedEvents: number;
103
+ retention: {
104
+ events: number;
105
+ days: number;
106
+ databaseBytes: number;
107
+ eventBytes: number;
108
+ sweepIntervalMs: number;
109
+ };
110
+ maintenance: {
111
+ schemaVersion: number;
112
+ runs: number;
113
+ lastSweepMs: number;
114
+ lastRemoved: number;
115
+ sharedByProfile: boolean;
116
+ };
117
+ unfinished: never[];
118
+ unfinishedMeaning: string;
119
+ };
120
+ }
121
+ export declare function bindAudit(raw: unknown): void;
122
+ export declare function auditEvent(event: string, raw?: unknown): void;
123
+ export declare function auditCommand<T>(store: AuditStore, command: string, options: unknown, action: () => Promise<T>, warn?: (code: string) => void): Promise<T>;
@@ -0,0 +1,310 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { randomUUID, createHash } from 'node:crypto';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { mkdirSync, lstatSync, chmodSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { performance } from 'node:perf_hooks';
7
+ import { CliError } from '@eyeauras/cli-factory';
8
+ import { diagnosticFailure } from './diagnostic-error.js';
9
+ import { auditLimits, auditPolicy, auditUnavailable, initializeRetention, retentionState, auditStorageMode, requireAuditStorageMode, collectAudit, acquireAuditWriter } from './audit-retention.js';
10
+ export { auditLimits } from './audit-retention.js';
11
+ const applicationId = 0x49534155;
12
+ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
13
+ const kinds = new Set(['audit.gc', 'command.started', 'command.succeeded', 'command.failed', 'transport.failed', 'request.state', 'gc.started', 'gc.finished', 'gc.failed', 'gc.category', 'gc.retained', 'gc.remove.started', 'gc.remove.succeeded', 'gc.remove.failed', 'gc.remove.planned', 'gc.release.started', 'gc.release.succeeded', 'gc.release.failed']);
14
+ const categories = new Set(['native-checkouts', 'duplicate-exports', 'temporary-caches', 'detached-projects', 'unreferenced-snapshots']);
15
+ const reasons = new Set(['live-or-uncertain', 'ownership-unproved', 'referenced', 'private-work', 'capture-unproved', 'link-or-special', 'removal-failed', 'other']);
16
+ const resourceTypes = new Set(['snapshot', 'native-view', 'project', 'export', 'cache', 'other']);
17
+ const states = new Set(['accepted', 'running', 'applied', 'failed', 'unknown', 'ready', 'opening', 'stopped', 'needs_recovery', 'planned', 'complete']);
18
+ const fsCodes = new Set(['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'ENOENT', 'EMFILE', 'ENFILE', 'EBUSY', 'ERR_SQLITE_ERROR', 'ERR_INVALID_STATE']);
19
+ function field(value, key) { try {
20
+ return value && typeof value === 'object' ? value[key] : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ } }
25
+ export function auditHash(value) { return createHash('sha256').update(value).digest('hex'); }
26
+ export function auditErrorCode(error) { const code = field(error, 'code'); return typeof code === 'string' && fsCodes.has(code) ? code : 'unavailable'; }
27
+ function correlation(raw) {
28
+ const out = {};
29
+ for (const [key, re] of Object.entries({ session: /^s_[a-f0-9-]{36}$/i, target: /^t_[a-f0-9]{32}$/i, context: /^c_[a-f0-9-]{36}$/i, request: /^[qa]_[a-f0-9-]{36}$/i, traceId: uuid, gcId: uuid })) {
30
+ const value = field(raw, key);
31
+ if (typeof value === 'string' && re.test(value))
32
+ out[key] = value;
33
+ }
34
+ return out;
35
+ }
36
+ // Request provenance comes from committed ledger notifications, never caller/result shape.
37
+ function commandCorrelation(raw) { const out = correlation(raw); delete out.request; return out; }
38
+ function details(raw) {
39
+ const out = { ...correlation(raw) };
40
+ for (const key of ['callerHash', 'resourceHash']) {
41
+ const value = field(raw, key);
42
+ if (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
43
+ out[key] = value;
44
+ }
45
+ for (const key of ['bytes', 'items', 'retainedCount', 'durationMs', 'pid', 'removedEvents', 'expiredEvents', 'eventsBefore', 'eventsAfter', 'liveBytesBefore', 'liveBytesAfterPrune']) {
46
+ const value = field(raw, key);
47
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER)
48
+ out[key] = value;
49
+ }
50
+ const state = field(raw, 'state'), reason = field(raw, 'reason'), category = field(raw, 'category'), dryRun = field(raw, 'dryRun'), outcome = field(raw, 'outcome');
51
+ if (typeof state === 'string' && states.has(state))
52
+ out.state = state;
53
+ if (typeof reason === 'string' && reasons.has(reason))
54
+ out.reason = reason;
55
+ if (typeof category === 'string' && categories.has(category))
56
+ out.category = category;
57
+ if (typeof dryRun === 'boolean')
58
+ out.dryRun = dryRun;
59
+ if (outcome === 'success' || outcome === 'failure')
60
+ out.outcome = outcome;
61
+ const artifact = field(raw, 'artifact'), resourceType = field(raw, 'resourceType');
62
+ if (typeof artifact === 'string' && /^(snapshot|native):[a-f0-9]{64}$/.test(artifact))
63
+ out.artifact = artifact;
64
+ if (typeof resourceType === 'string' && resourceTypes.has(resourceType))
65
+ out.resourceType = resourceType;
66
+ const automatic = field(raw, 'automatic'), gcTrigger = field(raw, 'gcTrigger');
67
+ if (typeof automatic === 'boolean')
68
+ out.automatic = automatic;
69
+ if (typeof gcTrigger === 'string' && ['periodic', 'event-limit', 'byte-limit', 'multiple'].includes(gcTrigger))
70
+ out.gcTrigger = gcTrigger;
71
+ const error = field(raw, 'error');
72
+ if (error !== undefined)
73
+ out.failure = diagnosticFailure(error) ?? { code: auditErrorCode(error) };
74
+ return out;
75
+ }
76
+ function readRecord(row) {
77
+ const text = String(row.data);
78
+ if (Buffer.byteLength(text) > auditLimits.eventBytes)
79
+ unavailable();
80
+ const raw = JSON.parse(text), operationId = field(raw, 'operationId'), command = field(raw, 'command'), event = field(raw, 'event'), at = field(raw, 'at'), sequence = Number(row.seq);
81
+ if (field(raw, 'schema') !== 1 || typeof operationId !== 'string' || !uuid.test(operationId) || operationId !== row.operation_id || typeof command !== 'string' || !/^[a-z0-9][a-z0-9 -]{0,159}$/.test(command) || command !== row.command || typeof event !== 'string' || !kinds.has(event) || event !== row.event || typeof at !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(at) || !Number.isSafeInteger(sequence) || sequence < 1)
82
+ unavailable();
83
+ const result = { schema: 1, sequence, operationId, command, event, at, ...details(raw) }, failure = field(raw, 'failure');
84
+ if (failure !== undefined) {
85
+ const code = field(failure, 'code');
86
+ result.failure = typeof code === 'string' ? (diagnosticFailure(new CliError('Recorded failure', { code, result: { transport: field(failure, 'transport') } })) ?? { code: fsCodes.has(code) ? code : 'unavailable' }) : { code: 'unavailable' };
87
+ }
88
+ return result;
89
+ }
90
+ function unavailable() { return auditUnavailable(); }
91
+ function stat(path) { try {
92
+ return lstatSync(path);
93
+ }
94
+ catch (error) {
95
+ if (field(error, 'code') === 'ENOENT')
96
+ return;
97
+ throw error;
98
+ } }
99
+ /** Independent operational history, never recovery authority. No argument/result serialization. */
100
+ export class AuditStore {
101
+ directory;
102
+ path;
103
+ initialPolicy;
104
+ constructor(directory, limits = auditLimits) {
105
+ this.directory = directory;
106
+ this.path = join(directory, 'activity.sqlite');
107
+ this.initialPolicy = auditPolicy(limits);
108
+ }
109
+ open(write) {
110
+ const existing = stat(this.directory);
111
+ if (!existing && !write)
112
+ return;
113
+ if (!existing)
114
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
115
+ const dir = stat(this.directory), file = stat(this.path);
116
+ if (!dir?.isDirectory() || dir.isSymbolicLink() || file && (!file.isFile() || file.isSymbolicLink() || file.nlink !== 1))
117
+ unavailable();
118
+ if (!file && !write)
119
+ return;
120
+ let db;
121
+ try {
122
+ db = new DatabaseSync(this.path, { readOnly: !write });
123
+ db.exec('PRAGMA busy_timeout=3000;');
124
+ db.exec('BEGIN');
125
+ const version = Number(db.prepare('PRAGMA user_version').get()?.user_version), app = Number(db.prepare('PRAGMA application_id').get()?.application_id), foreign = version === 0 && app === 0 && Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").get());
126
+ db.exec('END');
127
+ if (foreign)
128
+ unavailable();
129
+ if (write && version === 0 && app === 0) {
130
+ db.exec('PRAGMA auto_vacuum=FULL; PRAGMA synchronous=FULL; BEGIN IMMEDIATE;');
131
+ const currentVersion = Number(db.prepare('PRAGMA user_version').get()?.user_version);
132
+ if (currentVersion === 0) {
133
+ if (db.prepare("SELECT name FROM sqlite_master WHERE type='table'").get())
134
+ unavailable();
135
+ db.exec(`
136
+ CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
137
+ CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT,at_ms INTEGER NOT NULL,operation_id TEXT NOT NULL,event TEXT NOT NULL,command TEXT NOT NULL,session TEXT,target TEXT,request TEXT,caller_hash TEXT,outcome TEXT,data TEXT NOT NULL CHECK(length(data)<=4096));
138
+ CREATE INDEX IF NOT EXISTS events_operation ON events(operation_id,seq);
139
+ CREATE INDEX IF NOT EXISTS events_session ON events(session,operation_id);
140
+ CREATE INDEX IF NOT EXISTS events_target ON events(target,operation_id);
141
+ CREATE INDEX IF NOT EXISTS events_request ON events(request,caller_hash);
142
+ CREATE INDEX IF NOT EXISTS events_at ON events(at_ms);
143
+ PRAGMA application_id=${applicationId}; PRAGMA user_version=1;`);
144
+ db.prepare('INSERT OR IGNORE INTO metadata VALUES(?,?)').run('storeId', randomUUID());
145
+ db.prepare('INSERT OR IGNORE INTO metadata VALUES(?,?)').run('prunedEvents', '0');
146
+ initializeRetention(db, this.initialPolicy, Date.now());
147
+ }
148
+ else if (![1, 2].includes(currentVersion) || Number(db.prepare('PRAGMA application_id').get()?.application_id) !== applicationId)
149
+ unavailable();
150
+ db.exec('COMMIT');
151
+ }
152
+ else if (![1, 2].includes(version) || app !== applicationId)
153
+ unavailable();
154
+ this.metadata(db);
155
+ if (write) {
156
+ requireAuditStorageMode(db);
157
+ if (Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2)
158
+ retentionState(db);
159
+ chmodSync(this.path, 0o600);
160
+ db.exec('PRAGMA synchronous=FULL;');
161
+ }
162
+ else if (Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2)
163
+ retentionState(db);
164
+ return db;
165
+ }
166
+ catch (error) {
167
+ db?.close();
168
+ throw error;
169
+ }
170
+ }
171
+ insert(db, operationId, command, event, raw, scope, at) {
172
+ const data = { schema: 1, operationId, command, event, at: new Date(at).toISOString(), ...details(scope), ...details(raw), pid: process.pid }, text = JSON.stringify(data);
173
+ if (Buffer.byteLength(text) > auditLimits.eventBytes)
174
+ throw new Error('Internal audit event exceeds its bound.');
175
+ const value = (key) => typeof data[key] === 'string' ? data[key] : null;
176
+ return Number(db.prepare('INSERT INTO events(at_ms,operation_id,event,command,session,target,request,caller_hash,outcome,data,writer_version) VALUES(?,?,?,?,?,?,?,?,?,?,2)').run(at, operationId, event, command, value('session'), value('target'), value('request'), value('callerHash'), value('outcome'), text).lastInsertRowid);
177
+ }
178
+ append(operationId, command, event, raw = {}, scope = {}) {
179
+ if (!uuid.test(operationId) || !kinds.has(event) || !/^[a-z0-9][a-z0-9 -]{0,159}$/.test(command))
180
+ throw new Error('Invalid internal audit event.');
181
+ const db = this.open(true);
182
+ try {
183
+ acquireAuditWriter(db);
184
+ const metadata = this.metadata(db), version = Number(db.prepare('PRAGMA user_version').get()?.user_version);
185
+ requireAuditStorageMode(db);
186
+ if (version === 1)
187
+ initializeRetention(db, this.initialPolicy, 0);
188
+ else if (version !== 2)
189
+ unavailable();
190
+ const state = retentionState(db);
191
+ const at = Date.now(), sequence = this.insert(db, operationId, command, event, raw, scope, at);
192
+ collectAudit(db, at, sequence, metadata.prunedEvents, state, data => this.insert(db, operationId, command, 'audit.gc', data, scope, at));
193
+ db.exec('COMMIT');
194
+ }
195
+ finally {
196
+ db.close();
197
+ }
198
+ }
199
+ metadata(db) {
200
+ const storeId = db.prepare("SELECT value FROM metadata WHERE key='storeId'").get()?.value, rawPruned = db.prepare("SELECT value FROM metadata WHERE key='prunedEvents'").get()?.value;
201
+ if (typeof storeId !== 'string' || !uuid.test(storeId) || typeof rawPruned !== 'string' || !/^\d+(?:\.0+)?$/.test(rawPruned) || !Number.isSafeInteger(Number(rawPruned)))
202
+ unavailable();
203
+ return { storeId, prunedEvents: Number(rawPruned) };
204
+ }
205
+ snapshot(db) {
206
+ const range = db.prepare('SELECT count(*) count,min(seq) oldestSequence,max(seq) newestSequence FROM events').get();
207
+ return { ...this.metadata(db), count: Number(range.count), oldestSequence: range.oldestSequence === null ? null : Number(range.oldestSequence), newestSequence: range.newestSequence === null ? null : Number(range.newestSequence) };
208
+ }
209
+ list(filter = {}) {
210
+ const limit = filter.limit ?? 50;
211
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10000)
212
+ throw new CliError('Audit limit must be 1–10000.', { code: 'audit.invalid' });
213
+ let db;
214
+ try {
215
+ db = this.open(false);
216
+ if (!db)
217
+ return { schema: 1, storeId: null, count: 0, oldestSequence: null, newestSequence: null, prunedEvents: 0, items: [], hasMore: false, nextBefore: null };
218
+ db.exec('BEGIN');
219
+ const snapshot = this.snapshot(db), clauses = [], values = [];
220
+ const add = (sql, value) => { if (value !== undefined) {
221
+ clauses.push(sql);
222
+ values.push(value);
223
+ } };
224
+ add('seq<?', filter.before);
225
+ add('operation_id=?', filter.operationId);
226
+ add('command=?', filter.command);
227
+ add('event=?', filter.event);
228
+ add('at_ms>=?', filter.since);
229
+ add('at_ms<=?', filter.until);
230
+ for (const key of ['session', 'target'])
231
+ add(`operation_id IN (SELECT operation_id FROM events WHERE ${key}=?)`, filter[key]);
232
+ if (filter.request !== undefined) {
233
+ clauses.push('operation_id IN (SELECT operation_id FROM events WHERE request=? OR caller_hash=?)');
234
+ values.push(filter.request, auditHash(filter.request));
235
+ }
236
+ add("operation_id IN (SELECT operation_id FROM events WHERE json_extract(data,'$.traceId')=?)", filter.traceId);
237
+ if (filter.failures)
238
+ clauses.push("outcome='failure'");
239
+ const rows = db.prepare(`SELECT seq,operation_id,event,command,data FROM events ${clauses.length ? 'WHERE ' + clauses.join(' AND ') : ''} ORDER BY seq DESC LIMIT ?`).all(...values, limit + 1), hasMore = rows.length > limit;
240
+ const items = rows.slice(0, limit).map(row => readRecord(row));
241
+ db.exec('COMMIT');
242
+ return { schema: 1, ...snapshot, items, hasMore, nextBefore: hasMore ? items.at(-1).sequence : null };
243
+ }
244
+ catch {
245
+ return unavailable();
246
+ }
247
+ finally {
248
+ db?.close();
249
+ }
250
+ }
251
+ status() {
252
+ let db;
253
+ try {
254
+ db = this.open(false);
255
+ if (!db)
256
+ return { initialized: false, storeId: null, count: 0, oldestSequence: null, newestSequence: null, prunedEvents: 0, retention: { ...auditLimits, ...this.initialPolicy }, maintenance: { schemaVersion: 2, runs: 0, lastSweepMs: 0, lastRemoved: 0, sharedByProfile: true }, unfinished: [], unfinishedMeaning: 'No terminal record retained; this does not prove an operation is still running.' };
257
+ db.exec('BEGIN');
258
+ const check = db.prepare('PRAGMA quick_check(1)').get();
259
+ if (!check || Object.values(check)[0] !== 'ok')
260
+ unavailable();
261
+ const unfinished = db.prepare("SELECT s.seq,s.operation_id,s.command,s.event,s.data FROM events s WHERE event='command.started' AND NOT EXISTS(SELECT 1 FROM events e WHERE e.operation_id=s.operation_id AND e.event IN ('command.succeeded','command.failed')) ORDER BY seq DESC LIMIT 20").all().map(row => { const record = readRecord(row); return { operationId: record.operationId, command: record.command, startedAtMs: Date.parse(record.at), pid: record.pid }; });
262
+ const result = { initialized: true, ...this.snapshot(db), bytes: stat(this.path)?.size, retention: { ...auditLimits, ...(Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2 ? retentionState(db).policy : this.initialPolicy) }, maintenance: { schemaVersion: Number(db.prepare('PRAGMA user_version').get()?.user_version), ...(Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2 ? retentionState(db) : { runs: 0, lastSweepMs: 0, lastRemoved: 0 }), sharedByProfile: true, ...auditStorageMode(db) }, unfinished, unfinishedMeaning: 'No terminal record retained; this does not prove an operation is still running.' };
263
+ db.exec('COMMIT');
264
+ return result;
265
+ }
266
+ catch {
267
+ return unavailable();
268
+ }
269
+ finally {
270
+ db?.close();
271
+ }
272
+ }
273
+ }
274
+ const active = new AsyncLocalStorage();
275
+ export function bindAudit(raw) { const context = active.getStore(); if (context)
276
+ Object.assign(context.scope, correlation(raw)); }
277
+ export function auditEvent(event, raw = {}) {
278
+ const context = active.getStore();
279
+ if (!context || context.disabled)
280
+ return;
281
+ try {
282
+ context.store.append(context.operationId, context.command, event, raw, context.scope);
283
+ }
284
+ catch (error) {
285
+ context.disabled = true;
286
+ try {
287
+ context.warn(auditErrorCode(error));
288
+ }
289
+ catch { }
290
+ }
291
+ }
292
+ export async function auditCommand(store, command, options, action, warn = () => { }) {
293
+ const operationId = randomUUID(), started = performance.now(), scope = commandCorrelation(options), request = field(options, 'requestId');
294
+ if (typeof request === 'string' && request.length <= 4096)
295
+ scope.callerHash = auditHash(request);
296
+ return active.run({ store, operationId, command, scope, warn, disabled: false }, async () => {
297
+ auditEvent('command.started');
298
+ try {
299
+ const value = await action();
300
+ Object.assign(scope, commandCorrelation(value));
301
+ auditEvent('command.succeeded', { durationMs: performance.now() - started, outcome: 'success', state: field(value, 'state'), bytes: field(value, 'bytes'), retainedCount: field(value, 'retainedCount') });
302
+ return value;
303
+ }
304
+ catch (error) {
305
+ Object.assign(scope, commandCorrelation(field(error, 'result')));
306
+ auditEvent('command.failed', { durationMs: performance.now() - started, outcome: 'failure', error });
307
+ throw error;
308
+ }
309
+ });
310
+ }
@@ -0,0 +1,10 @@
1
+ import { type CommandContext, type CommandDefinition, type CommandInput } from '@eyeauras/cli-factory';
2
+ import { AuditStore } from './activity-audit.js';
3
+ /** Factory still owns admission, parsing, permissions, I/O and IPC. Only admitted handlers are wrapped. */
4
+ export declare class ActivityAudit {
5
+ private readonly failures;
6
+ store(c: CommandContext): AuditStore;
7
+ run<T>(c: CommandContext, name: string, input: CommandInput, action: () => Promise<T>): Promise<T>;
8
+ wrap(entry: CommandDefinition, parents?: string[]): CommandDefinition;
9
+ commands(): CommandDefinition;
10
+ }
@@ -0,0 +1,85 @@
1
+ import { command, Permission, CliError } from '@eyeauras/cli-factory';
2
+ import { join, resolve } from 'node:path';
3
+ import { open } from 'node:fs/promises';
4
+ import { AuditStore, auditCommand } from './activity-audit.js';
5
+ function invalid(message) { throw new CliError(message, { code: 'audit.invalid' }); }
6
+ function integer(value, max) { const n = Number(value); if (!Number.isSafeInteger(n) || n < 1 || n > max)
7
+ invalid('Audit cursor/limit is outside its supported bound.'); return n; }
8
+ function date(value) { if (value === undefined)
9
+ return; const text = String(value); if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?(?:Z|[+-]\d\d:\d\d)$/.test(text))
10
+ invalid('Use an ISO timestamp with a timezone.'); const n = Date.parse(text); if (!Number.isFinite(n))
11
+ invalid('Invalid audit timestamp.'); return n; }
12
+ const queryOptions = [{ flags: '--limit <count>', description: 'Newest matching events (1–200)', defaultValue: 50 }, { flags: '--before <sequence>', description: 'Exclusive sequence cursor from the previous page' },
13
+ { flags: '--since <time>', description: 'Inclusive ISO timestamp with timezone' }, { flags: '--until <time>', description: 'Inclusive ISO timestamp with timezone' },
14
+ { flags: '--command <name>', description: 'Exact command, such as ghidra gc' }, { flags: '--session <id>', description: 'Include attempts linked to this session' },
15
+ { flags: '--target <id>', description: 'Include attempts linked to this target' }, { flags: '--request <id>', description: 'Internal request ID or original caller request ID' },
16
+ { flags: '--trace <id>', description: 'Include attempts linked to a transport traceId' },
17
+ { flags: '--event <kind>', description: 'Exact event kind, such as audit.gc' },
18
+ { flags: '--failures', description: 'Only failure events' }];
19
+ function filter(o, max = 200) {
20
+ const result = { limit: integer(o.limit ?? 50, max), since: date(o.since), until: date(o.until), failures: Boolean(o.failures) };
21
+ if (result.since !== undefined && result.until !== undefined && result.since > result.until)
22
+ invalid('--since must not be later than --until.');
23
+ if (o.before !== undefined)
24
+ result.before = integer(o.before, Number.MAX_SAFE_INTEGER);
25
+ if (o.trace !== undefined) {
26
+ const value = String(o.trace);
27
+ if (!/^[a-f0-9-]{36}$/i.test(value))
28
+ invalid('Use a traceId from the command error.');
29
+ result.traceId = value;
30
+ }
31
+ for (const key of ['command', 'session', 'target', 'request', 'event'])
32
+ if (o[key] !== undefined) {
33
+ const value = String(o[key]);
34
+ if (!value || value.length > 256)
35
+ invalid('Audit filter exceeds its bound.');
36
+ result[key] = value;
37
+ }
38
+ return result;
39
+ }
40
+ /** Factory still owns admission, parsing, permissions, I/O and IPC. Only admitted handlers are wrapped. */
41
+ export class ActivityAudit {
42
+ failures = new Map();
43
+ store(c) { return new AuditStore(join(c.appArguments.AppDataDirectory, 'audit')); }
44
+ run(c, name, input, action) {
45
+ let warned = false;
46
+ const store = this.store(c);
47
+ return auditCommand(store, name, { session: input.options.session ?? input.args.session, target: input.options.target ?? input.args.target, requestId: input.options.requestId }, action, code => {
48
+ this.failures.set(store.directory, { at: new Date().toISOString(), code });
49
+ if (warned)
50
+ return;
51
+ warned = true;
52
+ // stderr is available in human/JSON/RPC modes; never write diagnostics into protocol stdout.
53
+ try {
54
+ c.io.error.write('Insight audit unavailable (' + code + '); command outcome is unchanged. Inspect audit status.\n');
55
+ }
56
+ catch { }
57
+ });
58
+ }
59
+ wrap(entry, parents = []) {
60
+ const path = [...parents, entry.name.split(' ')[0]], run = entry.run;
61
+ return { ...entry, ...(entry.children ? { children: entry.children.map(child => this.wrap(child, path)) } : {}), ...(run ? { run: (input, c) => this.run(c, path.join(' '), input, async () => run(input, c)) } : {}) };
62
+ }
63
+ commands() {
64
+ return command('audit', 'Inspect the local activity audit without starting tools', [
65
+ command('status', 'Read audit health, retention and attempts lacking a recorded outcome', (_i, c) => ({ schema: 1, path: this.store(c).path, ...this.store(c).status(), lastWriteFailure: this.failures.get(this.store(c).directory) ?? null,
66
+ coverage: { admittedServiceHandlers: true, requestStateTransitions: true, gcActions: true, transportFailures: true, authCallbacks: true, factoryParsingAndPermissionRefusals: false, factoryProfileCommands: false, packageMetadata: false }, authority: 'diagnostic history only; never authorizes replay or cleanup' }), { permission: Permission.ReadOnly }),
67
+ command('list', 'Read recent activity with stable sequence pagination', ({ options: o }, c) => this.store(c).list(filter(o)), { permission: Permission.ReadOnly, options: queryOptions }),
68
+ command('show <operation>', 'Read events for one command attempt', ({ args, options: o }, c) => { const operation = String(args.operation); if (!/^[a-f0-9-]{36}$/i.test(operation))
69
+ invalid('Use an operationId from audit list.'); return this.store(c).list({ ...filter(o), operationId: operation }); }, { permission: Permission.ReadOnly, options: queryOptions }),
70
+ command('export', 'Write one bounded sanitized page to a new private JSON file', async ({ options: o }, c) => {
71
+ const page = this.store(c).list(filter(o, 10000)), path = resolve(c.cwd, String(o.output)), document = JSON.stringify({ exportSchema: 1, ...page }, null, 2) + '\n';
72
+ // wx refuses both existing files and symlinks. An incomplete export is preserved for diagnosis.
73
+ const file = await open(path, 'wx', 0o600);
74
+ try {
75
+ await file.writeFile(document);
76
+ await file.sync();
77
+ }
78
+ finally {
79
+ await file.close();
80
+ }
81
+ return { path, events: page.items.length, hasMore: page.hasMore, nextBefore: page.nextBefore, storeId: page.storeId };
82
+ }, { permission: Permission.Update, options: [...queryOptions.filter(o => !o.flags.startsWith('--limit')), { flags: '--limit <count>', description: 'Export at most 10000 events', defaultValue: 1000 }, { flags: '--output <path>', description: 'New JSON file; never overwrite existing data', required: true }] }),
83
+ ]);
84
+ }
85
+ }
@@ -0,0 +1,38 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ export declare const auditLimits: {
3
+ events: number;
4
+ days: number;
5
+ eventBytes: number;
6
+ databaseBytes: number;
7
+ sweepIntervalMs: number;
8
+ };
9
+ export interface AuditPolicy {
10
+ events: number;
11
+ days: number;
12
+ databaseBytes: number;
13
+ }
14
+ export interface RetentionState {
15
+ policy: AuditPolicy;
16
+ lastSweepMs: number;
17
+ runs: number;
18
+ lastRemoved: number;
19
+ }
20
+ export declare function auditUnavailable(): never;
21
+ export declare function auditPolicy(input: {
22
+ events: number;
23
+ days: number;
24
+ databaseBytes?: number;
25
+ }): AuditPolicy;
26
+ /** Called only in the owned schema initialization/upgrade transaction. Never overwrite unknown metadata. */
27
+ export declare function initializeRetention(db: DatabaseSync, policy: AuditPolicy, now: number): void;
28
+ export declare function retentionState(db: DatabaseSync): RetentionState;
29
+ export declare function auditStorageMode(db: DatabaseSync): {
30
+ autoVacuum: number;
31
+ journalMode: string;
32
+ };
33
+ export declare function requireAuditStorageMode(db: DatabaseSync): void;
34
+ /** Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action. */
35
+ export declare function acquireAuditWriter(db: DatabaseSync): void;
36
+ export declare function liveAuditBytes(db: DatabaseSync): number;
37
+ /** The caller holds BEGIN IMMEDIATE. Summary insertion is direct, never another append/GC call. */
38
+ export declare function collectAudit(db: DatabaseSync, now: number, incoming: number, pruned: number, state: RetentionState, summary: (data: Record<string, unknown>) => void): void;