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,186 @@
1
+ import { PERSONA_VISUALS, resolvePersonaVisual } from "./config/definition.js";
2
+
3
+ /**
4
+ * Jules Tanaka — Streaming Event Formatter
5
+ *
6
+ * Formats NDJSON events for external agent consumption and terminal display.
7
+ * Universal envelope: every event carries agent identity, usage snapshot, timestamp.
8
+ */
9
+
10
+ const SCHEMA_VERSION = 1;
11
+
12
+ /**
13
+ * Build an NDJSON event envelope.
14
+ *
15
+ * @param {string} event - Event type (agent_start, tool_call, finding, heartbeat, etc.)
16
+ * @param {object} agentIdentity - { id, persona, color?, avatar? }
17
+ * @param {object} payload - Event-specific data
18
+ * @param {object} [usage] - Running usage totals
19
+ * @param {string} [runId] - Run identifier
20
+ * @returns {object} Complete event envelope
21
+ */
22
+ export function buildStreamEvent(event, agentIdentity, payload, usage, runId) {
23
+ const visual = resolvePersonaVisual(agentIdentity?.id) || {};
24
+ return {
25
+ stream: "sl_event",
26
+ version: SCHEMA_VERSION,
27
+ command: "audit.deep",
28
+ runId: runId || null,
29
+ timestamp: new Date().toISOString(),
30
+ agent: {
31
+ id: agentIdentity?.id || "unknown",
32
+ persona: agentIdentity?.persona || visual.fullName || "unknown",
33
+ color: agentIdentity?.color || visual.color || "white",
34
+ avatar: agentIdentity?.avatar || visual.avatar || "",
35
+ },
36
+ event,
37
+ payload: payload || {},
38
+ usage: usage || {},
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Create a streaming emitter bound to a specific agent and run.
44
+ *
45
+ * @param {object} config
46
+ * @param {object} config.agentIdentity - { id, persona }
47
+ * @param {string} config.runId
48
+ * @param {function} [config.onEvent] - Callback for each event
49
+ * @param {boolean} [config.stdoutNdjson] - Also write to stdout as NDJSON
50
+ * @returns {{ emit(event, payload, usage), close() }}
51
+ */
52
+ export function createStreamEmitter({ agentIdentity, runId, onEvent, stdoutNdjson = false }) {
53
+ let closed = false;
54
+ const usageRef = { costUsd: 0, outputTokens: 0, toolCalls: 0, durationMs: 0 };
55
+
56
+ return {
57
+ /**
58
+ * Emit a streaming event.
59
+ */
60
+ emit(event, payload, usage) {
61
+ if (closed) return;
62
+ const merged = { ...usageRef, ...usage };
63
+ Object.assign(usageRef, merged);
64
+ const evt = buildStreamEvent(event, agentIdentity, payload, merged, runId);
65
+ if (onEvent) onEvent(evt);
66
+ if (stdoutNdjson) console.log(JSON.stringify(evt));
67
+ return evt;
68
+ },
69
+
70
+ /**
71
+ * Update accumulated usage without emitting.
72
+ */
73
+ updateUsage(delta) {
74
+ if (delta.costUsd !== undefined) usageRef.costUsd = delta.costUsd;
75
+ if (delta.outputTokens !== undefined) usageRef.outputTokens = delta.outputTokens;
76
+ if (delta.toolCalls !== undefined) usageRef.toolCalls = delta.toolCalls;
77
+ if (delta.durationMs !== undefined) usageRef.durationMs = delta.durationMs;
78
+ },
79
+
80
+ /**
81
+ * Mark emitter as closed (no more events).
82
+ */
83
+ close() {
84
+ closed = true;
85
+ },
86
+
87
+ /**
88
+ * Get current usage snapshot.
89
+ */
90
+ getUsage() {
91
+ return { ...usageRef };
92
+ },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Format a terminal display line for a persona event (non-JSON mode).
98
+ *
99
+ * @param {object} evt - Stream event
100
+ * @returns {string} Formatted line for stderr
101
+ */
102
+ export function formatTerminalLine(evt) {
103
+ const agent = evt.agent || {};
104
+ const avatar = agent.avatar || "";
105
+ const name = agent.persona || agent.id || "Agent";
106
+ const p = evt.payload || {};
107
+
108
+ switch (evt.event) {
109
+ case "agent_start":
110
+ return `${avatar} ${name} starting (mode: ${p.mode || "primary"})...`;
111
+
112
+ case "progress":
113
+ return `${avatar} ${name}: ${p.message || p.phase || "working..."}`;
114
+
115
+ case "tool_call":
116
+ return `${avatar} ${name} [${p.tool}] ${formatToolInput(p.input)}`;
117
+
118
+ case "tool_result":
119
+ return `${avatar} ${name} [${p.tool}] ${p.durationMs || 0}ms ${p.success === false ? "FAILED" : "ok"}`;
120
+
121
+ case "finding": {
122
+ const sev = p.severity || "P3";
123
+ const sevColor = sev === "P0" ? "!!!" : sev === "P1" ? "!!" : sev === "P2" ? "!" : "";
124
+ return `${avatar} [${sev}${sevColor}] ${p.file || ""}:${p.line || ""} ${p.title || ""}`;
125
+ }
126
+
127
+ case "reasoning":
128
+ return `${avatar} ${name}: ${(p.summary || "").slice(0, 120)}`;
129
+
130
+ case "heartbeat": {
131
+ const h = p;
132
+ const budgetPct = h.budgetRemaining?.pct?.toFixed(0) || "?";
133
+ return `${avatar} ${name} [${h.turnsCompleted || 0}/${h.turnsMax || "?"} turns, ${budgetPct}% budget, ${h.findingsSoFar || 0} findings]`;
134
+ }
135
+
136
+ case "budget_warning":
137
+ return `${avatar} ${name} BUDGET WARNING: ${(p.warnings || []).map(w => w.code).join(", ")}`;
138
+
139
+ case "budget_stop":
140
+ return `${avatar} ${name} BUDGET STOP: ${(p.reasons || []).map(r => r.code || r).join(", ")}`;
141
+
142
+ case "swarm_start":
143
+ return `${avatar} ${name} spawning sub-agents (${p.scannerCount || 0} scanners, ${p.hunterCount || 0} hunters)...`;
144
+
145
+ case "swarm_complete":
146
+ return `${avatar} ${name} swarm complete: ${p.totalFindings || 0} findings from ${p.totalAgents || 0} agents ($${(p.totalCostUsd || 0).toFixed(2)})`;
147
+
148
+ case "phase_start":
149
+ return `${avatar} ${name} phase: ${p.phase || "unknown"}`;
150
+
151
+ case "agent_complete": {
152
+ const s = p;
153
+ return `${avatar} ${name} complete: ${s.total || 0} findings (P0=${s.P0 || 0} P1=${s.P1 || 0} P2=${s.P2 || 0}) $${(s.costUsd || 0).toFixed(2)} ${s.durationMs ? (s.durationMs / 1000).toFixed(1) + "s" : ""}`;
154
+ }
155
+
156
+ case "agent_abort":
157
+ return `${avatar} ${name} ABORTED: ${p.reason || "unknown"}`;
158
+
159
+ default:
160
+ return `${avatar} ${name} [${evt.event}]`;
161
+ }
162
+ }
163
+
164
+ function formatToolInput(input) {
165
+ if (!input) return "";
166
+ if (input.file_path) return input.file_path;
167
+ if (input.pattern) return `/${input.pattern}/`;
168
+ if (input.operation) return input.operation;
169
+ if (input.command) return input.command.slice(0, 60);
170
+ return "";
171
+ }
172
+
173
+ /**
174
+ * List all valid event types.
175
+ */
176
+ export const EVENT_TYPES = Object.freeze([
177
+ "agent_start", "agent_complete", "agent_abort", "agent_error",
178
+ "progress", "heartbeat",
179
+ "tool_call", "tool_result",
180
+ "finding", "reasoning",
181
+ "budget_warning", "budget_stop",
182
+ "swarm_start", "swarm_complete",
183
+ "phase_start", "phase_complete",
184
+ "convergence_expansion", "coverage_gap",
185
+ "llm_error",
186
+ ]);
@@ -0,0 +1,74 @@
1
+ import { JulesSubAgent } from "./sub-agent.js";
2
+
3
+ const FILE_SCANNER_PROMPT = `You are a FileScanner sub-agent working for Jules Tanaka (SentinelLayer Frontend Specialist).
4
+
5
+ Your job: Read each file in your scope and extract a structured summary.
6
+
7
+ For each file, extract:
8
+ - componentName: the primary exported component/function name
9
+ - useStateCount: number of useState calls
10
+ - useEffectCount: number of useEffect calls
11
+ - imports: list of imported modules (just the module names)
12
+ - exports: list of exported names
13
+ - loc: approximate line count
14
+ - riskSignals: array of any of these detected patterns:
15
+ - "dangerouslySetInnerHTML" if found
16
+ - "eval" if found
17
+ - "window_access_in_render" if window/document/localStorage used outside useEffect
18
+ - "missing_cleanup" if useEffect has subscription/timer without return
19
+ - "god_component" if useState count >= 16
20
+ - "large_file" if LOC > 500
21
+
22
+ Use the FileRead tool to read each file. Use Grep if you need to search for patterns.
23
+
24
+ Return your findings as a JSON array in a \`\`\`json code block:
25
+ [
26
+ {
27
+ "file": "path/to/file.tsx",
28
+ "componentName": "Dashboard",
29
+ "useStateCount": 3,
30
+ "useEffectCount": 2,
31
+ "imports": ["react", "zustand", "./Header"],
32
+ "exports": ["Dashboard"],
33
+ "loc": 150,
34
+ "riskSignals": [],
35
+ "discoveredDependencies": ["./utils/formatDate", "../hooks/useAuth"]
36
+ }
37
+ ]
38
+
39
+ The discoveredDependencies field is critical: list any imports that point to files NOT in your assigned scope. These will be used to expand the audit coverage.
40
+
41
+ Be thorough but concise. Do not explain findings — just extract data.`;
42
+
43
+ /**
44
+ * Create a FileScanner sub-agent for a batch of files.
45
+ *
46
+ * @param {object} config
47
+ * @param {string} config.id - Unique ID (e.g., "scanner-dashboard")
48
+ * @param {string[]} config.files - Files to scan
49
+ * @param {object} config.budget - Budget slice
50
+ * @param {object} config.blackboard - Shared blackboard
51
+ * @param {object} [config.provider] - LLM provider overrides
52
+ * @param {AbortController} [config.parentAbort]
53
+ * @param {function} [config.onEvent]
54
+ */
55
+ export function createFileScanner(config) {
56
+ return new JulesSubAgent({
57
+ id: config.id || `scanner-${Date.now()}`,
58
+ role: "FileScanner",
59
+ systemPrompt: FILE_SCANNER_PROMPT,
60
+ allowedTools: ["FileRead", "Grep", "Glob"],
61
+ scope: { files: config.files },
62
+ budget: config.budget || {
63
+ maxCostUsd: 0.5,
64
+ maxOutputTokens: 3000,
65
+ maxRuntimeMs: 60000,
66
+ maxToolCalls: config.files.length * 2 + 5,
67
+ },
68
+ blackboard: config.blackboard,
69
+ maxTurns: Math.min(config.files.length + 3, 15),
70
+ provider: config.provider,
71
+ parentAbort: config.parentAbort,
72
+ onEvent: config.onEvent,
73
+ });
74
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Jules Tanaka — Sub-Agent Swarm
3
+ *
4
+ * Parallel isolated agents for frontend audit work.
5
+ * Each sub-agent: own conversation, own budget, shared blackboard.
6
+ */
7
+
8
+ export { JulesSubAgent, runSubAgentBatch, SubAgentError } from "./sub-agent.js";
9
+ export { createFileScanner } from "./file-scanner.js";
10
+ export { createPatternHunter, HUNT_TYPES } from "./pattern-hunter.js";
11
+ export { shouldSpawnSubAgents, runJulesSwarm } from "./orchestrator.js";
@@ -0,0 +1,362 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import fsp from "node:fs/promises";
4
+
5
+ import { createFileScanner } from "./file-scanner.js";
6
+ import { createPatternHunter, HUNT_TYPES } from "./pattern-hunter.js";
7
+ import { runSubAgentBatch } from "./sub-agent.js";
8
+ import { frontendAnalyze } from "../tools/frontend-analyze.js";
9
+ import { createAgentContext } from "../tools/dispatch.js";
10
+
11
+ /**
12
+ * Jules Swarm Orchestrator
13
+ *
14
+ * Coordinates parallel sub-agents for thorough frontend audit.
15
+ * Multi-pass convergence ensures no file is missed:
16
+ * Pass 1 (FileScanners): Read all files, discover import deps
17
+ * Pass 2 (PatternHunters): Search for 6 issue classes in parallel
18
+ * Convergence: Expand scope with discovered deps, re-scan if needed
19
+ * Coverage verification: Ensure every reachable file was read
20
+ */
21
+
22
+ const SPAWN_THRESHOLDS = {
23
+ minFilesForSwarm: 15,
24
+ minRouteGroupsForSwarm: 3,
25
+ minLocForSwarm: 5000,
26
+ maxFilesPerScanner: 12,
27
+ maxConcurrentAgents: 4,
28
+ };
29
+
30
+ /**
31
+ * Decide whether the frontend surface warrants sub-agent spawning.
32
+ */
33
+ export function shouldSpawnSubAgents(scopeMap) {
34
+ const frontendFiles = (scopeMap.primary || []).filter(f => isFrontendFile(f.path || f));
35
+ const routeGroups = detectRouteGroups(frontendFiles);
36
+ const totalLoc = frontendFiles.reduce((sum, f) => sum + (f.loc || 80), 0);
37
+
38
+ return {
39
+ spawn: (
40
+ frontendFiles.length > SPAWN_THRESHOLDS.minFilesForSwarm ||
41
+ routeGroups.length >= SPAWN_THRESHOLDS.minRouteGroupsForSwarm ||
42
+ totalLoc > SPAWN_THRESHOLDS.minLocForSwarm
43
+ ),
44
+ fileCount: frontendFiles.length,
45
+ routeGroups: routeGroups.length,
46
+ estimatedLoc: totalLoc,
47
+ reason: frontendFiles.length > SPAWN_THRESHOLDS.minFilesForSwarm
48
+ ? `${frontendFiles.length} frontend files exceeds threshold (${SPAWN_THRESHOLDS.minFilesForSwarm})`
49
+ : routeGroups.length >= SPAWN_THRESHOLDS.minRouteGroupsForSwarm
50
+ ? `${routeGroups.length} route groups exceeds threshold (${SPAWN_THRESHOLDS.minRouteGroupsForSwarm})`
51
+ : totalLoc > SPAWN_THRESHOLDS.minLocForSwarm
52
+ ? `${totalLoc} LOC exceeds threshold (${SPAWN_THRESHOLDS.minLocForSwarm})`
53
+ : "below all thresholds",
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Run the full swarm orchestration: scanners → hunters → convergence → coverage.
59
+ *
60
+ * @param {object} config
61
+ * @param {object} config.scopeMap - { primary, secondary, tertiary } file lists
62
+ * @param {string} config.rootPath - Codebase root
63
+ * @param {object} config.blackboard - Shared blackboard instance
64
+ * @param {object} config.budget - Total budget for all sub-agents
65
+ * @param {object} [config.provider] - LLM provider overrides
66
+ * @param {AbortController} [config.parentAbort]
67
+ * @param {function} [config.onEvent]
68
+ * @returns {Promise<SwarmResult>}
69
+ */
70
+ export async function runJulesSwarm(config) {
71
+ const {
72
+ scopeMap, rootPath, blackboard, budget,
73
+ provider, parentAbort, onEvent,
74
+ } = config;
75
+
76
+ const runId = `swarm-jules-${Date.now()}-${randomUUID().slice(0, 8)}`;
77
+ const startedAt = Date.now();
78
+ const allResults = [];
79
+
80
+ emit(onEvent, "swarm_start", {
81
+ runId,
82
+ phases: ["file_scan", "pattern_hunt", "convergence", "coverage_verify"],
83
+ });
84
+
85
+ // ── Phase 1: File Scanners ──────────────────────────────────────
86
+
87
+ const primaryFiles = (scopeMap.primary || []).map(f => f.path || f);
88
+ const partitions = partitionFiles(primaryFiles, SPAWN_THRESHOLDS.maxFilesPerScanner);
89
+
90
+ emit(onEvent, "phase_start", {
91
+ phase: "file_scan",
92
+ scannerCount: partitions.length,
93
+ totalFiles: primaryFiles.length,
94
+ });
95
+
96
+ const scannerBudgetSlice = divideBudget(budget, partitions.length + HUNT_TYPES.length);
97
+
98
+ const scanners = partitions.map((files, i) =>
99
+ createFileScanner({
100
+ id: `scanner-${i}`,
101
+ files,
102
+ budget: scannerBudgetSlice,
103
+ blackboard,
104
+ provider,
105
+ parentAbort,
106
+ onEvent,
107
+ }),
108
+ );
109
+
110
+ const scanResults = await runSubAgentBatch(scanners, {
111
+ maxConcurrent: SPAWN_THRESHOLDS.maxConcurrentAgents,
112
+ });
113
+ allResults.push(...scanResults);
114
+
115
+ emit(onEvent, "phase_complete", {
116
+ phase: "file_scan",
117
+ agentsCompleted: scanResults.length,
118
+ findingsCount: scanResults.reduce((s, r) => s + r.findings.length, 0),
119
+ });
120
+
121
+ // ── Phase 2: Pattern Hunters ────────────────────────────────────
122
+
123
+ emit(onEvent, "phase_start", {
124
+ phase: "pattern_hunt",
125
+ hunterCount: HUNT_TYPES.length,
126
+ huntTypes: HUNT_TYPES,
127
+ });
128
+
129
+ const hunterBudgetSlice = divideBudget(budget, partitions.length + HUNT_TYPES.length);
130
+
131
+ const hunters = HUNT_TYPES.map(huntType =>
132
+ createPatternHunter({
133
+ huntType,
134
+ rootPath,
135
+ budget: hunterBudgetSlice,
136
+ blackboard,
137
+ provider,
138
+ parentAbort,
139
+ onEvent,
140
+ }),
141
+ );
142
+
143
+ const huntResults = await runSubAgentBatch(hunters, {
144
+ maxConcurrent: SPAWN_THRESHOLDS.maxConcurrentAgents,
145
+ });
146
+ allResults.push(...huntResults);
147
+
148
+ emit(onEvent, "phase_complete", {
149
+ phase: "pattern_hunt",
150
+ agentsCompleted: huntResults.length,
151
+ findingsCount: huntResults.reduce((s, r) => s + r.findings.length, 0),
152
+ });
153
+
154
+ // ── Convergence: Expand scope from discovered deps ──────────────
155
+
156
+ emit(onEvent, "phase_start", { phase: "convergence" });
157
+
158
+ const discoveredDeps = collectDiscoveredDeps(scanResults);
159
+ const alreadyScanned = new Set(primaryFiles);
160
+ const newFiles = discoveredDeps.filter(f => !alreadyScanned.has(f));
161
+
162
+ let convergenceResults = [];
163
+ if (newFiles.length > 0 && newFiles.length <= 30) {
164
+ emit(onEvent, "convergence_expansion", {
165
+ newFilesDiscovered: newFiles.length,
166
+ spawningExtraScanner: true,
167
+ });
168
+
169
+ const extraPartitions = partitionFiles(newFiles, SPAWN_THRESHOLDS.maxFilesPerScanner);
170
+ const extraScanners = extraPartitions.map((files, i) =>
171
+ createFileScanner({
172
+ id: `scanner-convergence-${i}`,
173
+ files,
174
+ budget: scannerBudgetSlice,
175
+ blackboard,
176
+ provider,
177
+ parentAbort,
178
+ onEvent,
179
+ }),
180
+ );
181
+
182
+ convergenceResults = await runSubAgentBatch(extraScanners, {
183
+ maxConcurrent: SPAWN_THRESHOLDS.maxConcurrentAgents,
184
+ });
185
+ allResults.push(...convergenceResults);
186
+ }
187
+
188
+ emit(onEvent, "phase_complete", {
189
+ phase: "convergence",
190
+ newFilesDiscovered: newFiles.length,
191
+ extraScannersRun: convergenceResults.length,
192
+ });
193
+
194
+ // ── Coverage Verification ───────────────────────────────────────
195
+ // Coverage is computed from CONFIRMED-READ files (via blackboard tool_call
196
+ // events), not from the seed set. This prevents overstating coverage when
197
+ // sub-agents hit budget limits before reading all assigned files.
198
+
199
+ emit(onEvent, "phase_start", { phase: "coverage_verify" });
200
+
201
+ // Collect confirmed-read files from sub-agent results
202
+ const confirmedReadFiles = new Set();
203
+ for (const result of allResults) {
204
+ // Sub-agents track which files they actually read via tool calls
205
+ if (result.findings) {
206
+ for (const f of result.findings) {
207
+ if (f.file) confirmedReadFiles.add(f.file);
208
+ // FileScanner results include discovered files
209
+ if (f.path) confirmedReadFiles.add(f.path);
210
+ }
211
+ }
212
+ // Also count any file explicitly tracked by agent usage
213
+ if (result.usage?.filesRead) {
214
+ for (const f of result.usage.filesRead) confirmedReadFiles.add(f);
215
+ }
216
+ }
217
+ // Add primary files only if they were in the confirmed set or no agents ran
218
+ const allScannedFiles = confirmedReadFiles.size > 0
219
+ ? confirmedReadFiles
220
+ : new Set([...primaryFiles, ...newFiles]);
221
+
222
+ // Use FrontendAnalyze to check what files should exist
223
+ let frameworkInfo = {};
224
+ try {
225
+ frameworkInfo = frontendAnalyze({ operation: "detect_framework", path: rootPath });
226
+ } catch { /* proceed without framework info */ }
227
+
228
+ let scopeGraphInfo = {};
229
+ try {
230
+ scopeGraphInfo = frontendAnalyze({ operation: "scope_graph", path: rootPath });
231
+ } catch { /* proceed without scope graph */ }
232
+
233
+ const expectedFrontendFiles = scopeGraphInfo.components || 0;
234
+ const coverageRatio = expectedFrontendFiles > 0
235
+ ? ((allScannedFiles.size / expectedFrontendFiles) * 100).toFixed(1)
236
+ : "N/A";
237
+
238
+ // Identify files that were assigned but not confirmed-read
239
+ const assignedButUnread = primaryFiles.filter(f => !confirmedReadFiles.has(f));
240
+ const missedFiles = assignedButUnread.length > 0 && confirmedReadFiles.size > 0
241
+ ? assignedButUnread
242
+ : [];
243
+
244
+ const coverageLedger = {
245
+ seedFilesAssigned: primaryFiles.length,
246
+ confirmedReadFiles: confirmedReadFiles.size,
247
+ expandedFilesDiscovered: newFiles.length,
248
+ totalFilesReviewed: allScannedFiles.size,
249
+ expectedFrontendFiles,
250
+ coverageRatio,
251
+ missedFiles,
252
+ coverageMethod: confirmedReadFiles.size > 0 ? "confirmed_read" : "seed_based_fallback",
253
+ };
254
+
255
+ emit(onEvent, "phase_complete", {
256
+ phase: "coverage_verify",
257
+ coverage: coverageLedger,
258
+ });
259
+
260
+ // ── Build Swarm Result ──────────────────────────────────────────
261
+
262
+ const totalFindings = allResults.reduce((s, r) => s + r.findings.length, 0);
263
+ const totalCost = allResults.reduce((s, r) => s + (r.usage?.costUsd || 0), 0);
264
+ const totalToolCalls = allResults.reduce((s, r) => s + (r.usage?.toolCalls || 0), 0);
265
+ const durationMs = Date.now() - startedAt;
266
+
267
+ const result = {
268
+ runId,
269
+ status: "completed",
270
+ framework: frameworkInfo.framework || "unknown",
271
+ phases: {
272
+ fileScanning: { agents: scanResults.length, findings: scanResults.reduce((s, r) => s + r.findings.length, 0) },
273
+ patternHunting: { agents: huntResults.length, findings: huntResults.reduce((s, r) => s + r.findings.length, 0) },
274
+ convergence: { newFiles: newFiles.length, extraScanners: convergenceResults.length },
275
+ },
276
+ coverage: coverageLedger,
277
+ findings: {
278
+ total: totalFindings,
279
+ byAgent: allResults.map(r => ({ agentId: r.agentId, role: r.role, count: r.findings.length })),
280
+ },
281
+ usage: {
282
+ totalAgents: allResults.length,
283
+ totalCostUsd: totalCost,
284
+ totalToolCalls,
285
+ totalDurationMs: durationMs,
286
+ },
287
+ agentResults: allResults,
288
+ };
289
+
290
+ emit(onEvent, "swarm_complete", {
291
+ runId,
292
+ totalFindings,
293
+ totalAgents: allResults.length,
294
+ totalCostUsd: totalCost,
295
+ durationMs,
296
+ coverageRatio,
297
+ });
298
+
299
+ return result;
300
+ }
301
+
302
+ // ── Helpers ──────────────────────────────────────────────────────────
303
+
304
+ function isFrontendFile(filePath) {
305
+ return /\.(tsx|jsx|vue|svelte|css|scss|less)$/.test(filePath);
306
+ }
307
+
308
+ function detectRouteGroups(files) {
309
+ const routeDirs = new Set();
310
+ for (const f of files) {
311
+ const filePath = f.path || f;
312
+ const match = filePath.match(/(?:app|pages)\/([^/]+)/);
313
+ if (match) routeDirs.add(match[1]);
314
+ }
315
+ return [...routeDirs];
316
+ }
317
+
318
+ function partitionFiles(files, maxPerPartition) {
319
+ const partitions = [];
320
+ for (let i = 0; i < files.length; i += maxPerPartition) {
321
+ partitions.push(files.slice(i, i + maxPerPartition));
322
+ }
323
+ return partitions;
324
+ }
325
+
326
+ function divideBudget(totalBudget, agentCount) {
327
+ if (agentCount <= 0) return totalBudget;
328
+ return {
329
+ maxCostUsd: (totalBudget.maxCostUsd || 5) / agentCount,
330
+ maxOutputTokens: Math.floor((totalBudget.maxOutputTokens || 12000) / agentCount),
331
+ maxRuntimeMs: totalBudget.maxRuntimeMs || 300000,
332
+ maxToolCalls: Math.floor((totalBudget.maxToolCalls || 150) / agentCount),
333
+ warningThresholdPercent: totalBudget.warningThresholdPercent || 70,
334
+ };
335
+ }
336
+
337
+ function collectDiscoveredDeps(scanResults) {
338
+ const deps = new Set();
339
+ for (const result of scanResults) {
340
+ for (const finding of result.findings) {
341
+ if (finding.discoveredDependencies) {
342
+ for (const dep of finding.discoveredDependencies) {
343
+ if (typeof dep === "string" && dep.startsWith(".")) {
344
+ deps.add(dep);
345
+ }
346
+ }
347
+ }
348
+ }
349
+ }
350
+ return [...deps];
351
+ }
352
+
353
+ function emit(onEvent, event, payload) {
354
+ if (onEvent) {
355
+ onEvent({
356
+ stream: "sl_event",
357
+ event,
358
+ agent: { id: "frontend", persona: "Jules Tanaka", color: "cyan", avatar: "\u{1F3AF}" },
359
+ payload,
360
+ });
361
+ }
362
+ }