@eyeauras/insight-cli 0.6.6 → 0.8.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.
- package/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/activity-audit.d.ts +130 -0
- package/dist/src/activity-audit.js +320 -0
- package/dist/src/analysis-storage.d.ts +5 -1
- package/dist/src/analysis-storage.js +9 -2
- package/dist/src/audit-commands.d.ts +10 -0
- package/dist/src/audit-commands.js +85 -0
- package/dist/src/audit-retention.d.ts +44 -0
- package/dist/src/audit-retention.js +167 -0
- package/dist/src/cli.js +28 -6
- package/dist/src/context-diagnostics.d.ts +1 -1
- package/dist/src/context-diagnostics.js +10 -2
- package/dist/src/contexts.d.ts +118 -10
- package/dist/src/contexts.js +851 -199
- package/dist/src/debugger.js +2 -1
- package/dist/src/diagnostic-error.d.ts +12 -0
- package/dist/src/diagnostic-error.js +82 -0
- package/dist/src/inline-script.js +3 -4
- package/dist/src/internal-timing.d.ts +8 -2
- package/dist/src/internal-timing.js +50 -7
- package/dist/src/lifecycle.d.ts +12 -1
- package/dist/src/lifecycle.js +34 -6
- package/dist/src/native-inputs.d.ts +6 -0
- package/dist/src/native-inputs.js +30 -6
- package/dist/src/native-queries.js +1 -6
- package/dist/src/native-service.d.ts +40 -0
- package/dist/src/native-service.js +406 -0
- package/dist/src/research.d.ts +30 -2
- package/dist/src/research.js +106 -27
- package/dist/src/server.d.ts +38 -1
- package/dist/src/server.js +160 -12
- package/dist/src/storage-gc.js +374 -341
- package/dist/src/sync-policy.js +2 -1
- package/dist/src/timed-backend.js +8 -0
- package/dist/src/timing-report.d.ts +32 -0
- package/dist/src/timing-report.js +74 -0
- package/dist/src/tool-runtime/identity.js +86 -1
- package/dist/src/tool-runtime/supervisor.js +6 -5
- package/dist/src/transport.d.ts +35 -0
- package/dist/src/transport.js +95 -16
- package/dist/src/unresolved-guidance.d.ts +46 -0
- package/dist/src/unresolved-guidance.js +55 -0
- package/dist/src/windbg.d.ts +1 -1
- package/dist/src/worker-lease.d.ts +17 -0
- package/dist/src/worker-lease.js +50 -0
- package/dist/src/workspace.d.ts +5 -9
- package/dist/src/workspace.js +34 -41
- package/package.json +1 -1
- package/references/native/InsightHeadlessMain.java +9 -2
- package/references/native/InsightNativeCheckout.java +113 -43
- package/references/native/InsightNativeFingerprint.java +28 -1
- package/references/native/InsightNativeRead.java +32 -9
- package/references/native/InsightNativeService.java +43 -0
- package/references/native/InsightNativeView.java +17 -6
- package/references/native/InsightOwnedScripts.java +170 -0
- package/references/native/InsightWorkerLease.java +132 -0
- package/references/recovery.md +68 -3
- package/references/research.md +71 -6
- package/references/setup.md +5 -1
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
- package/skill-bundle/insight-binary/SKILL.md +1 -1
- package/skill-bundle/insight-capture/SKILL.md +1 -1
- package/skill-bundle/insight-cli/SKILL.md +1 -1
- package/skill-bundle/insight-cli/references/recovery.md +68 -3
- package/skill-bundle/insight-cli/references/setup.md +5 -1
- package/skill-bundle/insight-die/SKILL.md +1 -1
- package/skill-bundle/insight-dnspy/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
- package/skill-bundle/insight-frida/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
- package/skill-bundle/insight-ghidra/references/research.md +71 -6
- package/skill-bundle/insight-ghidra/references/setup.md +5 -1
- package/skill-bundle/insight-ilspy/SKILL.md +1 -1
- package/skill-bundle/insight-interop/SKILL.md +1 -1
- package/skill-bundle/insight-lldb/SKILL.md +1 -1
- package/skill-bundle/insight-llvm/SKILL.md +1 -1
- package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
- package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
- package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
- package/skill-bundle/insight-overview/SKILL.md +1 -1
- package/skill-bundle/insight-procmon/SKILL.md +1 -1
- package/skill-bundle/insight-re/SKILL.md +7 -1
- package/skill-bundle/insight-re/references/recovery.md +68 -3
- package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
- package/skill-bundle/insight-strace/SKILL.md +1 -1
- package/skill-bundle/insight-tshark/SKILL.md +1 -1
- package/skill-bundle/insight-windbg/SKILL.md +1 -1
- package/skill-bundle/manifest.json +1 -1
- package/skills/insight-artifacts/SKILL.md +1 -1
- package/skills/insight-artifacts/references/recovery.md +68 -3
- package/skills/insight-binary/SKILL.md +1 -1
- package/skills/insight-capture/SKILL.md +1 -1
- package/skills/insight-die/SKILL.md +1 -1
- package/skills/insight-dnspy/SKILL.md +1 -1
- package/skills/insight-dotnet-dump/SKILL.md +1 -1
- package/skills/insight-dotnet-stack/SKILL.md +1 -1
- package/skills/insight-dotnet-trace/SKILL.md +1 -1
- package/skills/insight-frida/SKILL.md +1 -1
- package/skills/insight-ghidra/SKILL.md +1 -1
- package/skills/insight-ghidra/references/recovery.md +68 -3
- package/skills/insight-ghidra/references/research.md +71 -6
- package/skills/insight-ghidra/references/setup.md +5 -1
- package/skills/insight-ilspy/SKILL.md +1 -1
- package/skills/insight-interop/SKILL.md +1 -1
- package/skills/insight-lldb/SKILL.md +1 -1
- package/skills/insight-llvm/SKILL.md +1 -1
- package/skills/insight-managed-heap/SKILL.md +1 -1
- package/skills/insight-managed-metadata/SKILL.md +1 -1
- package/skills/insight-mitmproxy/SKILL.md +1 -1
- package/skills/insight-overview/SKILL.md +1 -1
- package/skills/insight-procmon/SKILL.md +1 -1
- package/skills/insight-re/SKILL.md +7 -1
- package/skills/insight-re/references/recovery.md +68 -3
- package/skills/insight-sevenzip/SKILL.md +1 -1
- package/skills/insight-strace/SKILL.md +1 -1
- package/skills/insight-tshark/SKILL.md +1 -1
- package/skills/insight-windbg/SKILL.md +1 -1
package/.cli-package-build.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"artifact":"
|
|
1
|
+
{"version":1,"artifact":"3c5d4ee1cf073825a74ba09b3f8b851cccefea0688d1cae155be30f698c4713f"}
|
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
|
+
# insight-cli 0.8.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
|
|
@@ -0,0 +1,130 @@
|
|
|
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
|
+
private readonly admissionMs;
|
|
46
|
+
/**
|
|
47
|
+
* `admissionMs` bounds the wait of a write for the shared writer lock (default three seconds). Its opening reads
|
|
48
|
+
* and its commit each wait for the database that long as well, and never less than three seconds; the waits add up.
|
|
49
|
+
*/
|
|
50
|
+
constructor(directory: string, limits?: {
|
|
51
|
+
events: number;
|
|
52
|
+
days: number;
|
|
53
|
+
databaseBytes?: number;
|
|
54
|
+
}, options?: {
|
|
55
|
+
admissionMs?: number;
|
|
56
|
+
});
|
|
57
|
+
private open;
|
|
58
|
+
private insert;
|
|
59
|
+
append(operationId: string, command: string, event: string, raw?: unknown, scope?: unknown): void;
|
|
60
|
+
private metadata;
|
|
61
|
+
private snapshot;
|
|
62
|
+
list(filter?: AuditFilter): AuditPage;
|
|
63
|
+
status(): {
|
|
64
|
+
bytes: number | undefined;
|
|
65
|
+
retention: {
|
|
66
|
+
events: number;
|
|
67
|
+
days: number;
|
|
68
|
+
databaseBytes: number;
|
|
69
|
+
eventBytes: number;
|
|
70
|
+
sweepIntervalMs: number;
|
|
71
|
+
};
|
|
72
|
+
maintenance: {
|
|
73
|
+
autoVacuum: number;
|
|
74
|
+
journalMode: string;
|
|
75
|
+
sharedByProfile: boolean;
|
|
76
|
+
policy: AuditPolicy;
|
|
77
|
+
lastSweepMs: number;
|
|
78
|
+
runs: number;
|
|
79
|
+
lastRemoved: number;
|
|
80
|
+
schemaVersion: number;
|
|
81
|
+
} | {
|
|
82
|
+
autoVacuum: number;
|
|
83
|
+
journalMode: string;
|
|
84
|
+
sharedByProfile: boolean;
|
|
85
|
+
runs: number;
|
|
86
|
+
lastSweepMs: number;
|
|
87
|
+
lastRemoved: number;
|
|
88
|
+
schemaVersion: number;
|
|
89
|
+
};
|
|
90
|
+
unfinished: {
|
|
91
|
+
operationId: string;
|
|
92
|
+
command: string;
|
|
93
|
+
startedAtMs: number;
|
|
94
|
+
pid: unknown;
|
|
95
|
+
}[];
|
|
96
|
+
unfinishedMeaning: string;
|
|
97
|
+
storeId: string | null;
|
|
98
|
+
count: number;
|
|
99
|
+
oldestSequence: number | null;
|
|
100
|
+
newestSequence: number | null;
|
|
101
|
+
prunedEvents: number;
|
|
102
|
+
initialized: boolean;
|
|
103
|
+
} | {
|
|
104
|
+
initialized: boolean;
|
|
105
|
+
storeId: null;
|
|
106
|
+
count: number;
|
|
107
|
+
oldestSequence: null;
|
|
108
|
+
newestSequence: null;
|
|
109
|
+
prunedEvents: number;
|
|
110
|
+
retention: {
|
|
111
|
+
events: number;
|
|
112
|
+
days: number;
|
|
113
|
+
databaseBytes: number;
|
|
114
|
+
eventBytes: number;
|
|
115
|
+
sweepIntervalMs: number;
|
|
116
|
+
};
|
|
117
|
+
maintenance: {
|
|
118
|
+
schemaVersion: number;
|
|
119
|
+
runs: number;
|
|
120
|
+
lastSweepMs: number;
|
|
121
|
+
lastRemoved: number;
|
|
122
|
+
sharedByProfile: boolean;
|
|
123
|
+
};
|
|
124
|
+
unfinished: never[];
|
|
125
|
+
unfinishedMeaning: string;
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export declare function bindAudit(raw: unknown): void;
|
|
129
|
+
export declare function auditEvent(event: string, raw?: unknown): void;
|
|
130
|
+
export declare function auditCommand<T>(store: AuditStore, command: string, options: unknown, action: () => Promise<T>, warn?: (code: string) => void): Promise<T>;
|
|
@@ -0,0 +1,320 @@
|
|
|
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, auditAdmissionMs } 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
|
+
admissionMs;
|
|
105
|
+
/**
|
|
106
|
+
* `admissionMs` bounds the wait of a write for the shared writer lock (default three seconds). Its opening reads
|
|
107
|
+
* and its commit each wait for the database that long as well, and never less than three seconds; the waits add up.
|
|
108
|
+
*/
|
|
109
|
+
constructor(directory, limits = auditLimits, options = {}) {
|
|
110
|
+
this.directory = directory;
|
|
111
|
+
this.path = join(directory, 'activity.sqlite');
|
|
112
|
+
this.initialPolicy = auditPolicy(limits);
|
|
113
|
+
this.admissionMs = options.admissionMs ?? auditAdmissionMs;
|
|
114
|
+
if (!Number.isSafeInteger(this.admissionMs) || this.admissionMs < 1 || this.admissionMs > 60000)
|
|
115
|
+
throw new Error('Invalid audit admission wait.');
|
|
116
|
+
}
|
|
117
|
+
open(write) {
|
|
118
|
+
const existing = stat(this.directory);
|
|
119
|
+
if (!existing && !write)
|
|
120
|
+
return;
|
|
121
|
+
if (!existing)
|
|
122
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
123
|
+
const dir = stat(this.directory), file = stat(this.path);
|
|
124
|
+
if (!dir?.isDirectory() || dir.isSymbolicLink() || file && (!file.isFile() || file.isSymbolicLink() || file.nlink !== 1))
|
|
125
|
+
unavailable();
|
|
126
|
+
if (!file && !write)
|
|
127
|
+
return;
|
|
128
|
+
let db;
|
|
129
|
+
try {
|
|
130
|
+
// A writer's reads before admission wait as long as its admission does: another writer's durable commit can
|
|
131
|
+
// hold the database for longer than SQLite's short default under disk load.
|
|
132
|
+
db = new DatabaseSync(this.path, { readOnly: !write });
|
|
133
|
+
db.exec('PRAGMA busy_timeout=' + (write ? Math.max(3000, this.admissionMs) : 3000) + ';');
|
|
134
|
+
db.exec('BEGIN');
|
|
135
|
+
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());
|
|
136
|
+
db.exec('END');
|
|
137
|
+
if (foreign)
|
|
138
|
+
unavailable();
|
|
139
|
+
if (write && version === 0 && app === 0) {
|
|
140
|
+
db.exec('PRAGMA auto_vacuum=FULL; PRAGMA synchronous=FULL; BEGIN IMMEDIATE;');
|
|
141
|
+
const currentVersion = Number(db.prepare('PRAGMA user_version').get()?.user_version);
|
|
142
|
+
if (currentVersion === 0) {
|
|
143
|
+
if (db.prepare("SELECT name FROM sqlite_master WHERE type='table'").get())
|
|
144
|
+
unavailable();
|
|
145
|
+
db.exec(`
|
|
146
|
+
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
147
|
+
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));
|
|
148
|
+
CREATE INDEX IF NOT EXISTS events_operation ON events(operation_id,seq);
|
|
149
|
+
CREATE INDEX IF NOT EXISTS events_session ON events(session,operation_id);
|
|
150
|
+
CREATE INDEX IF NOT EXISTS events_target ON events(target,operation_id);
|
|
151
|
+
CREATE INDEX IF NOT EXISTS events_request ON events(request,caller_hash);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS events_at ON events(at_ms);
|
|
153
|
+
PRAGMA application_id=${applicationId}; PRAGMA user_version=1;`);
|
|
154
|
+
db.prepare('INSERT OR IGNORE INTO metadata VALUES(?,?)').run('storeId', randomUUID());
|
|
155
|
+
db.prepare('INSERT OR IGNORE INTO metadata VALUES(?,?)').run('prunedEvents', '0');
|
|
156
|
+
initializeRetention(db, this.initialPolicy, Date.now());
|
|
157
|
+
}
|
|
158
|
+
else if (![1, 2].includes(currentVersion) || Number(db.prepare('PRAGMA application_id').get()?.application_id) !== applicationId)
|
|
159
|
+
unavailable();
|
|
160
|
+
db.exec('COMMIT');
|
|
161
|
+
}
|
|
162
|
+
else if (![1, 2].includes(version) || app !== applicationId)
|
|
163
|
+
unavailable();
|
|
164
|
+
this.metadata(db);
|
|
165
|
+
if (write) {
|
|
166
|
+
requireAuditStorageMode(db);
|
|
167
|
+
if (Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2)
|
|
168
|
+
retentionState(db);
|
|
169
|
+
chmodSync(this.path, 0o600);
|
|
170
|
+
db.exec('PRAGMA synchronous=FULL;');
|
|
171
|
+
}
|
|
172
|
+
else if (Number(db.prepare('PRAGMA user_version').get()?.user_version) === 2)
|
|
173
|
+
retentionState(db);
|
|
174
|
+
return db;
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
db?.close();
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
insert(db, operationId, command, event, raw, scope, at) {
|
|
182
|
+
const data = { schema: 1, operationId, command, event, at: new Date(at).toISOString(), ...details(scope), ...details(raw), pid: process.pid }, text = JSON.stringify(data);
|
|
183
|
+
if (Buffer.byteLength(text) > auditLimits.eventBytes)
|
|
184
|
+
throw new Error('Internal audit event exceeds its bound.');
|
|
185
|
+
const value = (key) => typeof data[key] === 'string' ? data[key] : null;
|
|
186
|
+
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);
|
|
187
|
+
}
|
|
188
|
+
append(operationId, command, event, raw = {}, scope = {}) {
|
|
189
|
+
if (!uuid.test(operationId) || !kinds.has(event) || !/^[a-z0-9][a-z0-9 -]{0,159}$/.test(command))
|
|
190
|
+
throw new Error('Invalid internal audit event.');
|
|
191
|
+
const db = this.open(true);
|
|
192
|
+
try {
|
|
193
|
+
acquireAuditWriter(db, this.directory, this.admissionMs);
|
|
194
|
+
const metadata = this.metadata(db), version = Number(db.prepare('PRAGMA user_version').get()?.user_version);
|
|
195
|
+
requireAuditStorageMode(db);
|
|
196
|
+
if (version === 1)
|
|
197
|
+
initializeRetention(db, this.initialPolicy, 0);
|
|
198
|
+
else if (version !== 2)
|
|
199
|
+
unavailable();
|
|
200
|
+
const state = retentionState(db);
|
|
201
|
+
const at = Date.now(), sequence = this.insert(db, operationId, command, event, raw, scope, at);
|
|
202
|
+
collectAudit(db, at, sequence, metadata.prunedEvents, state, data => this.insert(db, operationId, command, 'audit.gc', data, scope, at));
|
|
203
|
+
db.exec('COMMIT');
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
db.close();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
metadata(db) {
|
|
210
|
+
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;
|
|
211
|
+
if (typeof storeId !== 'string' || !uuid.test(storeId) || typeof rawPruned !== 'string' || !/^\d+(?:\.0+)?$/.test(rawPruned) || !Number.isSafeInteger(Number(rawPruned)))
|
|
212
|
+
unavailable();
|
|
213
|
+
return { storeId, prunedEvents: Number(rawPruned) };
|
|
214
|
+
}
|
|
215
|
+
snapshot(db) {
|
|
216
|
+
const range = db.prepare('SELECT count(*) count,min(seq) oldestSequence,max(seq) newestSequence FROM events').get();
|
|
217
|
+
return { ...this.metadata(db), count: Number(range.count), oldestSequence: range.oldestSequence === null ? null : Number(range.oldestSequence), newestSequence: range.newestSequence === null ? null : Number(range.newestSequence) };
|
|
218
|
+
}
|
|
219
|
+
list(filter = {}) {
|
|
220
|
+
const limit = filter.limit ?? 50;
|
|
221
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10000)
|
|
222
|
+
throw new CliError('Audit limit must be 1–10000.', { code: 'audit.invalid' });
|
|
223
|
+
let db;
|
|
224
|
+
try {
|
|
225
|
+
db = this.open(false);
|
|
226
|
+
if (!db)
|
|
227
|
+
return { schema: 1, storeId: null, count: 0, oldestSequence: null, newestSequence: null, prunedEvents: 0, items: [], hasMore: false, nextBefore: null };
|
|
228
|
+
db.exec('BEGIN');
|
|
229
|
+
const snapshot = this.snapshot(db), clauses = [], values = [];
|
|
230
|
+
const add = (sql, value) => { if (value !== undefined) {
|
|
231
|
+
clauses.push(sql);
|
|
232
|
+
values.push(value);
|
|
233
|
+
} };
|
|
234
|
+
add('seq<?', filter.before);
|
|
235
|
+
add('operation_id=?', filter.operationId);
|
|
236
|
+
add('command=?', filter.command);
|
|
237
|
+
add('event=?', filter.event);
|
|
238
|
+
add('at_ms>=?', filter.since);
|
|
239
|
+
add('at_ms<=?', filter.until);
|
|
240
|
+
for (const key of ['session', 'target'])
|
|
241
|
+
add(`operation_id IN (SELECT operation_id FROM events WHERE ${key}=?)`, filter[key]);
|
|
242
|
+
if (filter.request !== undefined) {
|
|
243
|
+
clauses.push('operation_id IN (SELECT operation_id FROM events WHERE request=? OR caller_hash=?)');
|
|
244
|
+
values.push(filter.request, auditHash(filter.request));
|
|
245
|
+
}
|
|
246
|
+
add("operation_id IN (SELECT operation_id FROM events WHERE json_extract(data,'$.traceId')=?)", filter.traceId);
|
|
247
|
+
if (filter.failures)
|
|
248
|
+
clauses.push("outcome='failure'");
|
|
249
|
+
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;
|
|
250
|
+
const items = rows.slice(0, limit).map(row => readRecord(row));
|
|
251
|
+
db.exec('COMMIT');
|
|
252
|
+
return { schema: 1, ...snapshot, items, hasMore, nextBefore: hasMore ? items.at(-1).sequence : null };
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return unavailable();
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
db?.close();
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
status() {
|
|
262
|
+
let db;
|
|
263
|
+
try {
|
|
264
|
+
db = this.open(false);
|
|
265
|
+
if (!db)
|
|
266
|
+
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.' };
|
|
267
|
+
db.exec('BEGIN');
|
|
268
|
+
const check = db.prepare('PRAGMA quick_check(1)').get();
|
|
269
|
+
if (!check || Object.values(check)[0] !== 'ok')
|
|
270
|
+
unavailable();
|
|
271
|
+
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 }; });
|
|
272
|
+
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.' };
|
|
273
|
+
db.exec('COMMIT');
|
|
274
|
+
return result;
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return unavailable();
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
db?.close();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
const active = new AsyncLocalStorage();
|
|
285
|
+
export function bindAudit(raw) { const context = active.getStore(); if (context)
|
|
286
|
+
Object.assign(context.scope, correlation(raw)); }
|
|
287
|
+
export function auditEvent(event, raw = {}) {
|
|
288
|
+
const context = active.getStore();
|
|
289
|
+
if (!context || context.disabled)
|
|
290
|
+
return;
|
|
291
|
+
try {
|
|
292
|
+
context.store.append(context.operationId, context.command, event, raw, context.scope);
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
context.disabled = true;
|
|
296
|
+
try {
|
|
297
|
+
context.warn(auditErrorCode(error));
|
|
298
|
+
}
|
|
299
|
+
catch { }
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
export async function auditCommand(store, command, options, action, warn = () => { }) {
|
|
303
|
+
const operationId = randomUUID(), started = performance.now(), scope = commandCorrelation(options), request = field(options, 'requestId');
|
|
304
|
+
if (typeof request === 'string' && request.length <= 4096)
|
|
305
|
+
scope.callerHash = auditHash(request);
|
|
306
|
+
return active.run({ store, operationId, command, scope, warn, disabled: false }, async () => {
|
|
307
|
+
auditEvent('command.started');
|
|
308
|
+
try {
|
|
309
|
+
const value = await action();
|
|
310
|
+
Object.assign(scope, commandCorrelation(value));
|
|
311
|
+
auditEvent('command.succeeded', { durationMs: performance.now() - started, outcome: 'success', state: field(value, 'state'), bytes: field(value, 'bytes'), retainedCount: field(value, 'retainedCount') });
|
|
312
|
+
return value;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
Object.assign(scope, commandCorrelation(field(error, 'result')));
|
|
316
|
+
auditEvent('command.failed', { durationMs: performance.now() - started, outcome: 'failure', error });
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
}
|
|
@@ -7,9 +7,13 @@ export declare class AnalysisStorage {
|
|
|
7
7
|
private readonly storeOverride;
|
|
8
8
|
private readonly release;
|
|
9
9
|
private readonly checkpoint?;
|
|
10
|
+
/** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
|
|
11
|
+
private readonly quiesce?;
|
|
10
12
|
private active;
|
|
11
13
|
private changing;
|
|
12
|
-
constructor(storeOverride: ProfileStoreContract | undefined, release: (c: CommandContext) => Promise<void>, checkpoint?: ((phase: string) => Promise<void>) | undefined
|
|
14
|
+
constructor(storeOverride: ProfileStoreContract | undefined, release: (c: CommandContext) => Promise<void>, checkpoint?: ((phase: string) => Promise<void>) | undefined,
|
|
15
|
+
/** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
|
|
16
|
+
quiesce?: ((c: CommandContext) => Promise<void>) | undefined);
|
|
13
17
|
private control;
|
|
14
18
|
private store;
|
|
15
19
|
private binding;
|
|
@@ -124,12 +124,16 @@ export class AnalysisStorage {
|
|
|
124
124
|
storeOverride;
|
|
125
125
|
release;
|
|
126
126
|
checkpoint;
|
|
127
|
+
quiesce;
|
|
127
128
|
active = new Map();
|
|
128
129
|
changing = new Set();
|
|
129
|
-
constructor(storeOverride, release, checkpoint
|
|
130
|
+
constructor(storeOverride, release, checkpoint,
|
|
131
|
+
/** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
|
|
132
|
+
quiesce) {
|
|
130
133
|
this.storeOverride = storeOverride;
|
|
131
134
|
this.release = release;
|
|
132
135
|
this.checkpoint = checkpoint;
|
|
136
|
+
this.quiesce = quiesce;
|
|
133
137
|
}
|
|
134
138
|
control(c) { return join(c.appArguments.AppDataDirectory, 'storage'); }
|
|
135
139
|
store(c) { return this.storeOverride ?? new ProfileStore({ applicationId: c.appArguments.AppName, appArguments: c.appArguments }); }
|
|
@@ -247,7 +251,10 @@ export class AnalysisStorage {
|
|
|
247
251
|
busy(directory) { return this.changing.has(directory); }
|
|
248
252
|
async exclusive(c, action) {
|
|
249
253
|
const key = c.appArguments.AppDataDirectory;
|
|
250
|
-
if (this.changing.has(key) || this.active.get(key)
|
|
254
|
+
if (this.changing.has(key) || this.active.get(key))
|
|
255
|
+
fail('busy', 'Finish active commands before storage migration.');
|
|
256
|
+
await this.quiesce?.(c);
|
|
257
|
+
if (toolProfileBusy(key))
|
|
251
258
|
fail('busy', 'Finish active commands before storage migration.');
|
|
252
259
|
this.changing.add(key);
|
|
253
260
|
try {
|
|
@@ -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,44 @@
|
|
|
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
|
+
export declare const auditAdmissionMs = 3000;
|
|
35
|
+
/**
|
|
36
|
+
* Fair writer admission across processes. SQLite has no queue: a continuously re-entering writer can win every
|
|
37
|
+
* free interval and starve others past the deadline. Each writer registers an ordered waiter marker, only the
|
|
38
|
+
* oldest live waiter contends for the lock, and the marker is removed as soon as the lock is held.
|
|
39
|
+
* Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action.
|
|
40
|
+
*/
|
|
41
|
+
export declare function acquireAuditWriter(db: DatabaseSync, directory: string, admissionMs?: number): void;
|
|
42
|
+
export declare function liveAuditBytes(db: DatabaseSync): number;
|
|
43
|
+
/** The caller holds BEGIN IMMEDIATE. Summary insertion is direct, never another append/GC call. */
|
|
44
|
+
export declare function collectAudit(db: DatabaseSync, now: number, incoming: number, pruned: number, state: RetentionState, summary: (data: Record<string, unknown>) => void): void;
|