@ipab/cli 0.1.0-rc.12 → 0.1.0-rc.13

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 (71) hide show
  1. package/dist/cli-daemon.d.ts +14 -0
  2. package/dist/cli-daemon.d.ts.map +1 -0
  3. package/dist/cli-daemon.js +400 -0
  4. package/dist/cli-daemon.js.map +1 -0
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +1260 -1404
  7. package/dist/cli.js.map +1 -1
  8. package/dist/daemon-api.d.ts +80 -0
  9. package/dist/daemon-api.d.ts.map +1 -0
  10. package/dist/daemon-api.js +2411 -0
  11. package/dist/daemon-api.js.map +1 -0
  12. package/dist/daemon-client.d.ts +322 -0
  13. package/dist/daemon-client.d.ts.map +1 -0
  14. package/dist/daemon-client.js +400 -0
  15. package/dist/daemon-client.js.map +1 -0
  16. package/dist/daemon-protocol.d.ts +22 -0
  17. package/dist/daemon-protocol.d.ts.map +1 -0
  18. package/dist/daemon-protocol.js +39 -0
  19. package/dist/daemon-protocol.js.map +1 -0
  20. package/dist/daemon-telemetry.d.ts +86 -0
  21. package/dist/daemon-telemetry.d.ts.map +1 -0
  22. package/dist/daemon-telemetry.js +502 -0
  23. package/dist/daemon-telemetry.js.map +1 -0
  24. package/dist/daemon-ui.d.ts +68 -0
  25. package/dist/daemon-ui.d.ts.map +1 -1
  26. package/dist/daemon-ui.js +283 -4
  27. package/dist/daemon-ui.js.map +1 -1
  28. package/dist/daemon.d.ts +10 -0
  29. package/dist/daemon.d.ts.map +1 -1
  30. package/dist/daemon.js +289 -38
  31. package/dist/daemon.js.map +1 -1
  32. package/dist/identity.d.ts.map +1 -1
  33. package/dist/identity.js +7 -2
  34. package/dist/identity.js.map +1 -1
  35. package/dist/ipc.d.ts +19 -7
  36. package/dist/ipc.d.ts.map +1 -1
  37. package/dist/ipc.js +96 -70
  38. package/dist/ipc.js.map +1 -1
  39. package/dist/pins.d.ts.map +1 -1
  40. package/dist/pins.js +18 -3
  41. package/dist/pins.js.map +1 -1
  42. package/dist/state-storage.d.ts.map +1 -1
  43. package/dist/state-storage.js +2 -1
  44. package/dist/state-storage.js.map +1 -1
  45. package/dist/state.d.ts +1 -1
  46. package/dist/state.d.ts.map +1 -1
  47. package/dist/state.js +3 -2
  48. package/dist/state.js.map +1 -1
  49. package/dist/swarm-files.d.ts.map +1 -1
  50. package/dist/swarm-files.js +7 -2
  51. package/dist/swarm-files.js.map +1 -1
  52. package/dist/swarm.d.ts +10 -1
  53. package/dist/swarm.d.ts.map +1 -1
  54. package/dist/swarm.js +230 -56
  55. package/dist/swarm.js.map +1 -1
  56. package/package.json +4 -4
  57. package/src/cli-daemon.ts +482 -0
  58. package/src/cli.ts +1689 -1948
  59. package/src/daemon-api.ts +3148 -0
  60. package/src/daemon-client.ts +975 -0
  61. package/src/daemon-protocol.ts +61 -0
  62. package/src/daemon-telemetry.ts +656 -0
  63. package/src/daemon-ui.ts +361 -4
  64. package/src/daemon.ts +337 -43
  65. package/src/identity.ts +10 -2
  66. package/src/ipc.ts +113 -79
  67. package/src/pins.ts +23 -3
  68. package/src/state-storage.ts +5 -1
  69. package/src/state.ts +3 -1
  70. package/src/swarm-files.ts +10 -2
  71. package/src/swarm.ts +698 -464
