sentinelayer-cli 0.1.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 (124) hide show
  1. package/README.md +996 -0
  2. package/bin/create-sentinelayer.js +5 -0
  3. package/bin/sentinelayer-cli.js +5 -0
  4. package/bin/sl.js +5 -0
  5. package/package.json +54 -0
  6. package/src/agents/jules/config/definition.js +209 -0
  7. package/src/agents/jules/config/system-prompt.js +175 -0
  8. package/src/agents/jules/error-intake.js +51 -0
  9. package/src/agents/jules/fix-cycle.js +377 -0
  10. package/src/agents/jules/loop.js +367 -0
  11. package/src/agents/jules/pulse.js +319 -0
  12. package/src/agents/jules/stream.js +186 -0
  13. package/src/agents/jules/swarm/file-scanner.js +74 -0
  14. package/src/agents/jules/swarm/index.js +11 -0
  15. package/src/agents/jules/swarm/orchestrator.js +362 -0
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -0
  17. package/src/agents/jules/swarm/sub-agent.js +308 -0
  18. package/src/agents/jules/tools/auth-audit.js +222 -0
  19. package/src/agents/jules/tools/dispatch.js +327 -0
  20. package/src/agents/jules/tools/file-edit.js +180 -0
  21. package/src/agents/jules/tools/file-read.js +100 -0
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -0
  23. package/src/agents/jules/tools/glob.js +168 -0
  24. package/src/agents/jules/tools/grep.js +228 -0
  25. package/src/agents/jules/tools/index.js +29 -0
  26. package/src/agents/jules/tools/path-guards.js +161 -0
  27. package/src/agents/jules/tools/runtime-audit.js +409 -0
  28. package/src/agents/jules/tools/shell.js +383 -0
  29. package/src/ai/aidenid.js +945 -0
  30. package/src/ai/client.js +508 -0
  31. package/src/ai/domain-target-store.js +268 -0
  32. package/src/ai/identity-store.js +270 -0
  33. package/src/ai/site-store.js +145 -0
  34. package/src/audit/agents/architecture.js +180 -0
  35. package/src/audit/agents/compliance.js +179 -0
  36. package/src/audit/agents/documentation.js +165 -0
  37. package/src/audit/agents/performance.js +145 -0
  38. package/src/audit/agents/security.js +215 -0
  39. package/src/audit/agents/testing.js +172 -0
  40. package/src/audit/orchestrator.js +557 -0
  41. package/src/audit/package.js +204 -0
  42. package/src/audit/registry.js +284 -0
  43. package/src/audit/replay.js +103 -0
  44. package/src/auth/http.js +113 -0
  45. package/src/auth/service.js +848 -0
  46. package/src/auth/session-store.js +345 -0
  47. package/src/cli.js +244 -0
  48. package/src/commands/ai/identity-lifecycle.js +1337 -0
  49. package/src/commands/ai/provision-governance.js +1246 -0
  50. package/src/commands/ai/shared.js +147 -0
  51. package/src/commands/ai.js +11 -0
  52. package/src/commands/apply.js +19 -0
  53. package/src/commands/audit.js +1147 -0
  54. package/src/commands/auth.js +366 -0
  55. package/src/commands/chat.js +191 -0
  56. package/src/commands/config.js +184 -0
  57. package/src/commands/cost.js +311 -0
  58. package/src/commands/daemon/core.js +850 -0
  59. package/src/commands/daemon/extended.js +1048 -0
  60. package/src/commands/daemon/shared.js +213 -0
  61. package/src/commands/daemon.js +11 -0
  62. package/src/commands/guide.js +174 -0
  63. package/src/commands/ingest.js +58 -0
  64. package/src/commands/init.js +55 -0
  65. package/src/commands/legacy-args.js +30 -0
  66. package/src/commands/mcp.js +404 -0
  67. package/src/commands/omargate.js +21 -0
  68. package/src/commands/persona.js +27 -0
  69. package/src/commands/plugin.js +260 -0
  70. package/src/commands/policy.js +132 -0
  71. package/src/commands/prompt.js +238 -0
  72. package/src/commands/review.js +704 -0
  73. package/src/commands/scan.js +788 -0
  74. package/src/commands/spec.js +716 -0
  75. package/src/commands/swarm.js +651 -0
  76. package/src/commands/telemetry.js +202 -0
  77. package/src/commands/watch.js +510 -0
  78. package/src/config/agent-dictionary.js +182 -0
  79. package/src/config/io.js +56 -0
  80. package/src/config/paths.js +18 -0
  81. package/src/config/schema.js +55 -0
  82. package/src/config/service.js +184 -0
  83. package/src/cost/budget.js +235 -0
  84. package/src/cost/history.js +188 -0
  85. package/src/cost/tracker.js +171 -0
  86. package/src/daemon/artifact-lineage.js +534 -0
  87. package/src/daemon/assignment-ledger.js +770 -0
  88. package/src/daemon/ast-parser-layer.js +258 -0
  89. package/src/daemon/budget-governor.js +633 -0
  90. package/src/daemon/callgraph-overlay.js +646 -0
  91. package/src/daemon/error-worker.js +626 -0
  92. package/src/daemon/hybrid-mapper.js +929 -0
  93. package/src/daemon/jira-lifecycle.js +632 -0
  94. package/src/daemon/operator-control.js +657 -0
  95. package/src/daemon/reliability-lane.js +471 -0
  96. package/src/daemon/watchdog.js +971 -0
  97. package/src/guide/generator.js +316 -0
  98. package/src/ingest/engine.js +918 -0
  99. package/src/legacy-cli.js +2435 -0
  100. package/src/mcp/registry.js +695 -0
  101. package/src/memory/blackboard.js +301 -0
  102. package/src/memory/retrieval.js +581 -0
  103. package/src/plugin/manifest.js +553 -0
  104. package/src/policy/packs.js +144 -0
  105. package/src/prompt/generator.js +106 -0
  106. package/src/review/ai-review.js +669 -0
  107. package/src/review/local-review.js +1284 -0
  108. package/src/review/replay.js +235 -0
  109. package/src/review/report.js +664 -0
  110. package/src/review/spec-binding.js +487 -0
  111. package/src/scan/generator.js +351 -0
  112. package/src/spec/generator.js +519 -0
  113. package/src/spec/regenerate.js +237 -0
  114. package/src/spec/templates.js +91 -0
  115. package/src/swarm/dashboard.js +247 -0
  116. package/src/swarm/factory.js +363 -0
  117. package/src/swarm/pentest.js +934 -0
  118. package/src/swarm/registry.js +419 -0
  119. package/src/swarm/report.js +158 -0
  120. package/src/swarm/runtime.js +576 -0
  121. package/src/swarm/scenario-dsl.js +272 -0
  122. package/src/telemetry/ledger.js +302 -0
  123. package/src/ui/markdown.js +220 -0
  124. package/src/ui/progress.js +100 -0
