@eyeauras/insight-cli 0.6.6 → 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 (73) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  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 +10 -2
  10. package/dist/src/diagnostic-error.d.ts +12 -0
  11. package/dist/src/diagnostic-error.js +82 -0
  12. package/dist/src/internal-timing.d.ts +8 -2
  13. package/dist/src/internal-timing.js +50 -7
  14. package/dist/src/lifecycle.d.ts +1 -1
  15. package/dist/src/research.d.ts +1 -1
  16. package/dist/src/storage-gc.js +374 -341
  17. package/dist/src/transport.js +19 -10
  18. package/dist/src/workspace.d.ts +2 -0
  19. package/dist/src/workspace.js +25 -0
  20. package/package.json +1 -1
  21. package/references/research.md +33 -2
  22. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  23. package/skill-bundle/insight-binary/SKILL.md +1 -1
  24. package/skill-bundle/insight-capture/SKILL.md +1 -1
  25. package/skill-bundle/insight-cli/SKILL.md +1 -1
  26. package/skill-bundle/insight-die/SKILL.md +1 -1
  27. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  28. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  29. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  30. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  31. package/skill-bundle/insight-frida/SKILL.md +1 -1
  32. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  33. package/skill-bundle/insight-ghidra/references/research.md +33 -2
  34. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  35. package/skill-bundle/insight-interop/SKILL.md +1 -1
  36. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  37. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  38. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  39. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  40. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  41. package/skill-bundle/insight-overview/SKILL.md +1 -1
  42. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  43. package/skill-bundle/insight-re/SKILL.md +7 -1
  44. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  45. package/skill-bundle/insight-strace/SKILL.md +1 -1
  46. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  47. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  48. package/skill-bundle/manifest.json +1 -1
  49. package/skills/insight-artifacts/SKILL.md +1 -1
  50. package/skills/insight-binary/SKILL.md +1 -1
  51. package/skills/insight-capture/SKILL.md +1 -1
  52. package/skills/insight-die/SKILL.md +1 -1
  53. package/skills/insight-dnspy/SKILL.md +1 -1
  54. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  55. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  56. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  57. package/skills/insight-frida/SKILL.md +1 -1
  58. package/skills/insight-ghidra/SKILL.md +1 -1
  59. package/skills/insight-ghidra/references/research.md +33 -2
  60. package/skills/insight-ilspy/SKILL.md +1 -1
  61. package/skills/insight-interop/SKILL.md +1 -1
  62. package/skills/insight-lldb/SKILL.md +1 -1
  63. package/skills/insight-llvm/SKILL.md +1 -1
  64. package/skills/insight-managed-heap/SKILL.md +1 -1
  65. package/skills/insight-managed-metadata/SKILL.md +1 -1
  66. package/skills/insight-mitmproxy/SKILL.md +1 -1
  67. package/skills/insight-overview/SKILL.md +1 -1
  68. package/skills/insight-procmon/SKILL.md +1 -1
  69. package/skills/insight-re/SKILL.md +7 -1
  70. package/skills/insight-sevenzip/SKILL.md +1 -1
  71. package/skills/insight-strace/SKILL.md +1 -1
  72. package/skills/insight-tshark/SKILL.md +1 -1
  73. package/skills/insight-windbg/SKILL.md +1 -1
