sentinelayer-cli 0.4.4 → 0.6.2

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 (149) hide show
  1. package/README.md +996 -998
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -0
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1166 -1166
  67. package/src/commands/auth.js +419 -375
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -21
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -1,626 +1,626 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import fsp from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- import { resolveOutputRoot } from "../config/service.js";
6
-
7
- const QUEUE_SCHEMA_VERSION = "1.0.0";
8
- const STATE_SCHEMA_VERSION = "1.0.0";
9
- const DEFAULT_MAX_EVENTS = 200;
10
-
11
- const TERMINAL_WORK_ITEM_STATUSES = new Set(["DONE", "SQUASHED"]);
12
-
13
- export const WORK_ITEM_STATUSES = Object.freeze([
14
- "QUEUED",
15
- "ASSIGNED",
16
- "IN_PROGRESS",
17
- "BLOCKED",
18
- "DONE",
19
- "SQUASHED",
20
- ]);
21
-
22
- const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
23
-
24
- const SEVERITY_RANK = new Map([
25
- ["UNKNOWN", 0],
26
- ["P3", 1],
27
- ["P2", 2],
28
- ["P1", 3],
29
- ["P0", 4],
30
- ]);
31
-
32
- function normalizeString(value) {
33
- return String(value || "").trim();
34
- }
35
-
36
- function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
37
- const normalized = normalizeString(value);
38
- if (!normalized) {
39
- return fallbackIso;
40
- }
41
- const epoch = Date.parse(normalized);
42
- if (!Number.isFinite(epoch)) {
43
- return fallbackIso;
44
- }
45
- return new Date(epoch).toISOString();
46
- }
47
-
48
- function normalizeNonNegativeInteger(value, fallbackValue = 0) {
49
- if (value === undefined || value === null || normalizeString(value) === "") {
50
- return fallbackValue;
51
- }
52
- const normalized = Number(value);
53
- if (!Number.isFinite(normalized) || normalized < 0) {
54
- throw new Error("Value must be a non-negative integer.");
55
- }
56
- return Math.floor(normalized);
57
- }
58
-
59
- function normalizePositiveInteger(value, fallbackValue = 1) {
60
- if (value === undefined || value === null || normalizeString(value) === "") {
61
- return fallbackValue;
62
- }
63
- const normalized = Number(value);
64
- if (!Number.isFinite(normalized) || normalized <= 0) {
65
- throw new Error("Value must be a positive integer.");
66
- }
67
- return Math.floor(normalized);
68
- }
69
-
70
- function stableTimestampForFile(date = new Date()) {
71
- return date.toISOString().replace(/[:.]/g, "-");
72
- }
73
-
74
- function normalizeSeverity(value) {
75
- const normalized = normalizeString(value).toUpperCase();
76
- if (normalized === "P0" || normalized === "P1" || normalized === "P2" || normalized === "P3") {
77
- return normalized;
78
- }
79
- return "UNKNOWN";
80
- }
81
-
82
- function normalizeMetadata(value) {
83
- if (!value || typeof value !== "object" || Array.isArray(value)) {
84
- return {};
85
- }
86
- return { ...value };
87
- }
88
-
89
- function normalizeStackTrace(value) {
90
- return String(value || "").replace(/\r\n/g, "\n").trim();
91
- }
92
-
93
- function computeStackFingerprint(stackTrace = "") {
94
- const normalized = normalizeStackTrace(stackTrace);
95
- if (!normalized) {
96
- return "none";
97
- }
98
- const reduced = normalized
99
- .split("\n")
100
- .map((line) => line.trim())
101
- .filter(Boolean)
102
- .slice(0, 6)
103
- .join("|");
104
- if (!reduced) {
105
- return "none";
106
- }
107
- return createHash("sha256").update(reduced).digest("hex");
108
- }
109
-
110
- function computeFingerprint(event = {}) {
111
- const materialized = [
112
- normalizeString(event.service).toLowerCase(),
113
- normalizeString(event.endpoint).toLowerCase(),
114
- normalizeString(event.errorCode).toLowerCase(),
115
- normalizeString(event.stackFingerprint).toLowerCase(),
116
- normalizeString(event.commitSha).toLowerCase(),
117
- ].join("|");
118
- return createHash("sha256").update(materialized).digest("hex");
119
- }
120
-
121
- function chooseHigherSeverity(left, right) {
122
- const leftNormalized = normalizeSeverity(left);
123
- const rightNormalized = normalizeSeverity(right);
124
- const leftRank = SEVERITY_RANK.get(leftNormalized) ?? 0;
125
- const rightRank = SEVERITY_RANK.get(rightNormalized) ?? 0;
126
- return rightRank > leftRank ? rightNormalized : leftNormalized;
127
- }
128
-
129
- function toSeverityRank(value) {
130
- return SEVERITY_RANK.get(normalizeSeverity(value)) ?? 0;
131
- }
132
-
133
- function createWorkItemId(nowIso = new Date().toISOString()) {
134
- return `err-${stableTimestampForFile(new Date(nowIso))}-${randomUUID().slice(0, 8)}`;
135
- }
136
-
137
- function normalizeWorkItemStatus(value) {
138
- const normalized = normalizeString(value).toUpperCase();
139
- if (WORK_ITEM_STATUS_SET.has(normalized)) {
140
- return normalized;
141
- }
142
- return "QUEUED";
143
- }
144
-
145
- function isTerminalStatus(status = "") {
146
- return TERMINAL_WORK_ITEM_STATUSES.has(normalizeWorkItemStatus(status));
147
- }
148
-
149
- function normalizeQueueItem(item = {}, fallbackNowIso = new Date().toISOString()) {
150
- const createdAt = normalizeIsoTimestamp(item.createdAt, fallbackNowIso);
151
- return {
152
- workItemId: normalizeString(item.workItemId) || createWorkItemId(createdAt),
153
- fingerprint: normalizeString(item.fingerprint),
154
- source: normalizeString(item.source) || "admin_error_log",
155
- service: normalizeString(item.service) || "unknown-service",
156
- endpoint: normalizeString(item.endpoint) || "unknown-endpoint",
157
- errorCode: normalizeString(item.errorCode) || "UNKNOWN_ERROR",
158
- severity: normalizeSeverity(item.severity),
159
- status: normalizeWorkItemStatus(item.status),
160
- message: normalizeString(item.message),
161
- stackFingerprint: normalizeString(item.stackFingerprint) || "none",
162
- commitSha: normalizeString(item.commitSha) || null,
163
- firstSeenAt: normalizeIsoTimestamp(item.firstSeenAt, createdAt),
164
- lastSeenAt: normalizeIsoTimestamp(item.lastSeenAt, createdAt),
165
- latestEventId: normalizeString(item.latestEventId) || null,
166
- occurrenceCount: Math.max(1, normalizeNonNegativeInteger(item.occurrenceCount, 1)),
167
- createdAt,
168
- updatedAt: normalizeIsoTimestamp(item.updatedAt, createdAt),
169
- metadata: normalizeMetadata(item.metadata),
170
- };
171
- }
172
-
173
- function getQueueInitialState(nowIso = new Date().toISOString()) {
174
- return {
175
- schemaVersion: QUEUE_SCHEMA_VERSION,
176
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
177
- items: [],
178
- };
179
- }
180
-
181
- function getWorkerStateInitial(nowIso = new Date().toISOString()) {
182
- return {
183
- schemaVersion: STATE_SCHEMA_VERSION,
184
- updatedAt: normalizeIsoTimestamp(nowIso, nowIso),
185
- lastRunAt: null,
186
- streamOffset: 0,
187
- runCount: 0,
188
- totalProcessedEvents: 0,
189
- totalQueuedItems: 0,
190
- totalDedupeHits: 0,
191
- };
192
- }
193
-
194
- async function loadQueueFile(queuePath, nowIso = new Date().toISOString()) {
195
- try {
196
- const raw = await fsp.readFile(queuePath, "utf-8");
197
- const parsed = JSON.parse(raw);
198
- const items = Array.isArray(parsed.items)
199
- ? parsed.items
200
- .map((item) => normalizeQueueItem(item, nowIso))
201
- .filter((item) => normalizeString(item.fingerprint))
202
- : [];
203
- return {
204
- schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
205
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
206
- items,
207
- };
208
- } catch (error) {
209
- if (error && typeof error === "object" && error.code === "ENOENT") {
210
- return getQueueInitialState(nowIso);
211
- }
212
- throw error;
213
- }
214
- }
215
-
216
- async function writeQueueFile(queuePath, queue = {}, nowIso = new Date().toISOString()) {
217
- const normalized = {
218
- schemaVersion: QUEUE_SCHEMA_VERSION,
219
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
220
- items: Array.isArray(queue.items)
221
- ? queue.items
222
- .map((item) => normalizeQueueItem(item, nowIso))
223
- .filter((item) => normalizeString(item.fingerprint))
224
- : [],
225
- };
226
- await fsp.mkdir(path.dirname(queuePath), { recursive: true });
227
- await fsp.writeFile(queuePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf-8");
228
- return normalized;
229
- }
230
-
231
- async function loadWorkerStateFile(statePath, nowIso = new Date().toISOString()) {
232
- try {
233
- const raw = await fsp.readFile(statePath, "utf-8");
234
- const parsed = JSON.parse(raw);
235
- return {
236
- schemaVersion: normalizeString(parsed.schemaVersion) || STATE_SCHEMA_VERSION,
237
- updatedAt: normalizeIsoTimestamp(parsed.updatedAt, nowIso),
238
- lastRunAt: parsed.lastRunAt ? normalizeIsoTimestamp(parsed.lastRunAt, nowIso) : null,
239
- streamOffset: normalizeNonNegativeInteger(parsed.streamOffset, 0),
240
- runCount: normalizeNonNegativeInteger(parsed.runCount, 0),
241
- totalProcessedEvents: normalizeNonNegativeInteger(parsed.totalProcessedEvents, 0),
242
- totalQueuedItems: normalizeNonNegativeInteger(parsed.totalQueuedItems, 0),
243
- totalDedupeHits: normalizeNonNegativeInteger(parsed.totalDedupeHits, 0),
244
- };
245
- } catch (error) {
246
- if (error && typeof error === "object" && error.code === "ENOENT") {
247
- return getWorkerStateInitial(nowIso);
248
- }
249
- throw error;
250
- }
251
- }
252
-
253
- async function writeWorkerStateFile(statePath, state = {}, nowIso = new Date().toISOString()) {
254
- const normalized = {
255
- schemaVersion: STATE_SCHEMA_VERSION,
256
- updatedAt: normalizeIsoTimestamp(nowIso, nowIso),
257
- lastRunAt: state.lastRunAt ? normalizeIsoTimestamp(state.lastRunAt, nowIso) : null,
258
- streamOffset: normalizeNonNegativeInteger(state.streamOffset, 0),
259
- runCount: normalizeNonNegativeInteger(state.runCount, 0),
260
- totalProcessedEvents: normalizeNonNegativeInteger(state.totalProcessedEvents, 0),
261
- totalQueuedItems: normalizeNonNegativeInteger(state.totalQueuedItems, 0),
262
- totalDedupeHits: normalizeNonNegativeInteger(state.totalDedupeHits, 0),
263
- };
264
- await fsp.mkdir(path.dirname(statePath), { recursive: true });
265
- await fsp.writeFile(statePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf-8");
266
- return normalized;
267
- }
268
-
269
- async function loadStreamLines(streamPath) {
270
- try {
271
- const raw = await fsp.readFile(streamPath, "utf-8");
272
- return raw
273
- .split(/\r?\n/)
274
- .map((line) => line.trim())
275
- .filter(Boolean);
276
- } catch (error) {
277
- if (error && typeof error === "object" && error.code === "ENOENT") {
278
- return [];
279
- }
280
- throw error;
281
- }
282
- }
283
-
284
- function buildWorkItemFromEvent(event, nowIso) {
285
- return normalizeQueueItem(
286
- {
287
- workItemId: createWorkItemId(nowIso),
288
- fingerprint: event.fingerprint,
289
- source: event.source,
290
- service: event.service,
291
- endpoint: event.endpoint,
292
- errorCode: event.errorCode,
293
- severity: event.severity,
294
- status: "QUEUED",
295
- message: event.message,
296
- stackFingerprint: event.stackFingerprint,
297
- commitSha: event.commitSha,
298
- firstSeenAt: event.occurredAt,
299
- lastSeenAt: event.occurredAt,
300
- latestEventId: event.eventId,
301
- occurrenceCount: 1,
302
- createdAt: nowIso,
303
- updatedAt: nowIso,
304
- metadata: {
305
- ...event.metadata,
306
- sourceEventId: event.eventId,
307
- },
308
- },
309
- nowIso
310
- );
311
- }
312
-
313
- export function normalizeErrorEvent(event = {}, nowIso = new Date().toISOString()) {
314
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
315
- const stackTrace = normalizeStackTrace(event.stackTrace || event.stack || "");
316
- const normalized = {
317
- eventId: normalizeString(event.eventId) || randomUUID(),
318
- occurredAt: normalizeIsoTimestamp(event.occurredAt, normalizedNow),
319
- recordedAt: normalizedNow,
320
- source: normalizeString(event.source) || "admin_error_log",
321
- service: normalizeString(event.service) || "unknown-service",
322
- endpoint: normalizeString(event.endpoint) || "unknown-endpoint",
323
- errorCode: normalizeString(event.errorCode) || "UNKNOWN_ERROR",
324
- severity: normalizeSeverity(event.severity),
325
- message: normalizeString(event.message) || "Unhandled runtime error",
326
- stackTrace,
327
- stackFingerprint: computeStackFingerprint(stackTrace),
328
- commitSha: normalizeString(event.commitSha) || null,
329
- metadata: normalizeMetadata(event.metadata),
330
- };
331
- return {
332
- ...normalized,
333
- fingerprint: computeFingerprint(normalized),
334
- };
335
- }
336
-
337
- export async function resolveErrorDaemonStorage({
338
- targetPath = ".",
339
- outputDir = "",
340
- env,
341
- homeDir,
342
- } = {}) {
343
- const outputRoot = await resolveOutputRoot({
344
- cwd: path.resolve(String(targetPath || ".")),
345
- outputDirOverride: outputDir,
346
- env,
347
- homeDir,
348
- });
349
- const baseDir = path.join(outputRoot, "observability", "error-daemon");
350
- return {
351
- outputRoot,
352
- baseDir,
353
- streamPath: path.join(baseDir, "admin-error-stream.ndjson"),
354
- queuePath: path.join(baseDir, "queue.json"),
355
- statePath: path.join(baseDir, "worker-state.json"),
356
- intakeDir: path.join(baseDir, "intake"),
357
- runsDir: path.join(baseDir, "runs"),
358
- };
359
- }
360
-
361
- export async function appendAdminErrorEvent({
362
- targetPath = ".",
363
- outputDir = "",
364
- event = {},
365
- env,
366
- homeDir,
367
- } = {}) {
368
- const nowIso = new Date().toISOString();
369
- const normalizedEvent = normalizeErrorEvent(event, nowIso);
370
- const storage = await resolveErrorDaemonStorage({
371
- targetPath,
372
- outputDir,
373
- env,
374
- homeDir,
375
- });
376
-
377
- await fsp.mkdir(storage.baseDir, { recursive: true });
378
- await fsp.appendFile(storage.streamPath, `${JSON.stringify(normalizedEvent)}\n`, "utf-8");
379
-
380
- await fsp.mkdir(storage.intakeDir, { recursive: true });
381
- const intakePath = path.join(
382
- storage.intakeDir,
383
- `intake-${stableTimestampForFile(new Date(normalizedEvent.recordedAt))}-${normalizedEvent.eventId.slice(0, 8)}.json`
384
- );
385
- await fsp.writeFile(
386
- intakePath,
387
- `${JSON.stringify(
388
- {
389
- schemaVersion: "1.0.0",
390
- generatedAt: nowIso,
391
- event: normalizedEvent,
392
- },
393
- null,
394
- 2
395
- )}\n`,
396
- "utf-8"
397
- );
398
-
399
- return {
400
- outputRoot: storage.outputRoot,
401
- streamPath: storage.streamPath,
402
- intakePath,
403
- event: normalizedEvent,
404
- };
405
- }
406
-
407
- export async function getErrorDaemonState({
408
- targetPath = ".",
409
- outputDir = "",
410
- env,
411
- homeDir,
412
- } = {}) {
413
- const storage = await resolveErrorDaemonStorage({
414
- targetPath,
415
- outputDir,
416
- env,
417
- homeDir,
418
- });
419
- const state = await loadWorkerStateFile(storage.statePath);
420
- return {
421
- ...storage,
422
- state,
423
- };
424
- }
425
-
426
- export async function runErrorDaemonWorker({
427
- targetPath = ".",
428
- outputDir = "",
429
- maxEvents = DEFAULT_MAX_EVENTS,
430
- env,
431
- homeDir,
432
- nowIso = new Date().toISOString(),
433
- } = {}) {
434
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
435
- const normalizedMaxEvents = normalizePositiveInteger(maxEvents, DEFAULT_MAX_EVENTS);
436
- const storage = await resolveErrorDaemonStorage({
437
- targetPath,
438
- outputDir,
439
- env,
440
- homeDir,
441
- });
442
-
443
- const [lines, queue, state] = await Promise.all([
444
- loadStreamLines(storage.streamPath),
445
- loadQueueFile(storage.queuePath, normalizedNow),
446
- loadWorkerStateFile(storage.statePath, normalizedNow),
447
- ]);
448
-
449
- const startOffset = Math.max(0, Math.min(state.streamOffset, lines.length));
450
- const endOffset = Math.min(lines.length, startOffset + normalizedMaxEvents);
451
- const openItemsByFingerprint = new Map();
452
- for (const item of queue.items) {
453
- const fingerprint = normalizeString(item.fingerprint);
454
- if (!fingerprint || isTerminalStatus(item.status)) {
455
- continue;
456
- }
457
- if (!openItemsByFingerprint.has(fingerprint)) {
458
- openItemsByFingerprint.set(fingerprint, item);
459
- }
460
- }
461
-
462
- let processedCount = 0;
463
- let queuedCount = 0;
464
- let dedupedCount = 0;
465
- let parseErrorCount = 0;
466
- for (let index = startOffset; index < endOffset; index += 1) {
467
- const rawLine = lines[index];
468
- if (!rawLine) {
469
- continue;
470
- }
471
-
472
- let parsed = null;
473
- try {
474
- parsed = JSON.parse(rawLine);
475
- } catch {
476
- parseErrorCount += 1;
477
- continue;
478
- }
479
- const event = normalizeErrorEvent(parsed, normalizedNow);
480
- processedCount += 1;
481
- const existing = openItemsByFingerprint.get(event.fingerprint);
482
- if (existing) {
483
- dedupedCount += 1;
484
- existing.occurrenceCount = Math.max(1, Number(existing.occurrenceCount || 1)) + 1;
485
- existing.lastSeenAt = event.occurredAt;
486
- existing.updatedAt = normalizedNow;
487
- existing.latestEventId = event.eventId;
488
- existing.severity = chooseHigherSeverity(existing.severity, event.severity);
489
- if (event.message) {
490
- existing.message = event.message;
491
- }
492
- existing.metadata = {
493
- ...normalizeMetadata(existing.metadata),
494
- ...normalizeMetadata(event.metadata),
495
- sourceEventId: event.eventId,
496
- };
497
- continue;
498
- }
499
-
500
- const queued = buildWorkItemFromEvent(event, normalizedNow);
501
- queue.items.push(queued);
502
- openItemsByFingerprint.set(queued.fingerprint, queued);
503
- queuedCount += 1;
504
- }
505
-
506
- queue.generatedAt = normalizedNow;
507
- const savedQueue = await writeQueueFile(storage.queuePath, queue, normalizedNow);
508
-
509
- const savedState = await writeWorkerStateFile(
510
- storage.statePath,
511
- {
512
- ...state,
513
- updatedAt: normalizedNow,
514
- lastRunAt: normalizedNow,
515
- streamOffset: endOffset,
516
- runCount: state.runCount + 1,
517
- totalProcessedEvents: state.totalProcessedEvents + processedCount,
518
- totalQueuedItems: savedQueue.items.length,
519
- totalDedupeHits: state.totalDedupeHits + dedupedCount,
520
- },
521
- normalizedNow
522
- );
523
-
524
- await fsp.mkdir(storage.runsDir, { recursive: true });
525
- const runId = `error-daemon-run-${stableTimestampForFile(new Date(normalizedNow))}-${randomUUID().slice(0, 8)}`;
526
- const runPath = path.join(storage.runsDir, `${runId}.json`);
527
- await fsp.writeFile(
528
- runPath,
529
- `${JSON.stringify(
530
- {
531
- schemaVersion: "1.0.0",
532
- generatedAt: normalizedNow,
533
- runId,
534
- streamPath: storage.streamPath,
535
- queuePath: storage.queuePath,
536
- statePath: storage.statePath,
537
- startOffset,
538
- endOffset,
539
- streamLength: lines.length,
540
- maxEvents: normalizedMaxEvents,
541
- processedCount,
542
- queuedCount,
543
- dedupedCount,
544
- parseErrorCount,
545
- queueDepth: savedQueue.items.length,
546
- },
547
- null,
548
- 2
549
- )}\n`,
550
- "utf-8"
551
- );
552
-
553
- return {
554
- ...storage,
555
- runId,
556
- runPath,
557
- maxEvents: normalizedMaxEvents,
558
- startOffset,
559
- endOffset,
560
- streamLength: lines.length,
561
- processedCount,
562
- queuedCount,
563
- dedupedCount,
564
- parseErrorCount,
565
- queueDepth: savedQueue.items.length,
566
- queue: savedQueue,
567
- state: savedState,
568
- };
569
- }
570
-
571
- function parseStatusFilter(statuses = []) {
572
- if (!Array.isArray(statuses)) {
573
- return null;
574
- }
575
- const normalized = statuses
576
- .map((value) => normalizeString(value).toUpperCase())
577
- .filter(Boolean)
578
- .filter((value) => WORK_ITEM_STATUS_SET.has(value));
579
- if (normalized.length === 0) {
580
- return null;
581
- }
582
- return new Set(normalized);
583
- }
584
-
585
- export async function listErrorQueue({
586
- targetPath = ".",
587
- outputDir = "",
588
- statuses = [],
589
- limit = 50,
590
- env,
591
- homeDir,
592
- } = {}) {
593
- const normalizedLimit = normalizePositiveInteger(limit, 50);
594
- const storage = await resolveErrorDaemonStorage({
595
- targetPath,
596
- outputDir,
597
- env,
598
- homeDir,
599
- });
600
- const [queue, state] = await Promise.all([
601
- loadQueueFile(storage.queuePath),
602
- loadWorkerStateFile(storage.statePath),
603
- ]);
604
-
605
- const statusFilter = parseStatusFilter(statuses);
606
- const sorted = [...queue.items].sort((left, right) => {
607
- const severityDelta = toSeverityRank(right.severity) - toSeverityRank(left.severity);
608
- if (severityDelta !== 0) {
609
- return severityDelta;
610
- }
611
- const leftTs = Date.parse(String(left.lastSeenAt || left.firstSeenAt || "")) || 0;
612
- const rightTs = Date.parse(String(right.lastSeenAt || right.firstSeenAt || "")) || 0;
613
- return rightTs - leftTs;
614
- });
615
- const filtered = statusFilter
616
- ? sorted.filter((item) => statusFilter.has(normalizeWorkItemStatus(item.status)))
617
- : sorted;
618
-
619
- return {
620
- ...storage,
621
- state,
622
- totalCount: sorted.length,
623
- filteredCount: filtered.length,
624
- items: filtered.slice(0, normalizedLimit),
625
- };
626
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { resolveOutputRoot } from "../config/service.js";
6
+
7
+ const QUEUE_SCHEMA_VERSION = "1.0.0";
8
+ const STATE_SCHEMA_VERSION = "1.0.0";
9
+ const DEFAULT_MAX_EVENTS = 200;
10
+
11
+ const TERMINAL_WORK_ITEM_STATUSES = new Set(["DONE", "SQUASHED"]);
12
+
13
+ export const WORK_ITEM_STATUSES = Object.freeze([
14
+ "QUEUED",
15
+ "ASSIGNED",
16
+ "IN_PROGRESS",
17
+ "BLOCKED",
18
+ "DONE",
19
+ "SQUASHED",
20
+ ]);
21
+
22
+ const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
23
+
24
+ const SEVERITY_RANK = new Map([
25
+ ["UNKNOWN", 0],
26
+ ["P3", 1],
27
+ ["P2", 2],
28
+ ["P1", 3],
29
+ ["P0", 4],
30
+ ]);
31
+
32
+ function normalizeString(value) {
33
+ return String(value || "").trim();
34
+ }
35
+
36
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
37
+ const normalized = normalizeString(value);
38
+ if (!normalized) {
39
+ return fallbackIso;
40
+ }
41
+ const epoch = Date.parse(normalized);
42
+ if (!Number.isFinite(epoch)) {
43
+ return fallbackIso;
44
+ }
45
+ return new Date(epoch).toISOString();
46
+ }
47
+
48
+ function normalizeNonNegativeInteger(value, fallbackValue = 0) {
49
+ if (value === undefined || value === null || normalizeString(value) === "") {
50
+ return fallbackValue;
51
+ }
52
+ const normalized = Number(value);
53
+ if (!Number.isFinite(normalized) || normalized < 0) {
54
+ throw new Error("Value must be a non-negative integer.");
55
+ }
56
+ return Math.floor(normalized);
57
+ }
58
+
59
+ function normalizePositiveInteger(value, fallbackValue = 1) {
60
+ if (value === undefined || value === null || normalizeString(value) === "") {
61
+ return fallbackValue;
62
+ }
63
+ const normalized = Number(value);
64
+ if (!Number.isFinite(normalized) || normalized <= 0) {
65
+ throw new Error("Value must be a positive integer.");
66
+ }
67
+ return Math.floor(normalized);
68
+ }
69
+
70
+ function stableTimestampForFile(date = new Date()) {
71
+ return date.toISOString().replace(/[:.]/g, "-");
72
+ }
73
+
74
+ function normalizeSeverity(value) {
75
+ const normalized = normalizeString(value).toUpperCase();
76
+ if (normalized === "P0" || normalized === "P1" || normalized === "P2" || normalized === "P3") {
77
+ return normalized;
78
+ }
79
+ return "UNKNOWN";
80
+ }
81
+
82
+ function normalizeMetadata(value) {
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
84
+ return {};
85
+ }
86
+ return { ...value };
87
+ }
88
+
89
+ function normalizeStackTrace(value) {
90
+ return String(value || "").replace(/\r\n/g, "\n").trim();
91
+ }
92
+
93
+ function computeStackFingerprint(stackTrace = "") {
94
+ const normalized = normalizeStackTrace(stackTrace);
95
+ if (!normalized) {
96
+ return "none";
97
+ }
98
+ const reduced = normalized
99
+ .split("\n")
100
+ .map((line) => line.trim())
101
+ .filter(Boolean)
102
+ .slice(0, 6)
103
+ .join("|");
104
+ if (!reduced) {
105
+ return "none";
106
+ }
107
+ return createHash("sha256").update(reduced).digest("hex");
108
+ }
109
+
110
+ function computeFingerprint(event = {}) {
111
+ const materialized = [
112
+ normalizeString(event.service).toLowerCase(),
113
+ normalizeString(event.endpoint).toLowerCase(),
114
+ normalizeString(event.errorCode).toLowerCase(),
115
+ normalizeString(event.stackFingerprint).toLowerCase(),
116
+ normalizeString(event.commitSha).toLowerCase(),
117
+ ].join("|");
118
+ return createHash("sha256").update(materialized).digest("hex");
119
+ }
120
+
121
+ function chooseHigherSeverity(left, right) {
122
+ const leftNormalized = normalizeSeverity(left);
123
+ const rightNormalized = normalizeSeverity(right);
124
+ const leftRank = SEVERITY_RANK.get(leftNormalized) ?? 0;
125
+ const rightRank = SEVERITY_RANK.get(rightNormalized) ?? 0;
126
+ return rightRank > leftRank ? rightNormalized : leftNormalized;
127
+ }
128
+
129
+ function toSeverityRank(value) {
130
+ return SEVERITY_RANK.get(normalizeSeverity(value)) ?? 0;
131
+ }
132
+
133
+ function createWorkItemId(nowIso = new Date().toISOString()) {
134
+ return `err-${stableTimestampForFile(new Date(nowIso))}-${randomUUID().slice(0, 8)}`;
135
+ }
136
+
137
+ function normalizeWorkItemStatus(value) {
138
+ const normalized = normalizeString(value).toUpperCase();
139
+ if (WORK_ITEM_STATUS_SET.has(normalized)) {
140
+ return normalized;
141
+ }
142
+ return "QUEUED";
143
+ }
144
+
145
+ function isTerminalStatus(status = "") {
146
+ return TERMINAL_WORK_ITEM_STATUSES.has(normalizeWorkItemStatus(status));
147
+ }
148
+
149
+ function normalizeQueueItem(item = {}, fallbackNowIso = new Date().toISOString()) {
150
+ const createdAt = normalizeIsoTimestamp(item.createdAt, fallbackNowIso);
151
+ return {
152
+ workItemId: normalizeString(item.workItemId) || createWorkItemId(createdAt),
153
+ fingerprint: normalizeString(item.fingerprint),
154
+ source: normalizeString(item.source) || "admin_error_log",
155
+ service: normalizeString(item.service) || "unknown-service",
156
+ endpoint: normalizeString(item.endpoint) || "unknown-endpoint",
157
+ errorCode: normalizeString(item.errorCode) || "UNKNOWN_ERROR",
158
+ severity: normalizeSeverity(item.severity),
159
+ status: normalizeWorkItemStatus(item.status),
160
+ message: normalizeString(item.message),
161
+ stackFingerprint: normalizeString(item.stackFingerprint) || "none",
162
+ commitSha: normalizeString(item.commitSha) || null,
163
+ firstSeenAt: normalizeIsoTimestamp(item.firstSeenAt, createdAt),
164
+ lastSeenAt: normalizeIsoTimestamp(item.lastSeenAt, createdAt),
165
+ latestEventId: normalizeString(item.latestEventId) || null,
166
+ occurrenceCount: Math.max(1, normalizeNonNegativeInteger(item.occurrenceCount, 1)),
167
+ createdAt,
168
+ updatedAt: normalizeIsoTimestamp(item.updatedAt, createdAt),
169
+ metadata: normalizeMetadata(item.metadata),
170
+ };
171
+ }
172
+
173
+ function getQueueInitialState(nowIso = new Date().toISOString()) {
174
+ return {
175
+ schemaVersion: QUEUE_SCHEMA_VERSION,
176
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
177
+ items: [],
178
+ };
179
+ }
180
+
181
+ function getWorkerStateInitial(nowIso = new Date().toISOString()) {
182
+ return {
183
+ schemaVersion: STATE_SCHEMA_VERSION,
184
+ updatedAt: normalizeIsoTimestamp(nowIso, nowIso),
185
+ lastRunAt: null,
186
+ streamOffset: 0,
187
+ runCount: 0,
188
+ totalProcessedEvents: 0,
189
+ totalQueuedItems: 0,
190
+ totalDedupeHits: 0,
191
+ };
192
+ }
193
+
194
+ async function loadQueueFile(queuePath, nowIso = new Date().toISOString()) {
195
+ try {
196
+ const raw = await fsp.readFile(queuePath, "utf-8");
197
+ const parsed = JSON.parse(raw);
198
+ const items = Array.isArray(parsed.items)
199
+ ? parsed.items
200
+ .map((item) => normalizeQueueItem(item, nowIso))
201
+ .filter((item) => normalizeString(item.fingerprint))
202
+ : [];
203
+ return {
204
+ schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
205
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
206
+ items,
207
+ };
208
+ } catch (error) {
209
+ if (error && typeof error === "object" && error.code === "ENOENT") {
210
+ return getQueueInitialState(nowIso);
211
+ }
212
+ throw error;
213
+ }
214
+ }
215
+
216
+ async function writeQueueFile(queuePath, queue = {}, nowIso = new Date().toISOString()) {
217
+ const normalized = {
218
+ schemaVersion: QUEUE_SCHEMA_VERSION,
219
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
220
+ items: Array.isArray(queue.items)
221
+ ? queue.items
222
+ .map((item) => normalizeQueueItem(item, nowIso))
223
+ .filter((item) => normalizeString(item.fingerprint))
224
+ : [],
225
+ };
226
+ await fsp.mkdir(path.dirname(queuePath), { recursive: true });
227
+ await fsp.writeFile(queuePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf-8");
228
+ return normalized;
229
+ }
230
+
231
+ async function loadWorkerStateFile(statePath, nowIso = new Date().toISOString()) {
232
+ try {
233
+ const raw = await fsp.readFile(statePath, "utf-8");
234
+ const parsed = JSON.parse(raw);
235
+ return {
236
+ schemaVersion: normalizeString(parsed.schemaVersion) || STATE_SCHEMA_VERSION,
237
+ updatedAt: normalizeIsoTimestamp(parsed.updatedAt, nowIso),
238
+ lastRunAt: parsed.lastRunAt ? normalizeIsoTimestamp(parsed.lastRunAt, nowIso) : null,
239
+ streamOffset: normalizeNonNegativeInteger(parsed.streamOffset, 0),
240
+ runCount: normalizeNonNegativeInteger(parsed.runCount, 0),
241
+ totalProcessedEvents: normalizeNonNegativeInteger(parsed.totalProcessedEvents, 0),
242
+ totalQueuedItems: normalizeNonNegativeInteger(parsed.totalQueuedItems, 0),
243
+ totalDedupeHits: normalizeNonNegativeInteger(parsed.totalDedupeHits, 0),
244
+ };
245
+ } catch (error) {
246
+ if (error && typeof error === "object" && error.code === "ENOENT") {
247
+ return getWorkerStateInitial(nowIso);
248
+ }
249
+ throw error;
250
+ }
251
+ }
252
+
253
+ async function writeWorkerStateFile(statePath, state = {}, nowIso = new Date().toISOString()) {
254
+ const normalized = {
255
+ schemaVersion: STATE_SCHEMA_VERSION,
256
+ updatedAt: normalizeIsoTimestamp(nowIso, nowIso),
257
+ lastRunAt: state.lastRunAt ? normalizeIsoTimestamp(state.lastRunAt, nowIso) : null,
258
+ streamOffset: normalizeNonNegativeInteger(state.streamOffset, 0),
259
+ runCount: normalizeNonNegativeInteger(state.runCount, 0),
260
+ totalProcessedEvents: normalizeNonNegativeInteger(state.totalProcessedEvents, 0),
261
+ totalQueuedItems: normalizeNonNegativeInteger(state.totalQueuedItems, 0),
262
+ totalDedupeHits: normalizeNonNegativeInteger(state.totalDedupeHits, 0),
263
+ };
264
+ await fsp.mkdir(path.dirname(statePath), { recursive: true });
265
+ await fsp.writeFile(statePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf-8");
266
+ return normalized;
267
+ }
268
+
269
+ async function loadStreamLines(streamPath) {
270
+ try {
271
+ const raw = await fsp.readFile(streamPath, "utf-8");
272
+ return raw
273
+ .split(/\r?\n/)
274
+ .map((line) => line.trim())
275
+ .filter(Boolean);
276
+ } catch (error) {
277
+ if (error && typeof error === "object" && error.code === "ENOENT") {
278
+ return [];
279
+ }
280
+ throw error;
281
+ }
282
+ }
283
+
284
+ function buildWorkItemFromEvent(event, nowIso) {
285
+ return normalizeQueueItem(
286
+ {
287
+ workItemId: createWorkItemId(nowIso),
288
+ fingerprint: event.fingerprint,
289
+ source: event.source,
290
+ service: event.service,
291
+ endpoint: event.endpoint,
292
+ errorCode: event.errorCode,
293
+ severity: event.severity,
294
+ status: "QUEUED",
295
+ message: event.message,
296
+ stackFingerprint: event.stackFingerprint,
297
+ commitSha: event.commitSha,
298
+ firstSeenAt: event.occurredAt,
299
+ lastSeenAt: event.occurredAt,
300
+ latestEventId: event.eventId,
301
+ occurrenceCount: 1,
302
+ createdAt: nowIso,
303
+ updatedAt: nowIso,
304
+ metadata: {
305
+ ...event.metadata,
306
+ sourceEventId: event.eventId,
307
+ },
308
+ },
309
+ nowIso
310
+ );
311
+ }
312
+
313
+ export function normalizeErrorEvent(event = {}, nowIso = new Date().toISOString()) {
314
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
315
+ const stackTrace = normalizeStackTrace(event.stackTrace || event.stack || "");
316
+ const normalized = {
317
+ eventId: normalizeString(event.eventId) || randomUUID(),
318
+ occurredAt: normalizeIsoTimestamp(event.occurredAt, normalizedNow),
319
+ recordedAt: normalizedNow,
320
+ source: normalizeString(event.source) || "admin_error_log",
321
+ service: normalizeString(event.service) || "unknown-service",
322
+ endpoint: normalizeString(event.endpoint) || "unknown-endpoint",
323
+ errorCode: normalizeString(event.errorCode) || "UNKNOWN_ERROR",
324
+ severity: normalizeSeverity(event.severity),
325
+ message: normalizeString(event.message) || "Unhandled runtime error",
326
+ stackTrace,
327
+ stackFingerprint: computeStackFingerprint(stackTrace),
328
+ commitSha: normalizeString(event.commitSha) || null,
329
+ metadata: normalizeMetadata(event.metadata),
330
+ };
331
+ return {
332
+ ...normalized,
333
+ fingerprint: computeFingerprint(normalized),
334
+ };
335
+ }
336
+
337
+ export async function resolveErrorDaemonStorage({
338
+ targetPath = ".",
339
+ outputDir = "",
340
+ env,
341
+ homeDir,
342
+ } = {}) {
343
+ const outputRoot = await resolveOutputRoot({
344
+ cwd: path.resolve(String(targetPath || ".")),
345
+ outputDirOverride: outputDir,
346
+ env,
347
+ homeDir,
348
+ });
349
+ const baseDir = path.join(outputRoot, "observability", "error-daemon");
350
+ return {
351
+ outputRoot,
352
+ baseDir,
353
+ streamPath: path.join(baseDir, "admin-error-stream.ndjson"),
354
+ queuePath: path.join(baseDir, "queue.json"),
355
+ statePath: path.join(baseDir, "worker-state.json"),
356
+ intakeDir: path.join(baseDir, "intake"),
357
+ runsDir: path.join(baseDir, "runs"),
358
+ };
359
+ }
360
+
361
+ export async function appendAdminErrorEvent({
362
+ targetPath = ".",
363
+ outputDir = "",
364
+ event = {},
365
+ env,
366
+ homeDir,
367
+ } = {}) {
368
+ const nowIso = new Date().toISOString();
369
+ const normalizedEvent = normalizeErrorEvent(event, nowIso);
370
+ const storage = await resolveErrorDaemonStorage({
371
+ targetPath,
372
+ outputDir,
373
+ env,
374
+ homeDir,
375
+ });
376
+
377
+ await fsp.mkdir(storage.baseDir, { recursive: true });
378
+ await fsp.appendFile(storage.streamPath, `${JSON.stringify(normalizedEvent)}\n`, "utf-8");
379
+
380
+ await fsp.mkdir(storage.intakeDir, { recursive: true });
381
+ const intakePath = path.join(
382
+ storage.intakeDir,
383
+ `intake-${stableTimestampForFile(new Date(normalizedEvent.recordedAt))}-${normalizedEvent.eventId.slice(0, 8)}.json`
384
+ );
385
+ await fsp.writeFile(
386
+ intakePath,
387
+ `${JSON.stringify(
388
+ {
389
+ schemaVersion: "1.0.0",
390
+ generatedAt: nowIso,
391
+ event: normalizedEvent,
392
+ },
393
+ null,
394
+ 2
395
+ )}\n`,
396
+ "utf-8"
397
+ );
398
+
399
+ return {
400
+ outputRoot: storage.outputRoot,
401
+ streamPath: storage.streamPath,
402
+ intakePath,
403
+ event: normalizedEvent,
404
+ };
405
+ }
406
+
407
+ export async function getErrorDaemonState({
408
+ targetPath = ".",
409
+ outputDir = "",
410
+ env,
411
+ homeDir,
412
+ } = {}) {
413
+ const storage = await resolveErrorDaemonStorage({
414
+ targetPath,
415
+ outputDir,
416
+ env,
417
+ homeDir,
418
+ });
419
+ const state = await loadWorkerStateFile(storage.statePath);
420
+ return {
421
+ ...storage,
422
+ state,
423
+ };
424
+ }
425
+
426
+ export async function runErrorDaemonWorker({
427
+ targetPath = ".",
428
+ outputDir = "",
429
+ maxEvents = DEFAULT_MAX_EVENTS,
430
+ env,
431
+ homeDir,
432
+ nowIso = new Date().toISOString(),
433
+ } = {}) {
434
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
435
+ const normalizedMaxEvents = normalizePositiveInteger(maxEvents, DEFAULT_MAX_EVENTS);
436
+ const storage = await resolveErrorDaemonStorage({
437
+ targetPath,
438
+ outputDir,
439
+ env,
440
+ homeDir,
441
+ });
442
+
443
+ const [lines, queue, state] = await Promise.all([
444
+ loadStreamLines(storage.streamPath),
445
+ loadQueueFile(storage.queuePath, normalizedNow),
446
+ loadWorkerStateFile(storage.statePath, normalizedNow),
447
+ ]);
448
+
449
+ const startOffset = Math.max(0, Math.min(state.streamOffset, lines.length));
450
+ const endOffset = Math.min(lines.length, startOffset + normalizedMaxEvents);
451
+ const openItemsByFingerprint = new Map();
452
+ for (const item of queue.items) {
453
+ const fingerprint = normalizeString(item.fingerprint);
454
+ if (!fingerprint || isTerminalStatus(item.status)) {
455
+ continue;
456
+ }
457
+ if (!openItemsByFingerprint.has(fingerprint)) {
458
+ openItemsByFingerprint.set(fingerprint, item);
459
+ }
460
+ }
461
+
462
+ let processedCount = 0;
463
+ let queuedCount = 0;
464
+ let dedupedCount = 0;
465
+ let parseErrorCount = 0;
466
+ for (let index = startOffset; index < endOffset; index += 1) {
467
+ const rawLine = lines[index];
468
+ if (!rawLine) {
469
+ continue;
470
+ }
471
+
472
+ let parsed = null;
473
+ try {
474
+ parsed = JSON.parse(rawLine);
475
+ } catch {
476
+ parseErrorCount += 1;
477
+ continue;
478
+ }
479
+ const event = normalizeErrorEvent(parsed, normalizedNow);
480
+ processedCount += 1;
481
+ const existing = openItemsByFingerprint.get(event.fingerprint);
482
+ if (existing) {
483
+ dedupedCount += 1;
484
+ existing.occurrenceCount = Math.max(1, Number(existing.occurrenceCount || 1)) + 1;
485
+ existing.lastSeenAt = event.occurredAt;
486
+ existing.updatedAt = normalizedNow;
487
+ existing.latestEventId = event.eventId;
488
+ existing.severity = chooseHigherSeverity(existing.severity, event.severity);
489
+ if (event.message) {
490
+ existing.message = event.message;
491
+ }
492
+ existing.metadata = {
493
+ ...normalizeMetadata(existing.metadata),
494
+ ...normalizeMetadata(event.metadata),
495
+ sourceEventId: event.eventId,
496
+ };
497
+ continue;
498
+ }
499
+
500
+ const queued = buildWorkItemFromEvent(event, normalizedNow);
501
+ queue.items.push(queued);
502
+ openItemsByFingerprint.set(queued.fingerprint, queued);
503
+ queuedCount += 1;
504
+ }
505
+
506
+ queue.generatedAt = normalizedNow;
507
+ const savedQueue = await writeQueueFile(storage.queuePath, queue, normalizedNow);
508
+
509
+ const savedState = await writeWorkerStateFile(
510
+ storage.statePath,
511
+ {
512
+ ...state,
513
+ updatedAt: normalizedNow,
514
+ lastRunAt: normalizedNow,
515
+ streamOffset: endOffset,
516
+ runCount: state.runCount + 1,
517
+ totalProcessedEvents: state.totalProcessedEvents + processedCount,
518
+ totalQueuedItems: savedQueue.items.length,
519
+ totalDedupeHits: state.totalDedupeHits + dedupedCount,
520
+ },
521
+ normalizedNow
522
+ );
523
+
524
+ await fsp.mkdir(storage.runsDir, { recursive: true });
525
+ const runId = `error-daemon-run-${stableTimestampForFile(new Date(normalizedNow))}-${randomUUID().slice(0, 8)}`;
526
+ const runPath = path.join(storage.runsDir, `${runId}.json`);
527
+ await fsp.writeFile(
528
+ runPath,
529
+ `${JSON.stringify(
530
+ {
531
+ schemaVersion: "1.0.0",
532
+ generatedAt: normalizedNow,
533
+ runId,
534
+ streamPath: storage.streamPath,
535
+ queuePath: storage.queuePath,
536
+ statePath: storage.statePath,
537
+ startOffset,
538
+ endOffset,
539
+ streamLength: lines.length,
540
+ maxEvents: normalizedMaxEvents,
541
+ processedCount,
542
+ queuedCount,
543
+ dedupedCount,
544
+ parseErrorCount,
545
+ queueDepth: savedQueue.items.length,
546
+ },
547
+ null,
548
+ 2
549
+ )}\n`,
550
+ "utf-8"
551
+ );
552
+
553
+ return {
554
+ ...storage,
555
+ runId,
556
+ runPath,
557
+ maxEvents: normalizedMaxEvents,
558
+ startOffset,
559
+ endOffset,
560
+ streamLength: lines.length,
561
+ processedCount,
562
+ queuedCount,
563
+ dedupedCount,
564
+ parseErrorCount,
565
+ queueDepth: savedQueue.items.length,
566
+ queue: savedQueue,
567
+ state: savedState,
568
+ };
569
+ }
570
+
571
+ function parseStatusFilter(statuses = []) {
572
+ if (!Array.isArray(statuses)) {
573
+ return null;
574
+ }
575
+ const normalized = statuses
576
+ .map((value) => normalizeString(value).toUpperCase())
577
+ .filter(Boolean)
578
+ .filter((value) => WORK_ITEM_STATUS_SET.has(value));
579
+ if (normalized.length === 0) {
580
+ return null;
581
+ }
582
+ return new Set(normalized);
583
+ }
584
+
585
+ export async function listErrorQueue({
586
+ targetPath = ".",
587
+ outputDir = "",
588
+ statuses = [],
589
+ limit = 50,
590
+ env,
591
+ homeDir,
592
+ } = {}) {
593
+ const normalizedLimit = normalizePositiveInteger(limit, 50);
594
+ const storage = await resolveErrorDaemonStorage({
595
+ targetPath,
596
+ outputDir,
597
+ env,
598
+ homeDir,
599
+ });
600
+ const [queue, state] = await Promise.all([
601
+ loadQueueFile(storage.queuePath),
602
+ loadWorkerStateFile(storage.statePath),
603
+ ]);
604
+
605
+ const statusFilter = parseStatusFilter(statuses);
606
+ const sorted = [...queue.items].sort((left, right) => {
607
+ const severityDelta = toSeverityRank(right.severity) - toSeverityRank(left.severity);
608
+ if (severityDelta !== 0) {
609
+ return severityDelta;
610
+ }
611
+ const leftTs = Date.parse(String(left.lastSeenAt || left.firstSeenAt || "")) || 0;
612
+ const rightTs = Date.parse(String(right.lastSeenAt || right.firstSeenAt || "")) || 0;
613
+ return rightTs - leftTs;
614
+ });
615
+ const filtered = statusFilter
616
+ ? sorted.filter((item) => statusFilter.has(normalizeWorkItemStatus(item.status)))
617
+ : sorted;
618
+
619
+ return {
620
+ ...storage,
621
+ state,
622
+ totalCount: sorted.length,
623
+ filteredCount: filtered.length,
624
+ items: filtered.slice(0, normalizedLimit),
625
+ };
626
+ }