@@ -0,0 +1,61 @@
1
+ export interface DaemonErrorPayload {
2
+ code: string;
3
+ message: string;
4
+ exitCode: number;
5
+ phase: string;
6
+ }
7
+
8
+ export type DaemonNdjsonFrame =
9
+ | { type: "diagnostic"; text: string; progress?: boolean }
10
+ | { type: "result"; data: unknown }
11
+ | ({ type: "error" } & DaemonErrorPayload);
12
+
13
+ export interface EncodedBytes {
14
+ __ipabBytes: string;
15
+ }
16
+
17
+ export function encodeIpcValue(value: unknown): unknown {
18
+ if (value instanceof Uint8Array) {
19
+ return {
20
+ __ipabBytes: Buffer.from(
21
+ value.buffer,
22
+ value.byteOffset,
23
+ value.byteLength,
24
+ ).toString("base64"),
25
+ } satisfies EncodedBytes;
26
+ }
27
+ if (Array.isArray(value)) {
28
+ return value.map((item) => encodeIpcValue(item));
29
+ }
30
+ if (value && typeof value === "object") {
31
+ const out: Record<string, unknown> = {};
32
+ for (const [k, v] of Object.entries(value)) {
33
+ out[k] = encodeIpcValue(v);
34
+ }
35
+ return out;
36
+ }
37
+ return value;
38
+ }
39
+
40
+ export function decodeIpcValue(value: unknown): unknown {
41
+ if (Array.isArray(value)) {
42
+ return value.map((item) => decodeIpcValue(item));
43
+ }
44
+ if (value && typeof value === "object") {
45
+ const record = value as Record<string, unknown>;
46
+ const keys = Object.keys(record);
47
+ if (
48
+ keys.length === 1 &&
49
+ keys[0] === "__ipabBytes" &&
50
+ typeof record.__ipabBytes === "string"
51
+ ) {
52
+ return new Uint8Array(Buffer.from(record.__ipabBytes, "base64"));
53
+ }
54
+ const out: Record<string, unknown> = {};
55
+ for (const [k, v] of Object.entries(record)) {
56
+ out[k] = decodeIpcValue(v);
57
+ }
58
+ return out;
59
+ }
60
+ return value;
61
+ }
@@ -0,0 +1,656 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, open, rename, stat } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import type { DatabaseSync, StatementSync } from "node:sqlite";
7
+ import {
8
+ redactDaemonText,
9
+ type DaemonActiveTask,
10
+ type DaemonObservabilitySnapshot,
11
+ type DaemonRequestSummary,
12
+ type DaemonSlowEvent,
13
+ type DaemonSqlStat,
14
+ type DaemonTelemetryThresholds,
15
+ type TelemetryCoordinationPhase,
16
+ type TelemetryDbName,
17
+ type TelemetryRequestStatus,
18
+ type TelemetrySource,
19
+ } from "./daemon-ui.js";
20
+
21
+ export type {
22
+ DaemonActiveTask,
23
+ DaemonObservabilitySnapshot,
24
+ DaemonRequestSummary,
25
+ DaemonSlowEvent,
26
+ DaemonSqlStat,
27
+ DaemonTelemetryThresholds,
28
+ TelemetryCoordinationPhase,
29
+ TelemetryDbName,
30
+ TelemetryRequestStatus,
31
+ TelemetrySource,
32
+ };
33
+
34
+ export const defaultSlowSqlMs = 50;
35
+ export const defaultSlowCoordMs = 100;
36
+ export const defaultSlowOpMs = 2000;
37
+ export const defaultRecentRequestLimit = 200;
38
+ export const defaultSlowEventLimit = 200;
39
+ export const defaultSqlStatSnapshotLimit = 50;
40
+ export const defaultMaxSqlStatKeys = 1000;
41
+ export const defaultTelemetryLogMaxBytes = 5 * 1024 * 1024;
42
+ export const telemetryLogFilename = "telemetry.log";
43
+
44
+ export interface RequestTraceContext {
45
+ readonly requestId: string;
46
+ readonly source: TelemetrySource;
47
+ readonly operation: string;
48
+ readonly swarm: string | null;
49
+ readonly startedAtMs: number;
50
+ readonly startedAtPerf: number;
51
+ sqlCount: number;
52
+ sqlDurationMs: number;
53
+ prepareDurationMs: number;
54
+ }
55
+
56
+ export interface RunWithContextMeta {
57
+ source: TelemetrySource;
58
+ operation: string;
59
+ swarm?: string | null;
60
+ requestId?: string;
61
+ }
62
+
63
+ export interface RecordSqlEvent {
64
+ db: TelemetryDbName;
65
+ op: string;
66
+ sql: string;
67
+ durationMs: number;
68
+ error?: string;
69
+ }
70
+
71
+ export interface RecordCoordinationEvent {
72
+ op: string;
73
+ phase: TelemetryCoordinationPhase;
74
+ durationMs: number;
75
+ error?: string;
76
+ }
77
+
78
+ export interface DaemonTelemetryOptions {
79
+ slowSqlMs?: number;
80
+ slowCoordMs?: number;
81
+ slowOpMs?: number;
82
+ traceSql?: boolean;
83
+ env?: NodeJS.ProcessEnv;
84
+ logPath?: string;
85
+ maxLogBytes?: number;
86
+ maxRecentRequests?: number;
87
+ maxSlowEvents?: number;
88
+ maxSqlStats?: number;
89
+ secrets?: () => readonly (string | undefined)[];
90
+ }
91
+
92
+ function roundMs(value: number): number {
93
+ if (!Number.isFinite(value) || value <= 0) return 0;
94
+ return Math.round(value * 100) / 100;
95
+ }
96
+
97
+ function parseNonNegativeMs(
98
+ explicit: number | undefined,
99
+ envValue: string | undefined,
100
+ fallback: number,
101
+ ): number {
102
+ if (explicit !== undefined && Number.isFinite(explicit) && explicit >= 0) {
103
+ return explicit;
104
+ }
105
+ if (envValue !== undefined && envValue.trim() !== "") {
106
+ const parsed = Number(envValue.trim());
107
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
108
+ }
109
+ return fallback;
110
+ }
111
+
112
+ function parseBooleanFlag(
113
+ explicit: boolean | undefined,
114
+ envValue: string | undefined,
115
+ ): boolean {
116
+ if (explicit !== undefined) return explicit;
117
+ if (envValue === undefined) return false;
118
+ const normalized = envValue.trim().toLowerCase();
119
+ return normalized === "1" || normalized === "true";
120
+ }
121
+
122
+ export function resolveTelemetryThresholds(
123
+ options: Pick<
124
+ DaemonTelemetryOptions,
125
+ "slowSqlMs" | "slowCoordMs" | "slowOpMs" | "traceSql" | "env"
126
+ > = {},
127
+ ): DaemonTelemetryThresholds {
128
+ const env = options.env ?? process.env;
129
+ return {
130
+ slowSqlMs: parseNonNegativeMs(
131
+ options.slowSqlMs,
132
+ env.IPAB_DAEMON_SLOW_SQL_MS,
133
+ defaultSlowSqlMs,
134
+ ),
135
+ slowCoordMs: parseNonNegativeMs(
136
+ options.slowCoordMs,
137
+ env.IPAB_DAEMON_SLOW_COORD_MS,
138
+ defaultSlowCoordMs,
139
+ ),
140
+ slowOpMs: parseNonNegativeMs(
141
+ options.slowOpMs,
142
+ env.IPAB_DAEMON_SLOW_OP_MS,
143
+ defaultSlowOpMs,
144
+ ),
145
+ traceSql: parseBooleanFlag(options.traceSql, env.IPAB_DAEMON_TRACE_SQL),
146
+ };
147
+ }
148
+
149
+ export function normalizeSqlFingerprint(sql: string, maxLength = 240): string {
150
+ const stripped = sql
151
+ .replace(/'(?:''|[^'])*'/g, "'?'")
152
+ .replace(/\s+/g, " ")
153
+ .trim();
154
+ if (stripped.length <= maxLength) return stripped;
155
+ return `${stripped.slice(0, Math.max(0, maxLength - 3))}...`;
156
+ }
157
+
158
+ function formatError(cause: unknown): string {
159
+ if (cause instanceof Error) {
160
+ const record = cause as Error & { code?: unknown; errstr?: unknown };
161
+ const code =
162
+ typeof record.code === "string" && record.code.length > 0
163
+ ? record.code
164
+ : typeof record.errstr === "string" && record.errstr.length > 0
165
+ ? record.errstr
166
+ : undefined;
167
+ return code && !cause.message.includes(code)
168
+ ? `${code}: ${cause.message}`
169
+ : cause.message;
170
+ }
171
+ return String(cause);
172
+ }
173
+
174
+ function isAbortError(cause: unknown): boolean {
175
+ return (
176
+ cause instanceof Error &&
177
+ (cause.name === "AbortError" ||
178
+ (cause as Error & { code?: unknown }).code === "ABORT_ERR")
179
+ );
180
+ }
181
+
182
+ function pushBounded<T>(items: T[], entry: T, limit: number): void {
183
+ items.push(entry);
184
+ if (items.length > limit) {
185
+ items.splice(0, items.length - limit);
186
+ }
187
+ }
188
+
189
+ export class DaemonTelemetry {
190
+ readonly thresholds: DaemonTelemetryThresholds;
191
+
192
+ private readonly storage = new AsyncLocalStorage<RequestTraceContext>();
193
+ private readonly activeTasks = new Map<string, RequestTraceContext>();
194
+ private readonly recentRequests: DaemonRequestSummary[] = [];
195
+ private readonly slowEvents: DaemonSlowEvent[] = [];
196
+ private readonly sqlStats = new Map<string, DaemonSqlStat>();
197
+ private readonly wrappedDatabases = new WeakSet<object>();
198
+
199
+ private readonly logPath: string | undefined;
200
+ private readonly maxLogBytes: number;
201
+ private readonly maxRecentRequests: number;
202
+ private readonly maxSlowEvents: number;
203
+ private readonly maxSqlStats: number;
204
+ private readonly getSecrets: () => readonly (string | undefined)[];
205
+
206
+ private eventSeq = 0;
207
+ private writeChain: Promise<void> = Promise.resolve();
208
+
209
+ constructor(options: DaemonTelemetryOptions = {}) {
210
+ this.thresholds = resolveTelemetryThresholds(options);
211
+ this.logPath = options.logPath;
212
+ this.maxLogBytes =
213
+ options.maxLogBytes !== undefined &&
214
+ Number.isFinite(options.maxLogBytes) &&
215
+ options.maxLogBytes > 0
216
+ ? options.maxLogBytes
217
+ : defaultTelemetryLogMaxBytes;
218
+ this.maxRecentRequests = Math.max(
219
+ 1,
220
+ options.maxRecentRequests ?? defaultRecentRequestLimit,
221
+ );
222
+ this.maxSlowEvents = Math.max(
223
+ 1,
224
+ options.maxSlowEvents ?? defaultSlowEventLimit,
225
+ );
226
+ this.maxSqlStats = Math.max(
227
+ 1,
228
+ options.maxSqlStats ?? defaultSqlStatSnapshotLimit,
229
+ );
230
+ this.getSecrets = options.secrets ?? (() => []);
231
+ }
232
+
233
+ currentContext(): RequestTraceContext | undefined {
234
+ return this.storage.getStore();
235
+ }
236
+
237
+ async runWithContext<T>(
238
+ meta: RunWithContextMeta,
239
+ fn: (ctx: RequestTraceContext) => Promise<T> | T,
240
+ ): Promise<T> {
241
+ const startedAtMs = Date.now();
242
+ const ctx: RequestTraceContext = {
243
+ requestId: meta.requestId ?? randomUUID(),
244
+ source: meta.source,
245
+ operation: this.sanitize(meta.operation),
246
+ swarm: meta.swarm ? this.sanitize(meta.swarm) : null,
247
+ startedAtMs,
248
+ startedAtPerf: performance.now(),
249
+ sqlCount: 0,
250
+ sqlDurationMs: 0,
251
+ prepareDurationMs: 0,
252
+ };
253
+
254
+ this.activeTasks.set(ctx.requestId, ctx);
255
+ let status: TelemetryRequestStatus = "ok";
256
+ let errorText: string | null = null;
257
+ try {
258
+ return await this.storage.run(ctx, () => fn(ctx));
259
+ } catch (cause) {
260
+ status = isAbortError(cause) ? "cancelled" : "error";
261
+ errorText = this.sanitize(formatError(cause));
262
+ throw cause;
263
+ } finally {
264
+ this.activeTasks.delete(ctx.requestId);
265
+ const finishedAtMs = Date.now();
266
+ const durationMs = roundMs(performance.now() - ctx.startedAtPerf);
267
+ const summary: DaemonRequestSummary = {
268
+ requestId: ctx.requestId,
269
+ source: ctx.source,
270
+ operation: ctx.operation,
271
+ swarm: ctx.swarm,
272
+ startedAt: new Date(ctx.startedAtMs).toISOString(),
273
+ finishedAt: new Date(finishedAtMs).toISOString(),
274
+ durationMs,
275
+ status,
276
+ sqlCount: ctx.sqlCount,
277
+ sqlDurationMs: roundMs(ctx.sqlDurationMs),
278
+ prepareDurationMs: roundMs(ctx.prepareDurationMs),
279
+ error: errorText,
280
+ };
281
+ pushBounded(this.recentRequests, summary, this.maxRecentRequests);
282
+
283
+ if (status !== "ok" || durationMs >= this.thresholds.slowOpMs) {
284
+ const event: DaemonSlowEvent = {
285
+ seq: ++this.eventSeq,
286
+ time: summary.finishedAt,
287
+ kind: "request",
288
+ requestId: ctx.requestId,
289
+ source: ctx.source,
290
+ operation: ctx.operation,
291
+ swarm: ctx.swarm,
292
+ db: null,
293
+ sqlOp: null,
294
+ phase: null,
295
+ fingerprint: null,
296
+ durationMs,
297
+ error: errorText,
298
+ };
299
+ pushBounded(this.slowEvents, event, this.maxSlowEvents);
300
+ this.enqueueLog(event);
301
+ }
302
+ }
303
+ }
304
+
305
+ recordSql(event: RecordSqlEvent): void {
306
+ const durationMs = roundMs(event.durationMs);
307
+ const fingerprint = this.sanitize(normalizeSqlFingerprint(event.sql));
308
+ const isSlow = durationMs >= this.thresholds.slowSqlMs;
309
+ const errorText = event.error ? this.sanitize(event.error) : null;
310
+ const hasError = errorText !== null;
311
+
312
+ const key = `${event.db}:${event.op}:${fingerprint}`;
313
+ const existing = this.sqlStats.get(key);
314
+ if (existing) {
315
+ existing.count += 1;
316
+ existing.totalMs = roundMs(existing.totalMs + durationMs);
317
+ if (durationMs > existing.maxMs) existing.maxMs = durationMs;
318
+ if (isSlow) existing.slowCount += 1;
319
+ if (hasError) existing.errorCount += 1;
320
+ } else if (this.sqlStats.size < defaultMaxSqlStatKeys) {
321
+ this.sqlStats.set(key, {
322
+ db: event.db,
323
+ op: event.op,
324
+ fingerprint,
325
+ count: 1,
326
+ totalMs: durationMs,
327
+ maxMs: durationMs,
328
+ slowCount: isSlow ? 1 : 0,
329
+ errorCount: hasError ? 1 : 0,
330
+ });
331
+ }
332
+
333
+ const ctx = this.storage.getStore();
334
+ if (ctx) {
335
+ ctx.sqlCount += 1;
336
+ ctx.sqlDurationMs = roundMs(ctx.sqlDurationMs + durationMs);
337
+ }
338
+
339
+ if (isSlow || hasError || this.thresholds.traceSql) {
340
+ const record: DaemonSlowEvent = {
341
+ seq: ++this.eventSeq,
342
+ time: new Date().toISOString(),
343
+ kind: "sql",
344
+ requestId: ctx?.requestId ?? null,
345
+ source: ctx?.source ?? null,
346
+ operation: ctx?.operation ?? `sql:${event.op}`,
347
+ swarm: ctx?.swarm ?? null,
348
+ db: event.db,
349
+ sqlOp: event.op,
350
+ phase: null,
351
+ fingerprint,
352
+ durationMs,
353
+ error: errorText,
354
+ };
355
+ if (isSlow || hasError) {
356
+ pushBounded(this.slowEvents, record, this.maxSlowEvents);
357
+ }
358
+ this.enqueueLog(record);
359
+ }
360
+ }
361
+
362
+ recordCoordination(event: RecordCoordinationEvent): void {
363
+ const durationMs = roundMs(event.durationMs);
364
+ const ctx = this.storage.getStore();
365
+ if (ctx && event.phase === "prepare") {
366
+ ctx.prepareDurationMs = roundMs(ctx.prepareDurationMs + durationMs);
367
+ }
368
+
369
+ const threshold =
370
+ event.phase === "prepare"
371
+ ? this.thresholds.slowOpMs
372
+ : this.thresholds.slowCoordMs;
373
+ const isSlow = durationMs >= threshold;
374
+ const errorText = event.error ? this.sanitize(event.error) : null;
375
+ const hasError = errorText !== null;
376
+
377
+ if (isSlow || hasError) {
378
+ const record: DaemonSlowEvent = {
379
+ seq: ++this.eventSeq,
380
+ time: new Date().toISOString(),
381
+ kind: "coordination",
382
+ requestId: ctx?.requestId ?? null,
383
+ source: ctx?.source ?? null,
384
+ operation: this.sanitize(event.op),
385
+ swarm: ctx?.swarm ?? null,
386
+ db: null,
387
+ sqlOp: null,
388
+ phase: event.phase,
389
+ fingerprint: null,
390
+ durationMs,
391
+ error: errorText,
392
+ };
393
+ pushBounded(this.slowEvents, record, this.maxSlowEvents);
394
+ this.enqueueLog(record);
395
+ }
396
+ }
397
+
398
+ wrapDatabase<T extends DatabaseSync>(db: T, dbName: TelemetryDbName): T {
399
+ if (this.wrappedDatabases.has(db)) return db;
400
+
401
+ const wrapStatement = (
402
+ statement: StatementSync,
403
+ sql: string,
404
+ ): StatementSync =>
405
+ new Proxy(statement, {
406
+ get: (target, prop) => {
407
+ if (prop === "get") {
408
+ return (
409
+ ...args: Parameters<StatementSync["get"]>
410
+ ): ReturnType<StatementSync["get"]> => {
411
+ const start = performance.now();
412
+ try {
413
+ const result = target.get(...args);
414
+ this.recordSql({
415
+ db: dbName,
416
+ op: "get",
417
+ sql,
418
+ durationMs: performance.now() - start,
419
+ });
420
+ return result;
421
+ } catch (cause) {
422
+ this.recordSql({
423
+ db: dbName,
424
+ op: "get",
425
+ sql,
426
+ durationMs: performance.now() - start,
427
+ error: formatError(cause),
428
+ });
429
+ throw cause;
430
+ }
431
+ };
432
+ }
433
+ if (prop === "all") {
434
+ return (
435
+ ...args: Parameters<StatementSync["all"]>
436
+ ): ReturnType<StatementSync["all"]> => {
437
+ const start = performance.now();
438
+ try {
439
+ const result = target.all(...args);
440
+ this.recordSql({
441
+ db: dbName,
442
+ op: "all",
443
+ sql,
444
+ durationMs: performance.now() - start,
445
+ });
446
+ return result;
447
+ } catch (cause) {
448
+ this.recordSql({
449
+ db: dbName,
450
+ op: "all",
451
+ sql,
452
+ durationMs: performance.now() - start,
453
+ error: formatError(cause),
454
+ });
455
+ throw cause;
456
+ }
457
+ };
458
+ }
459
+ if (prop === "run") {
460
+ return (
461
+ ...args: Parameters<StatementSync["run"]>
462
+ ): ReturnType<StatementSync["run"]> => {
463
+ const start = performance.now();
464
+ try {
465
+ const result = target.run(...args);
466
+ this.recordSql({
467
+ db: dbName,
468
+ op: "run",
469
+ sql,
470
+ durationMs: performance.now() - start,
471
+ });
472
+ return result;
473
+ } catch (cause) {
474
+ this.recordSql({
475
+ db: dbName,
476
+ op: "run",
477
+ sql,
478
+ durationMs: performance.now() - start,
479
+ error: formatError(cause),
480
+ });
481
+ throw cause;
482
+ }
483
+ };
484
+ }
485
+ const value: unknown = Reflect.get(target, prop, target);
486
+ return typeof value === "function"
487
+ ? (value.bind(target) as unknown)
488
+ : value;
489
+ },
490
+ });
491
+
492
+ const proxy = new Proxy(db, {
493
+ get: (target, prop) => {
494
+ if (prop === "exec") {
495
+ return (sql: string): void => {
496
+ const start = performance.now();
497
+ try {
498
+ target.exec(sql);
499
+ this.recordSql({
500
+ db: dbName,
501
+ op: "exec",
502
+ sql,
503
+ durationMs: performance.now() - start,
504
+ });
505
+ } catch (cause) {
506
+ this.recordSql({
507
+ db: dbName,
508
+ op: "exec",
509
+ sql,
510
+ durationMs: performance.now() - start,
511
+ error: formatError(cause),
512
+ });
513
+ throw cause;
514
+ }
515
+ };
516
+ }
517
+ if (prop === "prepare") {
518
+ return (sql: string): StatementSync => {
519
+ const start = performance.now();
520
+ try {
521
+ const statement = target.prepare(sql);
522
+ return wrapStatement(statement, sql);
523
+ } catch (cause) {
524
+ this.recordSql({
525
+ db: dbName,
526
+ op: "prepare",
527
+ sql,
528
+ durationMs: performance.now() - start,
529
+ error: formatError(cause),
530
+ });
531
+ throw cause;
532
+ }
533
+ };
534
+ }
535
+ const value: unknown = Reflect.get(target, prop, target);
536
+ return typeof value === "function"
537
+ ? (value.bind(target) as unknown)
538
+ : value;
539
+ },
540
+ });
541
+
542
+ this.wrappedDatabases.add(proxy);
543
+ return proxy;
544
+ }
545
+
546
+ snapshot(
547
+ secrets: readonly (string | undefined)[] = [],
548
+ ): DaemonObservabilitySnapshot {
549
+ const allSecrets = this.collectSecrets(secrets);
550
+ const redact = (value: string): string =>
551
+ redactDaemonText(value, allSecrets);
552
+ const redactNullable = (value: string | null): string | null =>
553
+ value === null ? null : redact(value);
554
+
555
+ const nowPerf = performance.now();
556
+ const activeTasks: DaemonActiveTask[] = [...this.activeTasks.values()].map(
557
+ (ctx) => ({
558
+ requestId: ctx.requestId,
559
+ source: ctx.source,
560
+ operation: redact(ctx.operation),
561
+ swarm: redactNullable(ctx.swarm),
562
+ startedAt: new Date(ctx.startedAtMs).toISOString(),
563
+ elapsedMs: roundMs(nowPerf - ctx.startedAtPerf),
564
+ sqlCount: ctx.sqlCount,
565
+ sqlDurationMs: roundMs(ctx.sqlDurationMs),
566
+ prepareDurationMs: roundMs(ctx.prepareDurationMs),
567
+ }),
568
+ );
569
+
570
+ const recentRequests: DaemonRequestSummary[] = this.recentRequests.map(
571
+ (entry) => ({
572
+ ...entry,
573
+ operation: redact(entry.operation),
574
+ swarm: redactNullable(entry.swarm),
575
+ error: redactNullable(entry.error),
576
+ }),
577
+ );
578
+
579
+ const slowEvents: DaemonSlowEvent[] = this.slowEvents.map((entry) => ({
580
+ ...entry,
581
+ operation: redact(entry.operation),
582
+ swarm: redactNullable(entry.swarm),
583
+ fingerprint: redactNullable(entry.fingerprint),
584
+ error: redactNullable(entry.error),
585
+ }));
586
+
587
+ const sqlStats: DaemonSqlStat[] = [...this.sqlStats.values()]
588
+ .sort(
589
+ (a, b) =>
590
+ b.totalMs - a.totalMs ||
591
+ b.count - a.count ||
592
+ a.fingerprint.localeCompare(b.fingerprint),
593
+ )
594
+ .slice(0, this.maxSqlStats)
595
+ .map((entry) => ({
596
+ ...entry,
597
+ fingerprint: redact(entry.fingerprint),
598
+ }));
599
+
600
+ return {
601
+ activeTasks,
602
+ recentRequests,
603
+ slowEvents,
604
+ sqlStats,
605
+ thresholds: { ...this.thresholds },
606
+ };
607
+ }
608
+
609
+ async flush(): Promise<void> {
610
+ await this.writeChain;
611
+ }
612
+
613
+ private collectSecrets(
614
+ extra: readonly (string | undefined)[] = [],
615
+ ): readonly (string | undefined)[] {
616
+ const base = this.getSecrets();
617
+ if (!extra.length) return base;
618
+ if (!base.length) return extra;
619
+ return [...base, ...extra];
620
+ }
621
+
622
+ private sanitize(text: string): string {
623
+ return redactDaemonText(text, this.getSecrets());
624
+ }
625
+
626
+ private enqueueLog(record: DaemonSlowEvent): void {
627
+ const targetPath = this.logPath;
628
+ if (!targetPath) return;
629
+
630
+ const rawLine = JSON.stringify(record);
631
+ const sanitizedLine = `${redactDaemonText(rawLine, this.getSecrets())}\n`;
632
+ const byteLength = Buffer.byteLength(sanitizedLine, "utf8");
633
+
634
+ this.writeChain = this.writeChain.then(async () => {
635
+ try {
636
+ await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 });
637
+ try {
638
+ const info = await stat(targetPath);
639
+ if (info.size > 0 && info.size + byteLength > this.maxLogBytes) {
640
+ await rename(targetPath, `${targetPath}.1`);
641
+ }
642
+ } catch {
643
+ // File does not exist yet or cannot be stat'd; proceed to append.
644
+ }
645
+ const handle = await open(targetPath, "a", 0o600);
646
+ try {
647
+ await handle.writeFile(sanitizedLine, "utf8");
648
+ } finally {
649
+ await handle.close();
650
+ }
651
+ } catch {
652
+ // Non-blocking error-safe telemetry writer: never break business logic.
653
+ }
654
+ });
655
+ }
656
+ }