@@ -0,0 +1,106 @@
1
+ import { CliError } from '@eyeauras/cli-factory';
2
+ export const auditLimits = { events: 20000, days: 30, eventBytes: 4096, databaseBytes: 16 * 1024 * 1024, sweepIntervalMs: 5 * 60000 };
3
+ export function auditUnavailable() { throw new CliError('Audit history is unavailable or incompatible; preserve its files. No history was reset.', { code: 'audit.unavailable' }); }
4
+ export function auditPolicy(input) {
5
+ const policy = { events: input.events, days: input.days, databaseBytes: input.databaseBytes ?? auditLimits.databaseBytes };
6
+ if (!Number.isSafeInteger(policy.events) || policy.events < 4 || policy.events > auditLimits.events || !Number.isSafeInteger(policy.days) || policy.days < 1 || policy.days > auditLimits.days || !Number.isSafeInteger(policy.databaseBytes) || policy.databaseBytes < 256 * 1024 || policy.databaseBytes > auditLimits.databaseBytes)
7
+ auditUnavailable();
8
+ return policy;
9
+ }
10
+ const keys = ['retentionEvents', 'retentionDays', 'retentionBytes', 'lastSweepMs', 'gcRuns', 'lastGcRemoved'];
11
+ function set(db, key, value) { if (!Number.isSafeInteger(value) || value < 0)
12
+ auditUnavailable(); db.prepare('INSERT OR REPLACE INTO metadata(key,value) VALUES(?,?)').run(key, String(value)); }
13
+ /** Called only in the owned schema initialization/upgrade transaction. Never overwrite unknown metadata. */
14
+ export function initializeRetention(db, policy, now) {
15
+ for (const key of keys)
16
+ if (db.prepare('SELECT value FROM metadata WHERE key=?').get(key))
17
+ auditUnavailable();
18
+ db.exec("ALTER TABLE events ADD COLUMN writer_version INTEGER NOT NULL DEFAULT 1; CREATE TRIGGER audit_writer_v2 BEFORE INSERT ON events WHEN NEW.writer_version IS NOT 2 BEGIN SELECT RAISE(ABORT,'Incompatible audit writer'); END;");
19
+ for (const [key, value] of Object.entries({ retentionEvents: policy.events, retentionDays: policy.days, retentionBytes: policy.databaseBytes, lastSweepMs: now, gcRuns: 0, lastGcRemoved: 0 }))
20
+ set(db, key, value);
21
+ db.exec('PRAGMA user_version=2');
22
+ }
23
+ export function retentionState(db) {
24
+ if (!db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name='audit_writer_v2'").get())
25
+ auditUnavailable();
26
+ const rows = db.prepare("SELECT key,value FROM metadata WHERE key IN ('retentionEvents','retentionDays','retentionBytes','lastSweepMs','gcRuns','lastGcRemoved')").all(), values = {};
27
+ for (const row of rows) {
28
+ if (typeof row.key !== 'string' || typeof row.value !== 'string' || !/^\d+$/.test(row.value) || !Number.isSafeInteger(Number(row.value)))
29
+ auditUnavailable();
30
+ values[row.key] = Number(row.value);
31
+ }
32
+ if (keys.some(key => values[key] === undefined))
33
+ auditUnavailable();
34
+ return { policy: auditPolicy({ events: values.retentionEvents, days: values.retentionDays, databaseBytes: values.retentionBytes }), lastSweepMs: values.lastSweepMs, runs: values.gcRuns, lastRemoved: values.lastGcRemoved };
35
+ }
36
+ export function auditStorageMode(db) { return { autoVacuum: Number(db.prepare('PRAGMA auto_vacuum').get()?.auto_vacuum), journalMode: String(db.prepare('PRAGMA journal_mode').get()?.journal_mode) }; }
37
+ export function requireAuditStorageMode(db) { const mode = auditStorageMode(db); if (mode.autoVacuum !== 1 || mode.journalMode !== 'delete')
38
+ auditUnavailable(); }
39
+ const writerWait = new Int32Array(new SharedArrayBuffer(4));
40
+ /** Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action. */
41
+ export function acquireAuditWriter(db) {
42
+ const deadline = performance.now() + 3000;
43
+ let attempt = 0;
44
+ try {
45
+ for (;;) {
46
+ const remaining = deadline - performance.now();
47
+ db.exec('PRAGMA busy_timeout=' + Math.max(0, Math.min(50, Math.ceil(remaining))));
48
+ try {
49
+ db.exec('BEGIN IMMEDIATE');
50
+ return;
51
+ }
52
+ catch (error) {
53
+ let busy = false;
54
+ try {
55
+ const e = error;
56
+ busy = e?.code === 'ERR_SQLITE_ERROR' && typeof e.errcode === 'number' && Number.isSafeInteger(e.errcode) && e.errcode > 0 && [5, 6].includes(e.errcode & 255);
57
+ }
58
+ catch { }
59
+ if (!busy || performance.now() >= deadline)
60
+ throw error;
61
+ // SQLite's long busy-handler backoff can repeatedly miss short free intervals.
62
+ // Restart it with a bounded jitter so a continuous producer cannot monopolize admission.
63
+ Atomics.wait(writerWait, 0, 0, Math.max(0, Math.min(5 + (process.pid + attempt++ * 13) % 21, deadline - performance.now())));
64
+ }
65
+ }
66
+ }
67
+ finally {
68
+ db.exec('PRAGMA busy_timeout=3000');
69
+ }
70
+ }
71
+ export function liveAuditBytes(db) { return (Number(db.prepare('PRAGMA page_count').get()?.page_count) - Number(db.prepare('PRAGMA freelist_count').get()?.freelist_count)) * Number(db.prepare('PRAGMA page_size').get()?.page_size); }
72
+ function count(db) { return Number(db.prepare('SELECT count(*) count FROM events').get().count); }
73
+ /** The caller holds BEGIN IMMEDIATE. Summary insertion is direct, never another append/GC call. */
74
+ export function collectAudit(db, now, incoming, pruned, state, summary) {
75
+ const policy = state.policy, eventsBefore = count(db), liveBytesBefore = liveAuditBytes(db), periodic = now < state.lastSweepMs || now - state.lastSweepMs >= auditLimits.sweepIntervalMs;
76
+ const reserve = 128 * 1024, eventPressure = eventsBefore > policy.events || periodic && eventsBefore + 1 > policy.events, bytePressure = liveBytesBefore > policy.databaseBytes || periodic && liveBytesBefore + reserve > policy.databaseBytes;
77
+ if (!periodic && !eventPressure && !bytePressure)
78
+ return;
79
+ const expiredEvents = Number(db.prepare('DELETE FROM events WHERE at_ms<? AND seq<>?').run(now - policy.days * 86400000, incoming).changes);
80
+ let removed = expiredEvents;
81
+ const targetEvents = Math.max(2, Math.floor(policy.events * 0.8));
82
+ const drop = (n) => Number(db.prepare('DELETE FROM events WHERE seq IN (SELECT seq FROM events WHERE seq<>? ORDER BY seq LIMIT ?)').run(incoming, n).changes);
83
+ if (eventPressure)
84
+ removed += drop(Math.max(0, count(db) - (targetEvents - 1))); // reserve the GC record itself
85
+ const trimBytes = bytePressure || liveAuditBytes(db) + reserve > policy.databaseBytes;
86
+ if (trimBytes) {
87
+ const targetBytes = Math.min(Math.floor(policy.databaseBytes * 0.75), policy.databaseBytes - reserve);
88
+ while (liveAuditBytes(db) > targetBytes) {
89
+ const changed = drop(Math.max(1, Math.ceil(count(db) * 0.1)));
90
+ if (!changed)
91
+ auditUnavailable();
92
+ removed += changed;
93
+ }
94
+ }
95
+ // Account for the maintenance event even if the original pressure was only age.
96
+ if (count(db) + 1 > policy.events)
97
+ removed += drop(Math.max(0, count(db) - (targetEvents - 1)));
98
+ const eventsAfter = count(db) + 1, liveBytesAfterPrune = liveAuditBytes(db);
99
+ set(db, 'prunedEvents', pruned + removed);
100
+ set(db, 'lastSweepMs', now);
101
+ set(db, 'gcRuns', state.runs + 1);
102
+ set(db, 'lastGcRemoved', removed);
103
+ summary({ automatic: true, state: 'complete', outcome: 'success', gcTrigger: eventPressure && trimBytes ? 'multiple' : eventPressure ? 'event-limit' : trimBytes ? 'byte-limit' : 'periodic', removedEvents: removed, expiredEvents, eventsBefore, eventsAfter, liveBytesBefore, liveBytesAfterPrune });
104
+ if (count(db) > policy.events || liveAuditBytes(db) > policy.databaseBytes)
105
+ auditUnavailable();
106
+ }
package/dist/src/cli.js CHANGED
@@ -57,6 +57,7 @@ import { codeReferenceCommands } from './code-references.js';
57
57
  import { stringAnchorCommands } from './string-anchors.js';
58
58
  import { contextDiagnosticCommands } from './context-diagnostics.js';
59
59
  import { traceCommand } from './internal-timing.js';
60
+ import { ActivityAudit } from './audit-commands.js';
60
61
  import { timedBackend } from './timed-backend.js';
61
62
  import { readInitialProgress } from './initial-progress.js';
62
63
  const bindingFields = ['java', 'ghidraHome', 'mcpJar', 'mcpJarSha256', 'server', 'repository', 'readerUser', 'publisherUser', 'maxContexts', 'debuggerPython', 'windbgDir', 'archiveUrl'];
@@ -328,13 +329,15 @@ function scopedFailures(entry, owner, parents = []) {
328
329
  catch {
329
330
  throw error;
330
331
  }
332
+ if (selected.session === 'new')
333
+ throw error;
331
334
  if (!(error instanceof CliError))
332
335
  throw error;
333
336
  const result = error.result && typeof error.result === 'object' && !Array.isArray(error.result) ? error.result : {};
334
337
  throw new CliError(error.message, { code: error.code, exitCode: error.exitCode, next: error.next, result: { ...result, ...selected } });
335
338
  }
336
339
  };