@@ -0,0 +1,367 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createMultiProviderApiClient } from "../../ai/client.js";
3
+ import { evaluateBudget } from "../../cost/budget.js";
4
+ import { dispatchTool, createAgentContext, BudgetExhaustedError } from "./tools/dispatch.js";
5
+ import { JULES_DEFINITION } from "./config/definition.js";
6
+ import { shouldSpawnSubAgents, runJulesSwarm } from "./swarm/orchestrator.js";
7
+ import { frontendAnalyze } from "./tools/frontend-analyze.js";
8
+
9
+ /**
10
+ * Jules Tanaka — Agentic Loop
11
+ *
12
+ * Core state machine: LLM → tool_use → execute → result → LLM → repeat
13
+ * With sub-agent swarm integration for large codebases.
14
+ *
15
+ * This loop is self-contained: it uses the existing ai/client.js for LLM calls,
16
+ * the existing cost/budget.js for budget enforcement, and the Jules tool
17
+ * dispatch for tool execution. No dependency on Batches O-Q.
18
+ */
19
+
20
+ const DEFAULT_MAX_TURNS = 25;
21
+ const HEARTBEAT_INTERVAL_TURNS = 5;
22
+
23
+ /**
24
+ * Run Jules' agentic audit loop.
25
+ *
26
+ * @param {object} config
27
+ * @param {string} config.systemPrompt - Jules' full system prompt
28
+ * @param {object} config.scopeMap - { primary, secondary, tertiary } file lists
29
+ * @param {string} config.rootPath - Codebase root
30
+ * @param {object} [config.omarBaseline] - Deterministic baseline findings (if available)
31
+ * @param {object} [config.blackboard] - Shared blackboard for cross-agent findings
32
+ * @param {object} [config.memory] - Memory index for cross-run recall
33
+ * @param {object} [config.budget] - Budget overrides
34
+ * @param {object} [config.provider] - LLM provider overrides
35
+ * @param {string} [config.mode] - "primary" | "secondary" | "tertiary"
36
+ * @param {number} [config.maxTurns] - Max loop iterations
37
+ * @param {AbortController} [config.abortController]
38
+ * @param {function} [config.onEvent] - Streaming event callback
39
+ * @returns {AsyncGenerator<JulesEvent>} Yields events as they occur
40
+ */
41
+ export async function* julesAuditLoop(config) {
42
+ const {
43
+ systemPrompt,
44
+ scopeMap,
45
+ rootPath,
46
+ omarBaseline,
47
+ blackboard,
48
+ memory,
49
+ provider,
50
+ mode = "primary",
51
+ maxTurns = DEFAULT_MAX_TURNS,
52
+ abortController,
53
+ onEvent,
54
+ } = config;
55
+
56
+ const budget = { ...JULES_DEFINITION.budget, ...config.budget };
57
+ const runId = `jules-${Date.now()}-${randomUUID().slice(0, 8)}`;
58
+ const startedAt = Date.now();
59
+ const client = createMultiProviderApiClient(provider || {});
60
+
61
+ const ctx = createAgentContext({
62
+ agentIdentity: { id: JULES_DEFINITION.id, persona: JULES_DEFINITION.persona },
63
+ budget,
64
+ runId,
65
+ onEvent,
66
+ });
67
+
68
+ const emit = (event, payload) => {
69
+ const evt = {
70
+ stream: "sl_event",
71
+ event,
72
+ agent: { id: JULES_DEFINITION.id, persona: JULES_DEFINITION.persona, color: JULES_DEFINITION.color, avatar: JULES_DEFINITION.avatar },
73
+ payload,
74
+ usage: {
75
+ costUsd: ctx.usage.costUsd,
76
+ outputTokens: ctx.usage.outputTokens,
77
+ toolCalls: ctx.usage.toolCalls,
78
+ durationMs: Date.now() - startedAt,
79
+ },
80
+ };
81
+ if (onEvent) onEvent(evt);
82
+ return evt;
83
+ };
84
+
85
+ yield emit("agent_start", { mode, runId, maxTurns, budget });
86
+
87
+ // ── Phase 0: Prerequisites ────────────────────────────────────────
88
+
89
+ yield emit("progress", { phase: "prerequisites", message: "Detecting framework..." });
90
+
91
+ let framework = {};
92
+ try {
93
+ framework = frontendAnalyze({ operation: "detect_framework", path: rootPath });
94
+ ctx.usage.toolCalls++;
95
+ yield emit("tool_result", { tool: "FrontendAnalyze", operation: "detect_framework", result: { framework: framework.framework, componentCount: framework.componentCount } });
96
+ } catch { /* proceed without */ }
97
+
98
+ // ── Phase 1: Swarm or direct? ─────────────────────────────────────
99
+
100
+ const spawnDecision = shouldSpawnSubAgents(scopeMap);
101
+ let swarmFindings = [];
102
+
103
+ if (spawnDecision.spawn && blackboard) {
104
+ yield emit("progress", { phase: "swarm", message: `Large frontend (${spawnDecision.reason}). Spawning sub-agents...` });
105
+
106
+ const swarmResult = await runJulesSwarm({
107
+ scopeMap,
108
+ rootPath,
109
+ blackboard,
110
+ budget: { ...budget, maxCostUsd: budget.maxCostUsd * 0.6 }, // 60% for swarm
111
+ provider,
112
+ parentAbort: abortController,
113
+ onEvent,
114
+ });
115
+
116
+ swarmFindings = swarmResult.agentResults.flatMap(r => r.findings);
117
+ ctx.usage.costUsd += swarmResult.usage.totalCostUsd;
118
+ ctx.usage.toolCalls += swarmResult.usage.totalToolCalls;
119
+
120
+ yield emit("swarm_complete", {
121
+ totalFindings: swarmFindings.length,
122
+ totalAgents: swarmResult.usage.totalAgents,
123
+ totalCostUsd: swarmResult.usage.totalCostUsd,
124
+ });
125
+ }
126
+
127
+ // ── Phase 2: Jules primary deep analysis (agentic LLM loop) ──────
128
+
129
+ yield emit("progress", { phase: "deep_analysis", message: "Starting deep analysis..." });
130
+
131
+ // Build context for LLM
132
+ const contextParts = [];
133
+ contextParts.push(`Framework: ${framework.framework || "unknown"}`);
134
+ contextParts.push(`Mode: ${mode}`);
135
+ contextParts.push(`Components: ${framework.componentCount || "unknown"}`);
136
+ contextParts.push(`Scope: ${(scopeMap.primary || []).length} primary files`);
137
+
138
+ if (swarmFindings.length > 0) {
139
+ contextParts.push(`\nSub-agent findings (${swarmFindings.length} total):`);
140
+ for (const f of swarmFindings.slice(0, 30)) {
141
+ contextParts.push(`- [${f.severity || "P3"}] ${f.file || ""}:${f.line || ""} ${f.title || f.type || ""}`);
142
+ }
143
+ }
144
+
145
+ if (omarBaseline) {
146
+ const baselineFindings = omarBaseline.findings || omarBaseline.summary || [];
147
+ if (Array.isArray(baselineFindings) && baselineFindings.length > 0) {
148
+ contextParts.push(`\nOmar baseline findings (${baselineFindings.length}):`);
149
+ for (const f of baselineFindings.slice(0, 20)) {
150
+ contextParts.push(`- [${f.severity || ""}] ${f.file || ""}:${f.line || ""} ${f.message || f.title || ""}`);
151
+ }
152
+ }
153
+ }
154
+
155
+ if (memory) {
156
+ try {
157
+ const recalled = memory.query ? memory.query({
158
+ files: (scopeMap.primary || []).map(f => f.path || f),
159
+ limit: 10,
160
+ }) : [];
161
+ if (recalled.length > 0) {
162
+ contextParts.push(`\nPrevious findings recalled from memory (${recalled.length}):`);
163
+ for (const r of recalled) {
164
+ contextParts.push(`- ${r.content || r.text || JSON.stringify(r).slice(0, 100)}`);
165
+ }
166
+ }
167
+ } catch { /* memory recall failure is non-blocking */ }
168
+ }
169
+
170
+ const messages = [
171
+ { role: "user", content: contextParts.join("\n") +
172
+ "\n\nPerform your deep analysis now. Use FileRead, Grep, Glob, and FrontendAnalyze tools as needed. " +
173
+ "Return your findings in a ```json code block as an array of { severity, file, line, title, evidence, rootCause, recommendedFix, trafficLight }." },
174
+ ];
175
+
176
+ const allFindings = [...swarmFindings];
177
+ let turnCount = 0;
178
+
179
+ while (turnCount < maxTurns) {
180
+ if (abortController?.signal.aborted) {
181
+ yield emit("agent_abort", { reason: "user_cancelled" });
182
+ break;
183
+ }
184
+
185
+ // Budget check before LLM call
186
+ const preCheck = evaluateBudget({
187
+ sessionSummary: {
188
+ costUsd: ctx.usage.costUsd,
189
+ outputTokens: ctx.usage.outputTokens,
190
+ durationMs: Date.now() - startedAt,
191
+ toolCalls: ctx.usage.toolCalls,
192
+ },
193
+ ...budget,
194
+ });
195
+
196
+ if (preCheck.blocking) {
197
+ yield emit("budget_stop", { reasons: preCheck.reasons });
198
+ break;
199
+ }
200
+
201
+ if (preCheck.warnings.length > 0) {
202
+ yield emit("budget_warning", { warnings: preCheck.warnings });
203
+ }
204
+
205
+ turnCount++;
206
+
207
+ // Heartbeat
208
+ if (turnCount % HEARTBEAT_INTERVAL_TURNS === 0) {
209
+ yield emit("heartbeat", {
210
+ turnsCompleted: turnCount,
211
+ turnsMax: maxTurns,
212
+ findingsSoFar: allFindings.length,
213
+ budgetRemaining: {
214
+ costUsd: Math.max(0, budget.maxCostUsd - ctx.usage.costUsd),
215
+ pct: Math.max(0, 100 - (ctx.usage.costUsd / budget.maxCostUsd * 100)),
216
+ },
217
+ });
218
+ }
219
+
220
+ // Call LLM
221
+ let response;
222
+ try {
223
+ response = await client.invoke({
224
+ systemPrompt,
225
+ messages,
226
+ });
227
+ } catch (err) {
228
+ yield emit("llm_error", { error: err.message, turn: turnCount });
229
+ break;
230
+ }
231
+
232
+ const responseText = response.text || "";
233
+ ctx.usage.outputTokens += Math.ceil(responseText.length / 4);
234
+ ctx.usage.costUsd += (Math.ceil(responseText.length / 4) / 1_000_000) * 15;
235
+
236
+ yield emit("reasoning", {
237
+ phase: "deep_analysis",
238
+ turn: turnCount,
239
+ summary: responseText.slice(0, 200),
240
+ });
241
+
242
+ // Parse tool_use blocks
243
+ const toolCalls = parseToolUseBlocks(responseText);
244
+
245
+ if (toolCalls.length === 0) {
246
+ // No tools — extract findings from response
247
+ const parsed = extractJsonFindings(responseText);
248
+ for (const finding of parsed) {
249
+ allFindings.push(finding);
250
+ yield emit("finding", { ...finding });
251
+ if (blackboard) {
252
+ try {
253
+ await blackboard.appendEntry({
254
+ agentId: JULES_DEFINITION.id,
255
+ source: "jules-primary",
256
+ ...finding,
257
+ });
258
+ } catch { /* blackboard write failure non-blocking */ }
259
+ }
260
+ }
261
+ messages.push({ role: "assistant", content: responseText });
262
+ break; // LLM is done
263
+ }
264
+
265
+ // Execute tool calls
266
+ const results = [];
267
+ for (const call of toolCalls) {
268
+ try {
269
+ const result = await dispatchTool(call.tool, call.input, ctx);
270
+ results.push({ tool: call.tool, result });
271
+ yield emit("tool_call", { tool: call.tool, input: sanitizeForEvent(call.input) });
272
+ } catch (err) {
273
+ if (err instanceof BudgetExhaustedError) {
274
+ yield emit("budget_stop", { reason: err.message });
275
+ break;
276
+ }
277
+ results.push({ tool: call.tool, error: err.message });
278
+ }
279
+ }
280
+
281
+ // Feed results back
282
+ messages.push({ role: "assistant", content: responseText });
283
+ messages.push({
284
+ role: "user",
285
+ content: results.map(r =>
286
+ r.error
287
+ ? `Tool ${r.tool} failed: ${r.error}`
288
+ : `Tool ${r.tool} result:\n${JSON.stringify(r.result).slice(0, 3000)}`,
289
+ ).join("\n\n") + "\n\nContinue your analysis. If done, return findings in a ```json code block.",
290
+ });
291
+ }
292
+
293
+ // ── Phase 3: Build final report ───────────────────────────────────
294
+
295
+ const durationMs = Date.now() - startedAt;
296
+ const severityCounts = { P0: 0, P1: 0, P2: 0, P3: 0 };
297
+ for (const f of allFindings) {
298
+ const sev = (f.severity || "P3").toUpperCase();
299
+ if (severityCounts[sev] !== undefined) severityCounts[sev]++;
300
+ else severityCounts.P3++;
301
+ }
302
+
303
+ const report = {
304
+ runId,
305
+ persona: JULES_DEFINITION.persona,
306
+ mode,
307
+ framework: framework.framework || "unknown",
308
+ status: "completed",
309
+ findings: allFindings,
310
+ summary: {
311
+ total: allFindings.length,
312
+ ...severityCounts,
313
+ blocking: severityCounts.P0 > 0 || severityCounts.P1 > 0,
314
+ },
315
+ usage: {
316
+ turns: turnCount,
317
+ costUsd: ctx.usage.costUsd,
318
+ outputTokens: ctx.usage.outputTokens,
319
+ toolCalls: ctx.usage.toolCalls,
320
+ durationMs,
321
+ },
322
+ signature: JULES_DEFINITION.signature,
323
+ };
324
+
325
+ yield emit("agent_complete", {
326
+ ...report.summary,
327
+ costUsd: ctx.usage.costUsd,
328
+ durationMs,
329
+ turns: turnCount,
330
+ });
331
+
332
+ return report;
333
+ }
334
+
335
+ // ── Helpers ──────────────────────────────────────────────────────────
336
+
337
+ function parseToolUseBlocks(text) {
338
+ const calls = [];
339
+ const regex = /```tool_use\s*\n([\s\S]*?)```/g;
340
+ let match;
341
+ while ((match = regex.exec(text)) !== null) {
342
+ try {
343
+ const parsed = JSON.parse(match[1].trim());
344
+ if (parsed.tool && parsed.input) calls.push(parsed);
345
+ } catch { /* skip malformed */ }
346
+ }
347
+ return calls;
348
+ }
349
+
350
+ function extractJsonFindings(text) {
351
+ const jsonMatch = text.match(/```json\s*\n([\s\S]*?)```/);
352
+ if (!jsonMatch) return [];
353
+ try {
354
+ const parsed = JSON.parse(jsonMatch[1].trim());
355
+ if (Array.isArray(parsed)) return parsed;
356
+ if (parsed.findings && Array.isArray(parsed.findings)) return parsed.findings;
357
+ } catch { /* skip malformed */ }
358
+ return [];
359
+ }
360
+
361
+ function sanitizeForEvent(input) {
362
+ const sanitized = { ...input };
363
+ if (typeof sanitized.content === "string" && sanitized.content.length > 200) {
364
+ sanitized.content = `[${sanitized.content.length} chars]`;
365
+ }
366
+ return sanitized;
367
+ }
@@ -0,0 +1,319 @@
1
+ import { PERSONA_VISUALS } from "./config/definition.js";
2
+
3
+ /**
4
+ * Pulse — SentinelLayer Internal Daemon Monitor
5
+ *
6
+ * Monitors running agent health, routes errors to the right persona,
7
+ * detects stuck/idle agents, and sends alerts on state changes.
8
+ * NOT called Kairos — Pulse monitors the heartbeat of all agents.
9
+ */
10
+
11
+ // ── Stuck Detection ──────────────────────────────────────────────────
12
+
13
+ const STUCK_THRESHOLDS = Object.freeze({
14
+ noToolCallSeconds: 90,
15
+ noProgressTurns: 5,
16
+ sameFileReadCount: 3,
17
+ budgetConsumedNoOutput: 0.5,
18
+ maxIdleBeforeEscalate: 300,
19
+ maxIdleBeforeKill: 600,
20
+ });
21
+
22
+ /**
23
+ * Detect if an agent is stuck based on its current state.
24
+ *
25
+ * @param {object} agentState
26
+ * @param {number} agentState.lastToolCallAt - Epoch ms
27
+ * @param {number} agentState.lastTurnProgressAt - Epoch ms
28
+ * @param {number} agentState.sameFileReadCount - Consecutive reads of same file
29
+ * @param {string} [agentState.lastFileRead] - Path of last file read
30
+ * @param {number} agentState.budgetConsumedPct - 0-100
31
+ * @param {number} agentState.findingCount
32
+ * @param {number} [agentState.turnsSinceLastProgress]
33
+ * @returns {{ stuck: boolean, reason?: string, idleSeconds?: number, file?: string, budgetPct?: number }}
34
+ */
35
+ export function detectStuckState(agentState) {
36
+ const now = Date.now();
37
+
38
+ // No tool calls for threshold period
39
+ if (agentState.lastToolCallAt) {
40
+ const idleMs = now - agentState.lastToolCallAt;
41
+ if (idleMs > STUCK_THRESHOLDS.noToolCallSeconds * 1000) {
42
+ return { stuck: true, reason: "no_tool_calls", idleSeconds: Math.floor(idleMs / 1000) };
43
+ }
44
+ }
45
+
46
+ // Same file read repeatedly (loop detection)
47
+ if (agentState.sameFileReadCount >= STUCK_THRESHOLDS.sameFileReadCount) {
48
+ return { stuck: true, reason: "loop_detected", file: agentState.lastFileRead };
49
+ }
50
+
51
+ // High budget consumption with no findings
52
+ if (
53
+ agentState.budgetConsumedPct > STUCK_THRESHOLDS.budgetConsumedNoOutput * 100 &&
54
+ agentState.findingCount === 0
55
+ ) {
56
+ return { stuck: true, reason: "inefficient", budgetPct: agentState.budgetConsumedPct };
57
+ }
58
+
59
+ // No turn progress
60
+ if (agentState.turnsSinceLastProgress >= STUCK_THRESHOLDS.noProgressTurns) {
61
+ return { stuck: true, reason: "no_progress", turns: agentState.turnsSinceLastProgress };
62
+ }
63
+
64
+ return { stuck: false };
65
+ }
66
+
67
+ /**
68
+ * Determine recovery action based on idle duration.
69
+ *
70
+ * @param {number} idleSeconds
71
+ * @returns {"hint" | "escalate" | "kill"}
72
+ */
73
+ export function determineRecoveryAction(idleSeconds) {
74
+ if (idleSeconds >= STUCK_THRESHOLDS.maxIdleBeforeKill) return "kill";
75
+ if (idleSeconds >= STUCK_THRESHOLDS.maxIdleBeforeEscalate) return "escalate";
76
+ return "hint";
77
+ }
78
+
79
+ // ── Error-to-Persona Routing ─────────────────────────────────────────
80
+
81
+ const ROUTING_RULES = [
82
+ // Stack trace patterns (most reliable)
83
+ { test: (w) => /\.(tsx|jsx|vue|svelte):\d+/.test(w.stackTrace || ""), persona: "frontend" },
84
+ { test: (w) => /React|Next|Vite|Webpack|hydrat/i.test(w.stackTrace || ""), persona: "frontend" },
85
+ { test: (w) => /\.py:\d+/.test(w.stackTrace || ""), persona: "backend" },
86
+ { test: (w) => /\.go:\d+/.test(w.stackTrace || ""), persona: "backend" },
87
+
88
+ // Endpoint patterns
89
+ { test: (w) => /\.(html|css|js|png|svg|woff)$/.test(w.endpoint || ""), persona: "frontend" },
90
+ { test: (w) => /\/api\/v\d+\/auth/.test(w.endpoint || ""), persona: "security" },
91
+ { test: (w) => /\/api\//.test(w.endpoint || ""), persona: "backend" },
92
+
93
+ // Error code patterns
94
+ { test: (w) => /HYDRATION|RENDER|DOM|CSR|SSR/i.test(w.errorCode || ""), persona: "frontend" },
95
+ { test: (w) => /AUTH|TOKEN|SESSION|PERMISSION/i.test(w.errorCode || ""), persona: "security" },
96
+ { test: (w) => /TIMEOUT|ECONNREFUSED|DNS|SOCKET/i.test(w.errorCode || ""), persona: "infrastructure" },
97
+ { test: (w) => /QUERY|MIGRATION|CONSTRAINT|DEADLOCK/i.test(w.errorCode || ""), persona: "data" },
98
+ ];
99
+
100
+ /**
101
+ * Route an error work item to the appropriate persona.
102
+ *
103
+ * @param {object} workItem - Error queue item
104
+ * @returns {string} Persona ID (e.g., "frontend", "backend", "security")
105
+ */
106
+ export function routeErrorToPersona(workItem) {
107
+ for (const rule of ROUTING_RULES) {
108
+ if (rule.test(workItem)) return rule.persona;
109
+ }
110
+ return "backend"; // default fallback
111
+ }
112
+
113
+ // ── Alert Building ───────────────────────────────────────────────────
114
+
115
+ /**
116
+ * Build a concise alert payload for Slack/Telegram.
117
+ *
118
+ * @param {object} config
119
+ * @param {string} config.agentId - Persona ID
120
+ * @param {string} config.event - Alert event type
121
+ * @param {object} config.state - Agent state snapshot
122
+ * @param {string} [config.workItemId]
123
+ * @param {string} [config.jiraIssueKey]
124
+ * @returns {{ headline, body, severity }}
125
+ */
126
+ export function buildAlertPayload({ agentId, event, state, workItemId, jiraIssueKey }) {
127
+ const visual = PERSONA_VISUALS[agentId] || { avatar: "", fullName: agentId, color: "white" };
128
+ const avatar = visual.avatar;
129
+ const name = visual.fullName;
130
+
131
+ const lines = [];
132
+ lines.push(`${avatar} ${name} \u2014 ${formatAlertEvent(event)}`);
133
+ lines.push("\u2501".repeat(30));
134
+
135
+ if (workItemId) lines.push(`Work Item: ${workItemId}`);
136
+ if (jiraIssueKey) lines.push(`Jira: ${jiraIssueKey}`);
137
+
138
+ if (state) {
139
+ if (state.durationMs) lines.push(`Duration: ${formatDuration(state.durationMs)}`);
140
+ if (state.budgetPct !== undefined) lines.push(`Budget: ${state.budgetPct.toFixed(0)}%`);
141
+ if (state.turnsCompleted !== undefined) lines.push(`Turns: ${state.turnsCompleted}/${state.turnsMax || "?"}`);
142
+ if (state.findingCount !== undefined) lines.push(`Findings: ${state.findingCount}`);
143
+ if (state.lastAction) lines.push(`Last: ${state.lastAction}`);
144
+ if (state.costUsd !== undefined) lines.push(`Cost: $${state.costUsd.toFixed(2)}`);
145
+ if (state.prNumber) lines.push(`PR: #${state.prNumber}`);
146
+ }
147
+
148
+ const severity = event.includes("stuck") || event.includes("kill") ? "warning" :
149
+ event.includes("merged") || event.includes("complete") ? "success" : "info";
150
+
151
+ lines.push("");
152
+ lines.push(`\u2014 ${name}, SentinelLayer`);
153
+
154
+ return {
155
+ headline: `${avatar} ${name}: ${formatAlertEvent(event)}`,
156
+ body: lines.join("\n"),
157
+ severity,
158
+ };
159
+ }
160
+
161
+ function formatAlertEvent(event) {
162
+ const map = {
163
+ agent_stuck: "Agent Stuck",
164
+ agent_recovered: "Agent Recovered",
165
+ budget_warning: "Budget Warning",
166
+ budget_exhausted: "Budget Exhausted",
167
+ pr_merged: "PR Merged",
168
+ audit_complete: "Audit Complete",
169
+ fix_complete: "Fix Complete",
170
+ kill_switch: "Kill Switch Activated",
171
+ error_intake: "Error Received",
172
+ jira_resolved: "Jira Resolved",
173
+ };
174
+ return map[event] || event;
175
+ }
176
+
177
+ function formatDuration(ms) {
178
+ if (ms < 60000) return `${(ms / 1000).toFixed(0)}s`;
179
+ if (ms < 3600000) return `${(ms / 60000).toFixed(1)}m`;
180
+ return `${(ms / 3600000).toFixed(1)}h`;
181
+ }
182
+
183
+ // ── Health Summary ───────────────────────────────────────────────────
184
+
185
+ /**
186
+ * Build a periodic health summary for Slack/Telegram.
187
+ *
188
+ * @param {object[]} agentStates - Current states of all running agents
189
+ * @returns {{ headline, body } | null} null if nothing to report
190
+ */
191
+ export function buildHealthSummary(agentStates) {
192
+ if (!agentStates || agentStates.length === 0) return null;
193
+
194
+ const active = agentStates.filter(a => a.status === "active");
195
+ const stuck = agentStates.filter(a => a.stuck);
196
+ const completed = agentStates.filter(a => a.status === "completed");
197
+
198
+ if (active.length === 0 && stuck.length === 0 && completed.length === 0) return null;
199
+
200
+ const lines = [];
201
+ lines.push("\u{1F4CA} Pulse Health Summary");
202
+ lines.push("\u2501".repeat(30));
203
+ lines.push(`Active: ${active.length} | Stuck: ${stuck.length} | Completed: ${completed.length}`);
204
+
205
+ for (const a of active.slice(0, 5)) {
206
+ const visual = PERSONA_VISUALS[a.agentId] || {};
207
+ lines.push(` ${visual.avatar || ""} ${visual.shortName || a.agentId}: ${a.findingCount || 0} findings, $${(a.costUsd || 0).toFixed(2)}`);
208
+ }
209
+
210
+ if (stuck.length > 0) {
211
+ lines.push("");
212
+ lines.push("\u26A0\uFE0F Stuck agents:");
213
+ for (const s of stuck) {
214
+ const visual = PERSONA_VISUALS[s.agentId] || {};
215
+ lines.push(` ${visual.avatar || ""} ${visual.shortName || s.agentId}: ${s.reason || "unknown"} (${s.idleSeconds || 0}s idle)`);
216
+ }
217
+ }
218
+
219
+ return {
220
+ headline: `Pulse: ${active.length} active, ${stuck.length} stuck, ${completed.length} done`,
221
+ body: lines.join("\n"),
222
+ };
223
+ }
224
+
225
+ // ── Webhook Delivery ─────────────────────────────────────────────────
226
+
227
+ /**
228
+ * Send an alert to configured Slack/Telegram webhooks.
229
+ * Reads config from env or .sentinelayer.yml.
230
+ * Fails silently — alert delivery must never block agent work.
231
+ *
232
+ * @param {object} alert - { headline, body, severity } from buildAlertPayload
233
+ * @param {object} [channels] - Override channel config
234
+ * @returns {Promise<{ sent: object[], errors: object[] }>}
235
+ */
236
+ export async function sendAlert(alert, channels) {
237
+ const resolved = channels || resolveAlertChannels();
238
+ const sent = [];
239
+ const errors = [];
240
+
241
+ for (const channel of resolved) {
242
+ try {
243
+ if (channel.type === "slack" && channel.webhook_url) {
244
+ await sendSlackWebhook(channel.webhook_url, alert);
245
+ sent.push({ type: "slack", status: "sent" });
246
+ } else if (channel.type === "telegram" && channel.bot_token && channel.chat_id) {
247
+ await sendTelegramMessage(channel.bot_token, channel.chat_id, alert);
248
+ sent.push({ type: "telegram", status: "sent" });
249
+ }
250
+ } catch (err) {
251
+ errors.push({ type: channel.type, error: err.message });
252
+ }
253
+ }
254
+
255
+ return { sent, errors };
256
+ }
257
+
258
+ async function sendSlackWebhook(webhookUrl, alert) {
259
+ const payload = JSON.stringify({
260
+ text: alert.headline,
261
+ blocks: [
262
+ { type: "header", text: { type: "plain_text", text: alert.headline } },
263
+ { type: "section", text: { type: "mrkdwn", text: alert.body } },
264
+ ],
265
+ });
266
+
267
+ const response = await fetch(webhookUrl, {
268
+ method: "POST",
269
+ headers: { "Content-Type": "application/json" },
270
+ body: payload,
271
+ signal: AbortSignal.timeout(10000),
272
+ });
273
+
274
+ if (!response.ok) {
275
+ throw new Error("Slack webhook failed: " + response.status);
276
+ }
277
+ }
278
+
279
+ async function sendTelegramMessage(botToken, chatId, alert) {
280
+ const url = "https://api.telegram.org/bot" + botToken + "/sendMessage";
281
+ const payload = JSON.stringify({
282
+ chat_id: chatId,
283
+ text: alert.body,
284
+ parse_mode: "Markdown",
285
+ disable_web_page_preview: true,
286
+ });
287
+
288
+ const response = await fetch(url, {
289
+ method: "POST",
290
+ headers: { "Content-Type": "application/json" },
291
+ body: payload,
292
+ signal: AbortSignal.timeout(10000),
293
+ });
294
+
295
+ if (!response.ok) {
296
+ throw new Error("Telegram send failed: " + response.status);
297
+ }
298
+ }
299
+
300
+ function resolveAlertChannels() {
301
+ const channels = [];
302
+
303
+ // Slack from env
304
+ const slackUrl = process.env.SENTINELAYER_SLACK_WEBHOOK_URL;
305
+ if (slackUrl) {
306
+ channels.push({ type: "slack", webhook_url: slackUrl });
307
+ }
308
+
309
+ // Telegram from env
310
+ const tgToken = process.env.SENTINELAYER_TELEGRAM_BOT_TOKEN;
311
+ const tgChat = process.env.SENTINELAYER_TELEGRAM_CHAT_ID;
312
+ if (tgToken && tgChat) {
313
+ channels.push({ type: "telegram", bot_token: tgToken, chat_id: tgChat });
314
+ }
315
+
316
+ return channels;
317
+ }
318
+
319
+ export { STUCK_THRESHOLDS };