337
- return path[1] === 'open' || input.options.session && input.options.target ? traceCommand(join(analysisDirectory(c), 'workspace'), name, execute) : execute();
340
+ return path[1] === 'open' || input.options.session && input.options.target ? traceCommand(join(analysisDirectory(c), 'workspace'), name, execute, { session: input.options.session, target: input.options.target }) : execute();
338
341
  } } : {}) };
339
342
  }
340
343
  export function createDefinition(options = {}) {
@@ -581,6 +584,11 @@ export function createDefinition(options = {}) {
581
584
  const commands = definition.commands?.map(entry => entry.name === 'ghidra' ?
582
585
  scopedFailures({ ...entry, children: extendQueries(extendQueries(extendQueries(entry.children ?? [], queryCommands(c => owner.selected(c).research)), mutationCommands(c => owner.selected(c).research)), [...codeReferenceCommands(c => owner.selected(c).research), ...stringAnchorCommands(c => owner.selected(c).research), ...contextDiagnosticCommands(c => owner.selected(c).research, c => owner.selected(c).workspace), ...sdkCommands(c => owner.selected(c).research), ...sdkFileCommands(c => owner.selected(c).sdkFiles), ...trackingCommands(c => owner.selected(c).tracking), ...crossCommands(c => owner.selected(c).research), ...administrationCommands(c => owner.selected(c).administration, options.backend ? undefined : async (c) => { const status = await new RuntimeManager(c).status(); return status.state === 'not_ready' ? { ...status.server, connected: false, state: 'runtime_not_ready', missing: status.missing } : undefined; }),
583
586
  ...extensionCommands(c => new Extensions(join(analysisDirectory(c), 'workspace'))), ...extensionInventoryCommands(c => owner.selected(c).backend), ...pluginCommands(c => owner.selected(c).ui), ...synchronizationCommands(c => owner.selected(c).synchronization), ...utilityCommands(), ...runtimeCommands((c, action, quiescent) => owner.runtime(c, action, quiescent)), ...lifecycleCommands(c => owner.selected(c).lifecycle, c => new RuntimeManager(c).status()), ...projectCommands(c => owner.selected(c).projects), ...uiCommands(c => owner.selected(c).ui), ...debuggerCommands(c => owner.selected(c).debugger), ...archiveCommands(c => owner.selected(c).archive)]) }, owner) : entry);
584
- return { ...definition, commands: [...(commands ?? []).map(e => storage.wrap(e)), storage.commands()] };
587
+ const audit = new ActivityAudit(), auth = definition.auth;
588
+ return { ...definition, auth: { ...auth,
589
+ login: (c, o) => audit.run(c, 'auth login', { args: {}, options: {} }, () => auth.login(c, o)),
590
+ status: c => audit.run(c, 'auth status', { args: {}, options: {} }, () => auth.status(c)),
591
+ logout: c => audit.run(c, 'auth logout', { args: {}, options: {} }, () => auth.logout(c)),
592
+ }, commands: [...[...(commands ?? []).map(e => storage.wrap(e)), storage.commands()].map(e => audit.wrap(e)), audit.commands()] };
585
593
  }
586
594
  export const createInsightCli = (options = {}) => createCli(createDefinition(options));
@@ -0,0 +1,12 @@
1
+ export type TransportPhase = 'fetch' | 'body' | 'status';
2
+ /** Machine categories only: never exception messages, stacks, addresses, headers or response data. */
3
+ export declare function transportDiagnostic(error: unknown, phase: TransportPhase, method: string, port: number, status?: number): {
4
+ httpStatus?: number | undefined;
5
+ causeCodes: string[];
6
+ errorName?: string | undefined;
7
+ phase: TransportPhase;
8
+ method: string;
9
+ port: number;
10
+ };
11
+ /** Revalidate even our own error results before persisting any structured diagnostics. */
12
+ export declare function diagnosticFailure(error: unknown): Record<string, unknown> | undefined;
@@ -0,0 +1,82 @@
1
+ import { CliError } from '@eyeauras/cli-factory';
2
+ const networkCodes = new Set([
3
+ 'ECONNREFUSED', 'ECONNRESET', 'ECONNABORTED', 'EPIPE', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'ENETDOWN',
4
+ 'EADDRNOTAVAIL', 'EACCES', 'EPERM', 'EMFILE', 'ENFILE', 'ENOBUFS', 'ENOTFOUND', 'EAI_AGAIN',
5
+ 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT',
6
+ 'UND_ERR_ABORTED', 'UND_ERR_DESTROYED', 'UND_ERR_CLOSED', 'UND_ERR_INVALID_ARG', 'UND_ERR_HEADERS_OVERFLOW',
7
+ 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH', 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH', 'UND_ERR_RESPONSE_EXCEEDED_MAX_SIZE',
8
+ 'ERR_STREAM_PREMATURE_CLOSE', 'ERR_INVALID_ARG_TYPE', 'ERR_INVALID_CHAR', 'ERR_INVALID_HTTP_TOKEN', 'ABORT_ERR',
9
+ 'HPE_INVALID_CONSTANT', 'HPE_INVALID_VERSION', 'HPE_INVALID_STATUS', 'HPE_INVALID_HEADER_TOKEN',
10
+ 'HPE_INVALID_CONTENT_LENGTH', 'HPE_UNEXPECTED_CONTENT_LENGTH', 'HPE_INVALID_CHUNK_SIZE', 'HPE_INVALID_EOF_STATE',
11
+ ]);
12
+ const names = new Set(['Error', 'TypeError', 'RangeError', 'SyntaxError', 'AggregateError', 'AbortError', 'TimeoutError']);
13
+ const errorCodes = new Set([
14
+ 'coordinator.credentials', 'coordinator.idempotency', 'coordinator.unsupported', 'audit.unavailable', 'audit.invalid', 'storage.aliases', 'storage.binding', 'storage.busy', 'storage.capacity', 'storage.changed', 'storage.configuration', 'storage.data', 'storage.destination', 'storage.journal', 'storage.limit', 'storage.link', 'storage.missing', 'storage.path', 'storage.pending', 'storage.repair', 'storage.retention', 'storage.type', 'storage.unavailable', 'storage.verification', 'storage.volume',
15
+ 'coordinator.transport', 'coordinator.timeout', 'coordinator.cancelled', 'coordinator.remote', 'coordinator.malformed',
16
+ 'coordinator.limit', 'coordinator.schema', 'coordinator.binding', 'coordinator.unknown', 'coordinator.blocked',
17
+ 'coordinator.busy', 'coordinator.conflict', 'coordinator.launch', 'coordinator.capacity', 'coordinator.invalid',
18
+ 'coordinator.migration', 'coordinator.configuration', 'coordinator.notFound', 'permission.denied', 'usage',
19
+ 'tool.timeout', 'tool.cancelled', 'tool.output.limit', 'tool.exit.code', 'tool.launch',
20
+ ]);
21
+ function field(value, key) {
22
+ try {
23
+ return value && typeof value === 'object' ? value[key] : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function array(value) { try {
30
+ return Array.isArray(value);
31
+ }
32
+ catch {
33
+ return false;
34
+ } }
35
+ /** Machine categories only: never exception messages, stacks, addresses, headers or response data. */
36
+ export function transportDiagnostic(error, phase, method, port, status) {
37
+ const codes = new Set(), queue = [error], seen = new Set();
38
+ for (let n = 0; n < 8 && queue.length; n++) {
39
+ const value = queue.shift();
40
+ if (!value || seen.has(value))
41
+ continue;
42
+ seen.add(value);
43
+ const code = field(value, 'code');
44
+ if (typeof code === 'string' && networkCodes.has(code) && codes.size < 4)
45
+ codes.add(code);
46
+ const cause = field(value, 'cause');
47
+ if (cause)
48
+ queue.push(cause);
49
+ const errors = field(value, 'errors'), length = field(errors, 'length');
50
+ if (array(errors) && typeof length === 'number')
51
+ for (let i = 0; i < 4 && i < length; i++)
52
+ queue.push(field(errors, String(i)));
53
+ }
54
+ const name = field(error, 'name');
55
+ return { phase, method, port, ...(typeof name === 'string' && names.has(name) ? { errorName: name } : {}), causeCodes: [...codes], ...(status !== undefined ? { httpStatus: status } : {}) };
56
+ }
57
+ /** Revalidate even our own error results before persisting any structured diagnostics. */
58
+ export function diagnosticFailure(error) {
59
+ try {
60
+ if (!(error instanceof CliError) || !errorCodes.has(error.code))
61
+ return undefined;
62
+ const result = { code: error.code }, raw = field(error.result, 'transport') ?? field(field(error.result, 'detail'), 'transport');
63
+ const phase = field(raw, 'phase'), method = field(raw, 'method'), port = field(raw, 'port');
64
+ if (typeof phase !== 'string' || !['fetch', 'body', 'status'].includes(phase) || typeof method !== 'string' || !['GET', 'POST'].includes(method) || !Number.isSafeInteger(port) || Number(port) < 0 || Number(port) > 65535)
65
+ return result;
66
+ const name = field(raw, 'errorName'), codes = field(raw, 'causeCodes'), status = field(raw, 'httpStatus'), safeCodes = [];
67
+ const length = field(codes, 'length');
68
+ if (array(codes) && typeof length === 'number')
69
+ for (let i = 0; i < 4 && i < length; i++) {
70
+ const code = field(codes, String(i));
71
+ if (typeof code === 'string' && networkCodes.has(code))
72
+ safeCodes.push(code);
73
+ }
74
+ result.transport = { phase, method, port, ...(typeof name === 'string' && names.has(name) ? { errorName: name } : {}),
75
+ causeCodes: safeCodes,
76
+ ...(Number.isInteger(status) && Number(status) >= 100 && Number(status) <= 599 ? { httpStatus: status } : {}) };
77
+ return result;
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
@@ -1,3 +1,9 @@
1
- /** Internal diagnostics only: fixed operation names, never argv, payloads, paths or errors. */
1
+ interface Correlation {
2
+ session?: unknown;
3
+ target?: unknown;
4
+ }
5
+ export declare function currentTraceId(): string | undefined;
6
+ /** Internal diagnostics: fixed operations and validated machine categories, never raw exception text or payloads. */
2
7
  export declare function timed<T>(phase: string, operation: string, action: () => Promise<T>): Promise<T>;
3
- export declare function traceCommand<T>(root: string, command: string, action: () => Promise<T>): Promise<T>;
8
+ export declare function traceCommand<T>(root: string, command: string, action: () => Promise<T>, selected?: Correlation): Promise<T>;
9
+ export {};
@@ -3,32 +3,75 @@ import { randomUUID } from 'node:crypto';
3
3
  import { mkdir, appendFile, stat, rename } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { performance } from 'node:perf_hooks';
6
+ import { CliError } from '@eyeauras/cli-factory';
7
+ import { diagnosticFailure } from './diagnostic-error.js';
6
8
  const current = new AsyncLocalStorage(), writes = new Map();
7
- /** Internal diagnostics only: fixed operation names, never argv, payloads, paths or errors. */
9
+ export function currentTraceId() { return current.getStore()?.id; }
10
+ function withTrace(error, traceId) {
11
+ try {
12
+ return new CliError(error.message, { code: error.code, exitCode: error.exitCode, next: error.next, result: { ...error.result, traceId } });
13
+ }
14
+ catch {
15
+ return error;
16
+ }
17
+ }
18
+ function correlation(value) {
19
+ const result = {};
20
+ try {
21
+ if (value && typeof value === 'object') {
22
+ const { session, target } = value;
23
+ if (typeof session === 'string' && /^s_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(session))
24
+ result.session = session;
25
+ if (typeof target === 'string' && /^t_[0-9a-f]{32}$/i.test(target))
26
+ result.target = target;
27
+ }
28
+ }
29
+ catch { }
30
+ return result;
31
+ }
32
+ /** Internal diagnostics: fixed operations and validated machine categories, never raw exception text or payloads. */
8
33
  export async function timed(phase, operation, action) {
9
34
  const trace = current.getStore();
10
35
  if (!trace)
11
36
  return action();
12
37
  const span = randomUUID(), started = performance.now();
13
- let outcome = 'success';
38
+ let outcome = 'success', failure;
14
39
  try {
15
40
  return await current.run({ ...trace, parent: span }, action);
16
41
  }
17
42
  catch (error) {
18
43
  outcome = 'failure';
44
+ failure = diagnosticFailure(error);
19
45
  throw error;
20
46
  }
21
47
  finally {
22
48
  if (trace.rows.length < 1024)
23
- trace.rows.push({ trace: trace.id, span, parent: trace.parent ?? null, command: trace.command, phase, operation, startedMs: started - trace.started, durationMs: performance.now() - started, outcome });
49
+ trace.rows.push({ trace: trace.id, span, parent: trace.parent ?? null, command: trace.command, phase, operation, startedMs: started - trace.started, durationMs: performance.now() - started, outcome, ...(failure ? { failure } : {}) });
24
50
  else
25
51
  trace.overflow.count++;
26
52
  }
27
53
  }
28
- export async function traceCommand(root, command, action) {
29
- const trace = { id: randomUUID(), command, started: performance.now(), rows: [], overflow: { count: 0 } }, at = new Date().toISOString();
54
+ export async function traceCommand(root, command, action, selected) {
55
+ const trace = { id: randomUUID(), command, started: performance.now(), rows: [], overflow: { count: 0 }, scope: correlation(selected) }, at = new Date().toISOString();
30
56
  try {
31
- return await current.run(trace, () => timed('facade.command', command, action));
57
+ const value = await current.run(trace, () => timed('facade.command', command, action));
58
+ Object.assign(trace.scope, correlation(value));
59
+ return value;
60
+ }
61
+ catch (error) {
62
+ let reported = error;
63
+ try {
64
+ if (error instanceof CliError) {
65
+ Object.assign(trace.scope, correlation(error.result));
66
+ // Domain replays keep their recorded envelope; only a transport attempt gains a trace link.
67
+ if ((['coordinator.transport', 'coordinator.timeout', 'coordinator.cancelled'].includes(error.code) || error.code === 'coordinator.remote' && diagnosticFailure(error)?.transport) &&
68
+ (error.result === undefined || error.result && typeof error.result === 'object' && !Array.isArray(error.result))) {
69
+ reported = withTrace(error, trace.id);
70
+ }
71
+ }
72
+ }
73
+ catch { }
74
+ throw reported;
32
75
  }
33
76
  finally {
34
77
  const directory = join(root, 'diagnostics'), path = join(directory, 'timings.jsonl'), previous = writes.get(path) ?? Promise.resolve();
@@ -36,7 +79,7 @@ export async function traceCommand(root, command, action) {
36
79
  await mkdir(directory, { recursive: true, mode: 0o700 });
37
80
  if (await stat(path).then(s => s.size, () => 0) > 8 * 1024 ** 2)
38
81
  await rename(path, path + '.previous');
39
- await appendFile(path, trace.rows.map(row => JSON.stringify({ schema: 1, at, ...row, droppedSpans: trace.overflow.count })).join('\n') + '\n', { mode: 0o600 });
82
+ await appendFile(path, trace.rows.map(row => JSON.stringify({ schema: 1, at, ...trace.scope, ...row, droppedSpans: trace.overflow.count })).join('\n') + '\n', { mode: 0o600 });
40
83
  });
41
84
  writes.set(path, pending);
42
85
  // Telemetry loss cannot change an acknowledged program operation into a failed write.
@@ -48,7 +48,7 @@ export declare class Lifecycle {
48
48
  state: "active" | "verified" | "dropped";
49
49
  } | undefined;
50
50
  syncPolicy: import("./workspace.js").SyncPolicy;
51
- state: "opening" | "ready" | "stopped" | "needs_recovery";
51
+ state: "ready" | "opening" | "stopped" | "needs_recovery";
52
52
  baseRevision: string | undefined;
53
53
  engine: string;
54
54
  };
@@ -177,7 +177,7 @@ export declare class Research {
177
177
  state: "active" | "verified" | "dropped";
178
178
  } | undefined;
179
179
  syncPolicy: import("./workspace.js").SyncPolicy;
180
- state: "opening" | "ready" | "stopped" | "needs_recovery";
180
+ state: "ready" | "opening" | "stopped" | "needs_recovery";
181
181
  baseRevision: string | undefined;
182
182
  engine: string;
183
183
  };