sentinelayer-cli 0.1.2 → 0.4.4

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 (129) hide show
  1. package/README.md +998 -996
  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 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +327 -319
  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 +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +557 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +503 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/agents/jules/tools/url-policy.js +100 -0
  30. package/src/ai/aidenid.js +972 -945
  31. package/src/ai/client.js +508 -508
  32. package/src/ai/domain-target-store.js +268 -268
  33. package/src/ai/identity-store.js +270 -270
  34. package/src/ai/site-store.js +145 -145
  35. package/src/audit/agents/architecture.js +180 -180
  36. package/src/audit/agents/compliance.js +179 -179
  37. package/src/audit/agents/documentation.js +165 -165
  38. package/src/audit/agents/performance.js +145 -145
  39. package/src/audit/agents/security.js +215 -215
  40. package/src/audit/agents/testing.js +172 -172
  41. package/src/audit/orchestrator.js +557 -557
  42. package/src/audit/package.js +204 -204
  43. package/src/audit/registry.js +284 -284
  44. package/src/audit/replay.js +103 -103
  45. package/src/auth/gate.js +45 -11
  46. package/src/auth/http.js +270 -113
  47. package/src/auth/service.js +891 -848
  48. package/src/auth/session-store.js +359 -345
  49. package/src/cli.js +252 -252
  50. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  51. package/src/commands/ai/provision-governance.js +1272 -1246
  52. package/src/commands/ai/shared.js +147 -147
  53. package/src/commands/ai.js +11 -11
  54. package/src/commands/apply.js +12 -12
  55. package/src/commands/audit.js +1166 -1166
  56. package/src/commands/auth.js +375 -366
  57. package/src/commands/chat.js +191 -191
  58. package/src/commands/config.js +184 -184
  59. package/src/commands/cost.js +311 -311
  60. package/src/commands/daemon/core.js +850 -850
  61. package/src/commands/daemon/extended.js +1048 -1048
  62. package/src/commands/daemon/shared.js +213 -213
  63. package/src/commands/daemon.js +11 -11
  64. package/src/commands/guide.js +174 -174
  65. package/src/commands/ingest.js +58 -58
  66. package/src/commands/init.js +55 -55
  67. package/src/commands/legacy-args.js +10 -10
  68. package/src/commands/mcp.js +461 -404
  69. package/src/commands/omargate.js +15 -15
  70. package/src/commands/persona.js +20 -20
  71. package/src/commands/plugin.js +260 -260
  72. package/src/commands/policy.js +132 -132
  73. package/src/commands/prompt.js +238 -238
  74. package/src/commands/review.js +704 -704
  75. package/src/commands/scan.js +866 -788
  76. package/src/commands/spec.js +716 -716
  77. package/src/commands/swarm.js +651 -651
  78. package/src/commands/telemetry.js +202 -202
  79. package/src/commands/watch.js +510 -510
  80. package/src/config/agent-dictionary.js +182 -182
  81. package/src/config/io.js +56 -56
  82. package/src/config/paths.js +18 -18
  83. package/src/config/schema.js +55 -55
  84. package/src/config/service.js +184 -184
  85. package/src/cost/budget.js +235 -235
  86. package/src/cost/history.js +188 -188
  87. package/src/cost/tracker.js +171 -171
  88. package/src/daemon/artifact-lineage.js +534 -534
  89. package/src/daemon/assignment-ledger.js +770 -770
  90. package/src/daemon/ast-parser-layer.js +258 -258
  91. package/src/daemon/budget-governor.js +633 -633
  92. package/src/daemon/callgraph-overlay.js +646 -646
  93. package/src/daemon/error-worker.js +626 -626
  94. package/src/daemon/hybrid-mapper.js +929 -929
  95. package/src/daemon/jira-lifecycle.js +632 -632
  96. package/src/daemon/operator-control.js +657 -657
  97. package/src/daemon/reliability-lane.js +471 -471
  98. package/src/daemon/watchdog.js +971 -971
  99. package/src/guide/generator.js +316 -316
  100. package/src/ingest/engine.js +918 -918
  101. package/src/legacy-cli.js +2592 -2435
  102. package/src/mcp/registry.js +695 -695
  103. package/src/memory/blackboard.js +301 -301
  104. package/src/memory/retrieval.js +581 -581
  105. package/src/plugin/manifest.js +553 -553
  106. package/src/policy/packs.js +144 -144
  107. package/src/prompt/generator.js +118 -106
  108. package/src/review/ai-review.js +669 -669
  109. package/src/review/local-review.js +1295 -1284
  110. package/src/review/replay.js +235 -235
  111. package/src/review/report.js +664 -664
  112. package/src/review/spec-binding.js +487 -487
  113. package/src/scaffold/generator.js +67 -0
  114. package/src/scaffold/templates.js +150 -0
  115. package/src/scan/generator.js +418 -351
  116. package/src/scan/gh-secrets.js +107 -0
  117. package/src/spec/generator.js +519 -519
  118. package/src/spec/regenerate.js +237 -237
  119. package/src/spec/templates.js +91 -91
  120. package/src/swarm/dashboard.js +247 -247
  121. package/src/swarm/factory.js +363 -363
  122. package/src/swarm/pentest.js +934 -934
  123. package/src/swarm/registry.js +419 -419
  124. package/src/swarm/report.js +158 -158
  125. package/src/swarm/runtime.js +576 -576
  126. package/src/swarm/scenario-dsl.js +272 -272
  127. package/src/telemetry/ledger.js +302 -302
  128. package/src/telemetry/sync.js +107 -61
  129. package/src/ui/markdown.js +220 -220
@@ -1,651 +1,651 @@
1
- import path from "node:path";
2
- import process from "node:process";
3
-
4
- import pc from "picocolors";
5
-
6
- import { buildSwarmExecutionPlan, writeSwarmPlanArtifacts } from "../swarm/factory.js";
7
- import { loadSwarmRegistry, selectSwarmAgents } from "../swarm/registry.js";
8
- import { loadSwarmPlanFile, loadSwarmPlaybook, runSwarmRuntime } from "../swarm/runtime.js";
9
- import {
10
- loadSwarmDashboardSnapshot,
11
- renderSwarmDashboard,
12
- watchSwarmDashboard,
13
- } from "../swarm/dashboard.js";
14
- import { buildSwarmExecutionReport } from "../swarm/report.js";
15
- import {
16
- parseScenarioFile,
17
- renderScenarioTemplate,
18
- validateScenarioSpec,
19
- writeScenarioTemplate,
20
- } from "../swarm/scenario-dsl.js";
21
- import { listBuiltinPentestScenarios, runSwarmPentest } from "../swarm/pentest.js";
22
-
23
- function shouldEmitJson(options, command) {
24
- const local = Boolean(options && options.json);
25
- const globalFromCommand =
26
- command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
27
- return local || globalFromCommand;
28
- }
29
-
30
- function parseMaxParallel(rawValue) {
31
- const normalized = Number(rawValue || 0);
32
- if (!Number.isFinite(normalized) || normalized < 1) {
33
- throw new Error("max-parallel must be an integer >= 1.");
34
- }
35
- return Math.floor(normalized);
36
- }
37
-
38
- function parseMaxSteps(rawValue) {
39
- const normalized = Number(rawValue || 0);
40
- if (!Number.isFinite(normalized) || normalized < 1) {
41
- throw new Error("max-steps must be an integer >= 1.");
42
- }
43
- return Math.floor(normalized);
44
- }
45
-
46
- function parsePollSeconds(rawValue, fieldName) {
47
- const normalized = Number(rawValue || 0);
48
- if (!Number.isFinite(normalized) || normalized <= 0) {
49
- throw new Error(`${fieldName} must be a positive number.`);
50
- }
51
- return normalized;
52
- }
53
-
54
- function parsePositiveNumber(rawValue, fieldName) {
55
- const normalized = Number(rawValue || 0);
56
- if (!Number.isFinite(normalized) || normalized <= 0) {
57
- throw new Error(`${fieldName} must be a positive number.`);
58
- }
59
- return normalized;
60
- }
61
-
62
- function normalizeString(value) {
63
- return String(value || "").trim();
64
- }
65
-
66
- function ensureOmarIncluded(registryAgents = [], selectedAgents = []) {
67
- const omarAgent = registryAgents.find((agent) => agent.id === "omar");
68
- if (!omarAgent) {
69
- throw new Error("Swarm registry must include 'omar' orchestrator.");
70
- }
71
- if (selectedAgents.some((agent) => agent.id === "omar")) {
72
- return [...selectedAgents];
73
- }
74
- return [omarAgent, ...selectedAgents];
75
- }
76
-
77
- function printSwarmSummary(payload = {}) {
78
- console.log(pc.bold("Swarm plan generated"));
79
- console.log(pc.gray(`Run: ${payload.runId}`));
80
- console.log(pc.gray(`Plan JSON: ${payload.planJsonPath}`));
81
- console.log(pc.gray(`Plan Markdown: ${payload.planMarkdownPath}`));
82
- console.log(`Scenario: ${payload.scenario}`);
83
- console.log(`Agents: ${payload.selectedAgents.join(", ")}`);
84
- console.log(
85
- `Budgets: cost<=${payload.globalBudget.maxCostUsd} tokens<=${payload.globalBudget.maxOutputTokens} runtime_ms<=${payload.globalBudget.maxRuntimeMs} tools<=${payload.globalBudget.maxToolCalls}`
86
- );
87
- }
88
-
89
- function printRuntimeSummary(payload = {}) {
90
- console.log(pc.bold("Swarm runtime complete"));
91
- console.log(pc.gray(`Runtime run: ${payload.runtimeRunId}`));
92
- console.log(pc.gray(`Plan run: ${payload.planRunId}`));
93
- console.log(pc.gray(`Runtime JSON: ${payload.runtimeJsonPath}`));
94
- console.log(pc.gray(`Runtime events: ${payload.runtimeEventsPath}`));
95
- console.log(`Status: ${payload.completed ? "completed" : `stopped (${payload.stop.stopClass})`}`);
96
- console.log(
97
- `Usage: output_tokens=${payload.usage.outputTokens} tool_calls=${payload.usage.toolCalls} duration_ms=${payload.usage.durationMs} cost_usd=${payload.usage.costUsd}`
98
- );
99
- }
100
-
101
- function printPentestSummary(payload = {}) {
102
- console.log(pc.bold("Swarm pen-test complete"));
103
- console.log(pc.gray(`Run: ${payload.runId}`));
104
- console.log(pc.gray(`Report JSON: ${payload.reportJsonPath}`));
105
- console.log(pc.gray(`Report Markdown: ${payload.reportMarkdownPath}`));
106
- console.log(pc.gray(`Audit log: ${payload.auditLogPath}`));
107
- console.log(`Target: ${payload.target.url} (${payload.target.targetId})`);
108
- console.log(`Scenario: ${payload.scenarioId}`);
109
- console.log(
110
- `Findings: P0=${payload.summary.P0} P1=${payload.summary.P1} P2=${payload.summary.P2} P3=${payload.summary.P3}`
111
- );
112
- }
113
-
114
- export function registerSwarmCommand(program) {
115
- const swarm = program
116
- .command("swarm")
117
- .description("Plan OMAR-governed swarm execution with deterministic assignments and budgets");
118
-
119
- swarm
120
- .command("registry")
121
- .description("List swarm agent registry records")
122
- .option("--registry-file <path>", "Optional custom swarm registry file")
123
- .option("--json", "Emit machine-readable output")
124
- .action(async (options, command) => {
125
- const emitJson = shouldEmitJson(options, command);
126
- const registry = await loadSwarmRegistry({
127
- registryFile: options.registryFile,
128
- });
129
- const payload = {
130
- command: "swarm registry",
131
- registrySource: registry.registrySource,
132
- registryFile: registry.registryFile,
133
- agentCount: registry.agents.length,
134
- agents: registry.agents,
135
- };
136
-
137
- if (emitJson) {
138
- console.log(JSON.stringify(payload, null, 2));
139
- return;
140
- }
141
-
142
- console.log(pc.bold("Swarm registry"));
143
- console.log(pc.gray(`Source: ${registry.registrySource}`));
144
- for (const agent of registry.agents) {
145
- console.log(`- ${agent.id} (${agent.persona}) :: ${agent.domain} [${agent.role}]`);
146
- }
147
- });
148
-
149
- swarm
150
- .command("create")
151
- .description("Create a governed swarm run (Phase 12.6 pen-test mode)")
152
- .option("--path <path>", "Target workspace path", ".")
153
- .option("--output-dir <path>", "Optional artifact output root override")
154
- .option("--scenario <id>", "Scenario identifier (`pen-test` or built-in pen-test scenario)", "pen-test")
155
- .option(
156
- "--pen-test-scenario <id>",
157
- "Built-in pen-test scenario when --scenario pen-test",
158
- "auth-bypass"
159
- )
160
- .option("--target <url>", "Target URL to test")
161
- .option("--target-id <id>", "Approved AIdenID target id")
162
- .option("--execute", "Execute live HTTP probes (default is dry-run logging)")
163
- .option("--json", "Emit machine-readable output")
164
- .action(async (options, command) => {
165
- const emitJson = shouldEmitJson(options, command);
166
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
167
- if (!normalizeString(options.target)) {
168
- throw new Error("--target is required.");
169
- }
170
- if (!normalizeString(options.targetId)) {
171
- throw new Error("--target-id is required.");
172
- }
173
-
174
- const report = await runSwarmPentest({
175
- targetPath,
176
- outputDir: options.outputDir,
177
- targetId: options.targetId,
178
- targetUrl: options.target,
179
- scenario: options.scenario,
180
- pentestScenario: options.penTestScenario,
181
- execute: Boolean(options.execute),
182
- env: process.env,
183
- });
184
-
185
- const payload = {
186
- command: "swarm create",
187
- mode: "pen-test",
188
- runId: report.runId,
189
- scenario: report.scenario,
190
- scenarioId: report.scenarioId,
191
- execute: report.execute,
192
- target: report.target,
193
- summary: report.summary,
194
- auditChain: report.auditChain,
195
- checkCount: report.checkCount,
196
- requestCount: report.requestCount,
197
- reportJsonPath: report.reportJsonPath,
198
- reportMarkdownPath: report.reportMarkdownPath,
199
- auditLogPath: report.auditLogPath,
200
- identityIsolationPath: report.identityIsolationPath,
201
- cleanupContractPath: report.cleanupContractPath,
202
- requestPlanPath: report.requestPlanPath,
203
- supportedPentestScenarios: listBuiltinPentestScenarios().map((item) => item.id),
204
- };
205
-
206
- if (emitJson) {
207
- console.log(JSON.stringify(payload, null, 2));
208
- } else {
209
- printPentestSummary(payload);
210
- }
211
-
212
- if (report.summary.blocking) {
213
- process.exitCode = 2;
214
- }
215
- });
216
-
217
- const scenario = swarm
218
- .command("scenario")
219
- .description("Create and validate swarm scenario DSL files");
220
-
221
- scenario
222
- .command("init")
223
- .description("Write scenario DSL template")
224
- .argument("<scenarioId>", "Scenario identifier")
225
- .option("--path <path>", "Target workspace path", ".")
226
- .option("--output <path>", "Output file path (default: .sentinelayer/scenarios/<scenarioId>.sls)")
227
- .option("--start-url <url>", "Default start URL for template", "https://example.com")
228
- .option("--json", "Emit machine-readable output")
229
- .action(async (scenarioId, options, command) => {
230
- const emitJson = shouldEmitJson(options, command);
231
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
232
- const result = await writeScenarioTemplate({
233
- scenarioId,
234
- targetPath,
235
- outputFile: options.output,
236
- startUrl: options.startUrl,
237
- });
238
- const payload = {
239
- command: "swarm scenario init",
240
- scenarioId,
241
- filePath: result.filePath,
242
- template: renderScenarioTemplate({
243
- scenarioId,
244
- startUrl: options.startUrl,
245
- }),
246
- };
247
-
248
- if (emitJson) {
249
- console.log(JSON.stringify(payload, null, 2));
250
- return;
251
- }
252
-
253
- console.log(pc.bold("Swarm scenario template generated"));
254
- console.log(pc.gray(`Scenario: ${scenarioId}`));
255
- console.log(pc.gray(`File: ${result.filePath}`));
256
- });
257
-
258
- scenario
259
- .command("validate")
260
- .description("Validate scenario DSL file")
261
- .option("--file <path>", "Scenario DSL file path")
262
- .option("--json", "Emit machine-readable output")
263
- .action(async (options, command) => {
264
- const emitJson = shouldEmitJson(options, command);
265
- if (!normalizeString(options.file)) {
266
- throw new Error("--file is required.");
267
- }
268
- const parsed = await parseScenarioFile(options.file);
269
- const validation = validateScenarioSpec(parsed.spec);
270
- const payload = {
271
- command: "swarm scenario validate",
272
- filePath: parsed.filePath,
273
- scenarioId: parsed.spec.id,
274
- startUrl: parsed.spec.startUrl,
275
- actionCount: parsed.spec.actions.length,
276
- valid: validation.valid,
277
- errors: validation.errors,
278
- };
279
-
280
- if (emitJson) {
281
- console.log(JSON.stringify(payload, null, 2));
282
- if (!validation.valid) {
283
- process.exitCode = 2;
284
- }
285
- return;
286
- }
287
-
288
- if (validation.valid) {
289
- console.log(pc.green("Scenario DSL valid"));
290
- } else {
291
- console.log(pc.red("Scenario DSL invalid"));
292
- for (const error of validation.errors) {
293
- console.log(`- ${error}`);
294
- }
295
- process.exitCode = 2;
296
- }
297
- console.log(pc.gray(`File: ${parsed.filePath}`));
298
- });
299
-
300
- swarm
301
- .command("plan")
302
- .description("Build deterministic swarm execution plan + artifacts")
303
- .argument("[targetPath]", "Target workspace path", ".")
304
- .option("--path <path>", "Target workspace path override")
305
- .option("--registry-file <path>", "Optional custom swarm registry file")
306
- .option("--agents <ids>", "Comma-separated agent ids (default: full registry)", "")
307
- .option("--scenario <id>", "Scenario identifier", "qa_audit")
308
- .option(
309
- "--objective <text>",
310
- "Execution objective",
311
- "Run OMAR-governed quality/security swarm analysis with deterministic handoffs."
312
- )
313
- .option("--max-parallel <n>", "Maximum specialist agents processed in parallel", "4")
314
- .option("--max-cost-usd <n>", "Global max cost budget", "5")
315
- .option("--max-output-tokens <n>", "Global max output-token budget", "20000")
316
- .option("--max-runtime-ms <n>", "Global max runtime budget (ms)", "3600000")
317
- .option("--max-tool-calls <n>", "Global max tool-call budget", "500")
318
- .option("--warning-threshold-percent <n>", "Budget warning threshold percent", "80")
319
- .option("--output-dir <path>", "Optional artifact output root override")
320
- .option("--json", "Emit machine-readable output")
321
- .action(async (targetPathArg, options, command) => {
322
- const emitJson = shouldEmitJson(options, command);
323
- const targetPath = path.resolve(process.cwd(), String(options.path || targetPathArg || "."));
324
-
325
- const registry = await loadSwarmRegistry({
326
- registryFile: options.registryFile,
327
- });
328
- const selected = selectSwarmAgents(registry.agents, options.agents);
329
- if (selected.missing.length > 0) {
330
- throw new Error(`Unknown agent id(s): ${selected.missing.join(", ")}`);
331
- }
332
- if (selected.selected.length === 0) {
333
- throw new Error("No agents selected for swarm plan.");
334
- }
335
-
336
- const selectedAgents = ensureOmarIncluded(registry.agents, selected.selected);
337
-
338
- const plan = buildSwarmExecutionPlan({
339
- targetPath,
340
- scenario: options.scenario,
341
- objective: options.objective,
342
- agents: selectedAgents,
343
- maxParallel: parseMaxParallel(options.maxParallel),
344
- globalBudget: {
345
- maxCostUsd: parsePositiveNumber(options.maxCostUsd, "max-cost-usd"),
346
- maxOutputTokens: parsePositiveNumber(options.maxOutputTokens, "max-output-tokens"),
347
- maxRuntimeMs: parsePositiveNumber(options.maxRuntimeMs, "max-runtime-ms"),
348
- maxToolCalls: parsePositiveNumber(options.maxToolCalls, "max-tool-calls"),
349
- warningThresholdPercent: parsePositiveNumber(
350
- options.warningThresholdPercent,
351
- "warning-threshold-percent"
352
- ),
353
- },
354
- registrySource: registry.registrySource,
355
- registryFile: registry.registryFile,
356
- });
357
-
358
- const artifacts = await writeSwarmPlanArtifacts({
359
- plan,
360
- outputDir: options.outputDir,
361
- env: process.env,
362
- });
363
-
364
- const payload = {
365
- command: "swarm plan",
366
- targetPath: plan.targetPath,
367
- runId: plan.runId,
368
- scenario: plan.scenario,
369
- objective: plan.objective,
370
- maxParallel: plan.maxParallel,
371
- registrySource: plan.registrySource,
372
- registryFile: plan.registryFile,
373
- selectedAgents: plan.selectedAgents,
374
- globalBudget: plan.globalBudget,
375
- summary: plan.summary,
376
- runDirectory: artifacts.runDirectory,
377
- planJsonPath: artifacts.planJsonPath,
378
- planMarkdownPath: artifacts.planMarkdownPath,
379
- };
380
-
381
- if (emitJson) {
382
- console.log(JSON.stringify(payload, null, 2));
383
- return;
384
- }
385
-
386
- printSwarmSummary(payload);
387
- });
388
-
389
- swarm
390
- .command("dashboard")
391
- .description("Show or watch runtime swarm dashboard snapshots from artifact streams")
392
- .option("--path <path>", "Target workspace path", ".")
393
- .option("--run-id <id>", "Runtime run id (defaults to latest swarm-runtime run)")
394
- .option("--output-dir <path>", "Optional artifact output root override")
395
- .option("--watch", "Stream dashboard snapshots until completion/idle timeout")
396
- .option("--poll-seconds <n>", "Polling interval for --watch", "2")
397
- .option("--max-idle-seconds <n>", "Idle timeout for --watch", "20")
398
- .option("--json", "Emit machine-readable output")
399
- .action(async (options, command) => {
400
- const emitJson = shouldEmitJson(options, command);
401
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
402
-
403
- if (!options.watch) {
404
- const snapshot = await loadSwarmDashboardSnapshot({
405
- targetPath,
406
- outputDir: options.outputDir,
407
- runId: options.runId,
408
- env: process.env,
409
- });
410
- const payload = {
411
- command: "swarm dashboard",
412
- mode: "snapshot",
413
- ...snapshot,
414
- };
415
- if (emitJson) {
416
- console.log(JSON.stringify(payload, null, 2));
417
- return;
418
- }
419
- console.log(pc.bold("Swarm dashboard snapshot"));
420
- console.log(renderSwarmDashboard(snapshot));
421
- return;
422
- }
423
-
424
- const streamedSnapshots = [];
425
- const watchResult = await watchSwarmDashboard({
426
- targetPath,
427
- outputDir: options.outputDir,
428
- runId: options.runId,
429
- pollSeconds: parsePollSeconds(options.pollSeconds, "poll-seconds"),
430
- maxIdleSeconds: parsePollSeconds(options.maxIdleSeconds, "max-idle-seconds"),
431
- env: process.env,
432
- onSnapshot: async (snapshot) => {
433
- streamedSnapshots.push(snapshot);
434
- if (!emitJson) {
435
- console.log("");
436
- console.log(pc.bold(`Swarm dashboard update @ ${snapshot.generatedAt}`));
437
- console.log(renderSwarmDashboard(snapshot));
438
- }
439
- },
440
- });
441
-
442
- const payload = {
443
- command: "swarm dashboard",
444
- mode: "watch",
445
- snapshotCount: streamedSnapshots.length,
446
- stopReason: watchResult.stopReason,
447
- finalSnapshot: watchResult.finalSnapshot,
448
- };
449
-
450
- if (emitJson) {
451
- console.log(JSON.stringify(payload, null, 2));
452
- return;
453
- }
454
-
455
- console.log("");
456
- console.log(pc.bold("Swarm dashboard watch complete"));
457
- console.log(pc.gray(`Snapshots: ${payload.snapshotCount}`));
458
- console.log(pc.gray(`Stop reason: ${payload.stopReason}`));
459
- });
460
-
461
- swarm
462
- .command("report")
463
- .description("Build deterministic swarm execution report bundle from runtime artifacts")
464
- .option("--path <path>", "Target workspace path", ".")
465
- .option("--run-id <id>", "Runtime run id (defaults to latest swarm-runtime run)")
466
- .option("--plan-file <path>", "Optional explicit SWARM_PLAN.json path")
467
- .option("--output-dir <path>", "Optional artifact output root override")
468
- .option("--json", "Emit machine-readable output")
469
- .action(async (options, command) => {
470
- const emitJson = shouldEmitJson(options, command);
471
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
472
- const report = await buildSwarmExecutionReport({
473
- targetPath,
474
- outputDir: options.outputDir,
475
- runId: options.runId,
476
- planFile: options.planFile,
477
- env: process.env,
478
- });
479
- const payload = {
480
- command: "swarm report",
481
- runtimeRunId: report.runtimeRunId,
482
- planRunId: report.planRunId,
483
- scenario: report.scenario,
484
- completed: report.completed,
485
- stop: report.stop,
486
- usage: report.usage,
487
- eventCount: report.eventCount,
488
- agentSummary: report.agentSummary,
489
- reportJsonPath: report.reportJsonPath,
490
- reportMarkdownPath: report.reportMarkdownPath,
491
- runtimeJsonPath: report.runtimeJsonPath,
492
- runtimeEventsPath: report.runtimeEventsPath,
493
- planJsonPath: report.planJsonPath,
494
- };
495
-
496
- if (emitJson) {
497
- console.log(JSON.stringify(payload, null, 2));
498
- return;
499
- }
500
-
501
- console.log(pc.bold("Swarm execution report generated"));
502
- console.log(pc.gray(`Runtime run: ${payload.runtimeRunId}`));
503
- console.log(pc.gray(`Report JSON: ${payload.reportJsonPath}`));
504
- console.log(pc.gray(`Report Markdown: ${payload.reportMarkdownPath}`));
505
- console.log(
506
- `Usage: output_tokens=${payload.usage.outputTokens || 0} tool_calls=${payload.usage.toolCalls || 0} duration_ms=${payload.usage.durationMs || 0} cost_usd=${payload.usage.costUsd || 0}`
507
- );
508
- });
509
-
510
- swarm
511
- .command("run")
512
- .description("Execute a governed swarm runtime loop (mock by default, optional Playwright adapter)")
513
- .argument("[targetPath]", "Target workspace path", ".")
514
- .option("--path <path>", "Target workspace path override")
515
- .option("--plan-file <path>", "Existing `SWARM_PLAN.json` to execute")
516
- .option("--playbook-file <path>", "Optional Playwright playbook JSON ({ actions: [...] })")
517
- .option("--scenario-file <path>", "Scenario DSL file (.sls) for runtime actions")
518
- .option("--registry-file <path>", "Optional custom swarm registry file (when building plan inline)")
519
- .option("--agents <ids>", "Comma-separated agent ids for inline plan mode", "security,testing,reliability")
520
- .option("--scenario <id>", "Scenario identifier for inline plan mode", "qa_audit")
521
- .option(
522
- "--objective <text>",
523
- "Execution objective for inline plan mode",
524
- "Run OMAR-governed runtime loop with deterministic artifact lineage."
525
- )
526
- .option("--max-parallel <n>", "Max specialist parallelism for inline plan mode", "3")
527
- .option("--max-steps <n>", "Maximum runtime steps before forced stop", "20")
528
- .option("--engine <mode>", "Runtime engine mode (`mock` or `playwright`)", "mock")
529
- .option("--start-url <url>", "Initial URL for Playwright mode", "about:blank")
530
- .option("--execute", "Enable live execution (default is dry-run simulation)")
531
- .option("--max-cost-usd <n>", "Global max cost budget for inline plan mode", "5")
532
- .option("--max-output-tokens <n>", "Global max output-token budget for inline plan mode", "20000")
533
- .option("--max-runtime-ms <n>", "Global max runtime budget for inline plan mode", "3600000")
534
- .option("--max-tool-calls <n>", "Global max tool-call budget for inline plan mode", "500")
535
- .option("--warning-threshold-percent <n>", "Budget warning threshold percent", "80")
536
- .option("--output-dir <path>", "Optional artifact output root override")
537
- .option("--json", "Emit machine-readable output")
538
- .action(async (targetPathArg, options, command) => {
539
- const emitJson = shouldEmitJson(options, command);
540
- const explicitTargetPath = normalizeString(options.path || targetPathArg);
541
- if (normalizeString(options.playbookFile) && normalizeString(options.scenarioFile)) {
542
- throw new Error("Use either --playbook-file or --scenario-file, not both.");
543
- }
544
-
545
- let playbookActions = await loadSwarmPlaybook(options.playbookFile);
546
- let scenarioSource = "flags";
547
- let scenarioIdOverride = "";
548
- let startUrlOverride = "";
549
- if (normalizeString(options.scenarioFile)) {
550
- const parsedScenario = await parseScenarioFile(options.scenarioFile);
551
- const validation = validateScenarioSpec(parsedScenario.spec);
552
- if (!validation.valid) {
553
- throw new Error(`Scenario DSL invalid: ${validation.errors.join("; ")}`);
554
- }
555
- playbookActions = parsedScenario.spec.actions;
556
- scenarioSource = "scenario_dsl";
557
- scenarioIdOverride = normalizeString(parsedScenario.spec.id);
558
- startUrlOverride = normalizeString(parsedScenario.spec.startUrl);
559
- }
560
-
561
- let plan;
562
- let inlinePlanArtifacts = null;
563
- let targetPath = path.resolve(process.cwd(), explicitTargetPath || ".");
564
-
565
- if (normalizeString(options.planFile)) {
566
- plan = await loadSwarmPlanFile(options.planFile);
567
- if (!explicitTargetPath) {
568
- targetPath = path.resolve(String(plan.targetPath || "."));
569
- }
570
- } else {
571
- const registry = await loadSwarmRegistry({
572
- registryFile: options.registryFile,
573
- });
574
- const selected = selectSwarmAgents(registry.agents, options.agents);
575
- if (selected.missing.length > 0) {
576
- throw new Error(`Unknown agent id(s): ${selected.missing.join(", ")}`);
577
- }
578
- if (selected.selected.length === 0) {
579
- throw new Error("No agents selected for swarm runtime.");
580
- }
581
- const selectedAgents = ensureOmarIncluded(registry.agents, selected.selected);
582
- plan = buildSwarmExecutionPlan({
583
- targetPath,
584
- scenario: scenarioIdOverride || options.scenario,
585
- objective: options.objective,
586
- agents: selectedAgents,
587
- maxParallel: parseMaxParallel(options.maxParallel),
588
- globalBudget: {
589
- maxCostUsd: parsePositiveNumber(options.maxCostUsd, "max-cost-usd"),
590
- maxOutputTokens: parsePositiveNumber(options.maxOutputTokens, "max-output-tokens"),
591
- maxRuntimeMs: parsePositiveNumber(options.maxRuntimeMs, "max-runtime-ms"),
592
- maxToolCalls: parsePositiveNumber(options.maxToolCalls, "max-tool-calls"),
593
- warningThresholdPercent: parsePositiveNumber(
594
- options.warningThresholdPercent,
595
- "warning-threshold-percent"
596
- ),
597
- },
598
- registrySource: registry.registrySource,
599
- registryFile: registry.registryFile,
600
- });
601
- inlinePlanArtifacts = await writeSwarmPlanArtifacts({
602
- plan,
603
- outputDir: options.outputDir,
604
- env: process.env,
605
- });
606
- }
607
-
608
- const runtime = await runSwarmRuntime({
609
- plan,
610
- targetPath,
611
- engine: options.engine,
612
- execute: Boolean(options.execute),
613
- maxSteps: parseMaxSteps(options.maxSteps),
614
- startUrl: startUrlOverride || options.startUrl,
615
- playbookActions,
616
- outputDir: options.outputDir,
617
- env: process.env,
618
- });
619
-
620
- const payload = {
621
- command: "swarm run",
622
- targetPath: runtime.targetPath,
623
- runtimeRunId: runtime.runId,
624
- planRunId: runtime.planRunId,
625
- scenario: runtime.scenario,
626
- scenarioSource,
627
- scenarioFile: normalizeString(options.scenarioFile),
628
- engine: runtime.engine,
629
- execute: runtime.execute,
630
- completed: runtime.completed,
631
- stop: runtime.stop,
632
- usage: runtime.usage,
633
- eventCount: runtime.eventCount,
634
- runtimeDirectory: runtime.runtimeDirectory,
635
- runtimeJsonPath: runtime.runtimeJsonPath,
636
- runtimeMarkdownPath: runtime.runtimeMarkdownPath,
637
- runtimeEventsPath: runtime.runtimeEventsPath,
638
- inlinePlanPath: inlinePlanArtifacts?.planJsonPath || "",
639
- };
640
-
641
- if (emitJson) {
642
- console.log(JSON.stringify(payload, null, 2));
643
- } else {
644
- printRuntimeSummary(payload);
645
- }
646
-
647
- if (!runtime.completed) {
648
- process.exitCode = 2;
649
- }
650
- });
651
- }
1
+ import path from "node:path";
2
+ import process from "node:process";
3
+
4
+ import pc from "picocolors";
5
+
6
+ import { buildSwarmExecutionPlan, writeSwarmPlanArtifacts } from "../swarm/factory.js";
7
+ import { loadSwarmRegistry, selectSwarmAgents } from "../swarm/registry.js";
8
+ import { loadSwarmPlanFile, loadSwarmPlaybook, runSwarmRuntime } from "../swarm/runtime.js";
9
+ import {
10
+ loadSwarmDashboardSnapshot,
11
+ renderSwarmDashboard,
12
+ watchSwarmDashboard,
13
+ } from "../swarm/dashboard.js";
14
+ import { buildSwarmExecutionReport } from "../swarm/report.js";
15
+ import {
16
+ parseScenarioFile,
17
+ renderScenarioTemplate,
18
+ validateScenarioSpec,
19
+ writeScenarioTemplate,
20
+ } from "../swarm/scenario-dsl.js";
21
+ import { listBuiltinPentestScenarios, runSwarmPentest } from "../swarm/pentest.js";
22
+
23
+ function shouldEmitJson(options, command) {
24
+ const local = Boolean(options && options.json);
25
+ const globalFromCommand =
26
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
27
+ return local || globalFromCommand;
28
+ }
29
+
30
+ function parseMaxParallel(rawValue) {
31
+ const normalized = Number(rawValue || 0);
32
+ if (!Number.isFinite(normalized) || normalized < 1) {
33
+ throw new Error("max-parallel must be an integer >= 1.");
34
+ }
35
+ return Math.floor(normalized);
36
+ }
37
+
38
+ function parseMaxSteps(rawValue) {
39
+ const normalized = Number(rawValue || 0);
40
+ if (!Number.isFinite(normalized) || normalized < 1) {
41
+ throw new Error("max-steps must be an integer >= 1.");
42
+ }
43
+ return Math.floor(normalized);
44
+ }
45
+
46
+ function parsePollSeconds(rawValue, fieldName) {
47
+ const normalized = Number(rawValue || 0);
48
+ if (!Number.isFinite(normalized) || normalized <= 0) {
49
+ throw new Error(`${fieldName} must be a positive number.`);
50
+ }
51
+ return normalized;
52
+ }
53
+
54
+ function parsePositiveNumber(rawValue, fieldName) {
55
+ const normalized = Number(rawValue || 0);
56
+ if (!Number.isFinite(normalized) || normalized <= 0) {
57
+ throw new Error(`${fieldName} must be a positive number.`);
58
+ }
59
+ return normalized;
60
+ }
61
+
62
+ function normalizeString(value) {
63
+ return String(value || "").trim();
64
+ }
65
+
66
+ function ensureOmarIncluded(registryAgents = [], selectedAgents = []) {
67
+ const omarAgent = registryAgents.find((agent) => agent.id === "omar");
68
+ if (!omarAgent) {
69
+ throw new Error("Swarm registry must include 'omar' orchestrator.");
70
+ }
71
+ if (selectedAgents.some((agent) => agent.id === "omar")) {
72
+ return [...selectedAgents];
73
+ }
74
+ return [omarAgent, ...selectedAgents];
75
+ }
76
+
77
+ function printSwarmSummary(payload = {}) {
78
+ console.log(pc.bold("Swarm plan generated"));
79
+ console.log(pc.gray(`Run: ${payload.runId}`));
80
+ console.log(pc.gray(`Plan JSON: ${payload.planJsonPath}`));
81
+ console.log(pc.gray(`Plan Markdown: ${payload.planMarkdownPath}`));
82
+ console.log(`Scenario: ${payload.scenario}`);
83
+ console.log(`Agents: ${payload.selectedAgents.join(", ")}`);
84
+ console.log(
85
+ `Budgets: cost<=${payload.globalBudget.maxCostUsd} tokens<=${payload.globalBudget.maxOutputTokens} runtime_ms<=${payload.globalBudget.maxRuntimeMs} tools<=${payload.globalBudget.maxToolCalls}`
86
+ );
87
+ }
88
+
89
+ function printRuntimeSummary(payload = {}) {
90
+ console.log(pc.bold("Swarm runtime complete"));
91
+ console.log(pc.gray(`Runtime run: ${payload.runtimeRunId}`));
92
+ console.log(pc.gray(`Plan run: ${payload.planRunId}`));
93
+ console.log(pc.gray(`Runtime JSON: ${payload.runtimeJsonPath}`));
94
+ console.log(pc.gray(`Runtime events: ${payload.runtimeEventsPath}`));
95
+ console.log(`Status: ${payload.completed ? "completed" : `stopped (${payload.stop.stopClass})`}`);
96
+ console.log(
97
+ `Usage: output_tokens=${payload.usage.outputTokens} tool_calls=${payload.usage.toolCalls} duration_ms=${payload.usage.durationMs} cost_usd=${payload.usage.costUsd}`
98
+ );
99
+ }
100
+
101
+ function printPentestSummary(payload = {}) {
102
+ console.log(pc.bold("Swarm pen-test complete"));
103
+ console.log(pc.gray(`Run: ${payload.runId}`));
104
+ console.log(pc.gray(`Report JSON: ${payload.reportJsonPath}`));
105
+ console.log(pc.gray(`Report Markdown: ${payload.reportMarkdownPath}`));
106
+ console.log(pc.gray(`Audit log: ${payload.auditLogPath}`));
107
+ console.log(`Target: ${payload.target.url} (${payload.target.targetId})`);
108
+ console.log(`Scenario: ${payload.scenarioId}`);
109
+ console.log(
110
+ `Findings: P0=${payload.summary.P0} P1=${payload.summary.P1} P2=${payload.summary.P2} P3=${payload.summary.P3}`
111
+ );
112
+ }
113
+
114
+ export function registerSwarmCommand(program) {
115
+ const swarm = program
116
+ .command("swarm")
117
+ .description("Plan OMAR-governed swarm execution with deterministic assignments and budgets");
118
+
119
+ swarm
120
+ .command("registry")
121
+ .description("List swarm agent registry records")
122
+ .option("--registry-file <path>", "Optional custom swarm registry file")
123
+ .option("--json", "Emit machine-readable output")
124
+ .action(async (options, command) => {
125
+ const emitJson = shouldEmitJson(options, command);
126
+ const registry = await loadSwarmRegistry({
127
+ registryFile: options.registryFile,
128
+ });
129
+ const payload = {
130
+ command: "swarm registry",
131
+ registrySource: registry.registrySource,
132
+ registryFile: registry.registryFile,
133
+ agentCount: registry.agents.length,
134
+ agents: registry.agents,
135
+ };
136
+
137
+ if (emitJson) {
138
+ console.log(JSON.stringify(payload, null, 2));
139
+ return;
140
+ }
141
+
142
+ console.log(pc.bold("Swarm registry"));
143
+ console.log(pc.gray(`Source: ${registry.registrySource}`));
144
+ for (const agent of registry.agents) {
145
+ console.log(`- ${agent.id} (${agent.persona}) :: ${agent.domain} [${agent.role}]`);
146
+ }
147
+ });
148
+
149
+ swarm
150
+ .command("create")
151
+ .description("Create a governed swarm run (Phase 12.6 pen-test mode)")
152
+ .option("--path <path>", "Target workspace path", ".")
153
+ .option("--output-dir <path>", "Optional artifact output root override")
154
+ .option("--scenario <id>", "Scenario identifier (`pen-test` or built-in pen-test scenario)", "pen-test")
155
+ .option(
156
+ "--pen-test-scenario <id>",
157
+ "Built-in pen-test scenario when --scenario pen-test",
158
+ "auth-bypass"
159
+ )
160
+ .option("--target <url>", "Target URL to test")
161
+ .option("--target-id <id>", "Approved AIdenID target id")
162
+ .option("--execute", "Execute live HTTP probes (default is dry-run logging)")
163
+ .option("--json", "Emit machine-readable output")
164
+ .action(async (options, command) => {
165
+ const emitJson = shouldEmitJson(options, command);
166
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
167
+ if (!normalizeString(options.target)) {
168
+ throw new Error("--target is required.");
169
+ }
170
+ if (!normalizeString(options.targetId)) {
171
+ throw new Error("--target-id is required.");
172
+ }
173
+
174
+ const report = await runSwarmPentest({
175
+ targetPath,
176
+ outputDir: options.outputDir,
177
+ targetId: options.targetId,
178
+ targetUrl: options.target,
179
+ scenario: options.scenario,
180
+ pentestScenario: options.penTestScenario,
181
+ execute: Boolean(options.execute),
182
+ env: process.env,
183
+ });
184
+
185
+ const payload = {
186
+ command: "swarm create",
187
+ mode: "pen-test",
188
+ runId: report.runId,
189
+ scenario: report.scenario,
190
+ scenarioId: report.scenarioId,
191
+ execute: report.execute,
192
+ target: report.target,
193
+ summary: report.summary,
194
+ auditChain: report.auditChain,
195
+ checkCount: report.checkCount,
196
+ requestCount: report.requestCount,
197
+ reportJsonPath: report.reportJsonPath,
198
+ reportMarkdownPath: report.reportMarkdownPath,
199
+ auditLogPath: report.auditLogPath,
200
+ identityIsolationPath: report.identityIsolationPath,
201
+ cleanupContractPath: report.cleanupContractPath,
202
+ requestPlanPath: report.requestPlanPath,
203
+ supportedPentestScenarios: listBuiltinPentestScenarios().map((item) => item.id),
204
+ };
205
+
206
+ if (emitJson) {
207
+ console.log(JSON.stringify(payload, null, 2));
208
+ } else {
209
+ printPentestSummary(payload);
210
+ }
211
+
212
+ if (report.summary.blocking) {
213
+ process.exitCode = 2;
214
+ }
215
+ });
216
+
217
+ const scenario = swarm
218
+ .command("scenario")
219
+ .description("Create and validate swarm scenario DSL files");
220
+
221
+ scenario
222
+ .command("init")
223
+ .description("Write scenario DSL template")
224
+ .argument("<scenarioId>", "Scenario identifier")
225
+ .option("--path <path>", "Target workspace path", ".")
226
+ .option("--output <path>", "Output file path (default: .sentinelayer/scenarios/<scenarioId>.sls)")
227
+ .option("--start-url <url>", "Default start URL for template", "https://example.com")
228
+ .option("--json", "Emit machine-readable output")
229
+ .action(async (scenarioId, options, command) => {
230
+ const emitJson = shouldEmitJson(options, command);
231
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
232
+ const result = await writeScenarioTemplate({
233
+ scenarioId,
234
+ targetPath,
235
+ outputFile: options.output,
236
+ startUrl: options.startUrl,
237
+ });
238
+ const payload = {
239
+ command: "swarm scenario init",
240
+ scenarioId,
241
+ filePath: result.filePath,
242
+ template: renderScenarioTemplate({
243
+ scenarioId,
244
+ startUrl: options.startUrl,
245
+ }),
246
+ };
247
+
248
+ if (emitJson) {
249
+ console.log(JSON.stringify(payload, null, 2));
250
+ return;
251
+ }
252
+
253
+ console.log(pc.bold("Swarm scenario template generated"));
254
+ console.log(pc.gray(`Scenario: ${scenarioId}`));
255
+ console.log(pc.gray(`File: ${result.filePath}`));
256
+ });
257
+
258
+ scenario
259
+ .command("validate")
260
+ .description("Validate scenario DSL file")
261
+ .option("--file <path>", "Scenario DSL file path")
262
+ .option("--json", "Emit machine-readable output")
263
+ .action(async (options, command) => {
264
+ const emitJson = shouldEmitJson(options, command);
265
+ if (!normalizeString(options.file)) {
266
+ throw new Error("--file is required.");
267
+ }
268
+ const parsed = await parseScenarioFile(options.file);
269
+ const validation = validateScenarioSpec(parsed.spec);
270
+ const payload = {
271
+ command: "swarm scenario validate",
272
+ filePath: parsed.filePath,
273
+ scenarioId: parsed.spec.id,
274
+ startUrl: parsed.spec.startUrl,
275
+ actionCount: parsed.spec.actions.length,
276
+ valid: validation.valid,
277
+ errors: validation.errors,
278
+ };
279
+
280
+ if (emitJson) {
281
+ console.log(JSON.stringify(payload, null, 2));
282
+ if (!validation.valid) {
283
+ process.exitCode = 2;
284
+ }
285
+ return;
286
+ }
287
+
288
+ if (validation.valid) {
289
+ console.log(pc.green("Scenario DSL valid"));
290
+ } else {
291
+ console.log(pc.red("Scenario DSL invalid"));
292
+ for (const error of validation.errors) {
293
+ console.log(`- ${error}`);
294
+ }
295
+ process.exitCode = 2;
296
+ }
297
+ console.log(pc.gray(`File: ${parsed.filePath}`));
298
+ });
299
+
300
+ swarm
301
+ .command("plan")
302
+ .description("Build deterministic swarm execution plan + artifacts")
303
+ .argument("[targetPath]", "Target workspace path", ".")
304
+ .option("--path <path>", "Target workspace path override")
305
+ .option("--registry-file <path>", "Optional custom swarm registry file")
306
+ .option("--agents <ids>", "Comma-separated agent ids (default: full registry)", "")
307
+ .option("--scenario <id>", "Scenario identifier", "qa_audit")
308
+ .option(
309
+ "--objective <text>",
310
+ "Execution objective",
311
+ "Run OMAR-governed quality/security swarm analysis with deterministic handoffs."
312
+ )
313
+ .option("--max-parallel <n>", "Maximum specialist agents processed in parallel", "4")
314
+ .option("--max-cost-usd <n>", "Global max cost budget", "5")
315
+ .option("--max-output-tokens <n>", "Global max output-token budget", "20000")
316
+ .option("--max-runtime-ms <n>", "Global max runtime budget (ms)", "3600000")
317
+ .option("--max-tool-calls <n>", "Global max tool-call budget", "500")
318
+ .option("--warning-threshold-percent <n>", "Budget warning threshold percent", "80")
319
+ .option("--output-dir <path>", "Optional artifact output root override")
320
+ .option("--json", "Emit machine-readable output")
321
+ .action(async (targetPathArg, options, command) => {
322
+ const emitJson = shouldEmitJson(options, command);
323
+ const targetPath = path.resolve(process.cwd(), String(options.path || targetPathArg || "."));
324
+
325
+ const registry = await loadSwarmRegistry({
326
+ registryFile: options.registryFile,
327
+ });
328
+ const selected = selectSwarmAgents(registry.agents, options.agents);
329
+ if (selected.missing.length > 0) {
330
+ throw new Error(`Unknown agent id(s): ${selected.missing.join(", ")}`);
331
+ }
332
+ if (selected.selected.length === 0) {
333
+ throw new Error("No agents selected for swarm plan.");
334
+ }
335
+
336
+ const selectedAgents = ensureOmarIncluded(registry.agents, selected.selected);
337
+
338
+ const plan = buildSwarmExecutionPlan({
339
+ targetPath,
340
+ scenario: options.scenario,
341
+ objective: options.objective,
342
+ agents: selectedAgents,
343
+ maxParallel: parseMaxParallel(options.maxParallel),
344
+ globalBudget: {
345
+ maxCostUsd: parsePositiveNumber(options.maxCostUsd, "max-cost-usd"),
346
+ maxOutputTokens: parsePositiveNumber(options.maxOutputTokens, "max-output-tokens"),
347
+ maxRuntimeMs: parsePositiveNumber(options.maxRuntimeMs, "max-runtime-ms"),
348
+ maxToolCalls: parsePositiveNumber(options.maxToolCalls, "max-tool-calls"),
349
+ warningThresholdPercent: parsePositiveNumber(
350
+ options.warningThresholdPercent,
351
+ "warning-threshold-percent"
352
+ ),
353
+ },
354
+ registrySource: registry.registrySource,
355
+ registryFile: registry.registryFile,
356
+ });
357
+
358
+ const artifacts = await writeSwarmPlanArtifacts({
359
+ plan,
360
+ outputDir: options.outputDir,
361
+ env: process.env,
362
+ });
363
+
364
+ const payload = {
365
+ command: "swarm plan",
366
+ targetPath: plan.targetPath,
367
+ runId: plan.runId,
368
+ scenario: plan.scenario,
369
+ objective: plan.objective,
370
+ maxParallel: plan.maxParallel,
371
+ registrySource: plan.registrySource,
372
+ registryFile: plan.registryFile,
373
+ selectedAgents: plan.selectedAgents,
374
+ globalBudget: plan.globalBudget,
375
+ summary: plan.summary,
376
+ runDirectory: artifacts.runDirectory,
377
+ planJsonPath: artifacts.planJsonPath,
378
+ planMarkdownPath: artifacts.planMarkdownPath,
379
+ };
380
+
381
+ if (emitJson) {
382
+ console.log(JSON.stringify(payload, null, 2));
383
+ return;
384
+ }
385
+
386
+ printSwarmSummary(payload);
387
+ });
388
+
389
+ swarm
390
+ .command("dashboard")
391
+ .description("Show or watch runtime swarm dashboard snapshots from artifact streams")
392
+ .option("--path <path>", "Target workspace path", ".")
393
+ .option("--run-id <id>", "Runtime run id (defaults to latest swarm-runtime run)")
394
+ .option("--output-dir <path>", "Optional artifact output root override")
395
+ .option("--watch", "Stream dashboard snapshots until completion/idle timeout")
396
+ .option("--poll-seconds <n>", "Polling interval for --watch", "2")
397
+ .option("--max-idle-seconds <n>", "Idle timeout for --watch", "20")
398
+ .option("--json", "Emit machine-readable output")
399
+ .action(async (options, command) => {
400
+ const emitJson = shouldEmitJson(options, command);
401
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
402
+
403
+ if (!options.watch) {
404
+ const snapshot = await loadSwarmDashboardSnapshot({
405
+ targetPath,
406
+ outputDir: options.outputDir,
407
+ runId: options.runId,
408
+ env: process.env,
409
+ });
410
+ const payload = {
411
+ command: "swarm dashboard",
412
+ mode: "snapshot",
413
+ ...snapshot,
414
+ };
415
+ if (emitJson) {
416
+ console.log(JSON.stringify(payload, null, 2));
417
+ return;
418
+ }
419
+ console.log(pc.bold("Swarm dashboard snapshot"));
420
+ console.log(renderSwarmDashboard(snapshot));
421
+ return;
422
+ }
423
+
424
+ const streamedSnapshots = [];
425
+ const watchResult = await watchSwarmDashboard({
426
+ targetPath,
427
+ outputDir: options.outputDir,
428
+ runId: options.runId,
429
+ pollSeconds: parsePollSeconds(options.pollSeconds, "poll-seconds"),
430
+ maxIdleSeconds: parsePollSeconds(options.maxIdleSeconds, "max-idle-seconds"),
431
+ env: process.env,
432
+ onSnapshot: async (snapshot) => {
433
+ streamedSnapshots.push(snapshot);
434
+ if (!emitJson) {
435
+ console.log("");
436
+ console.log(pc.bold(`Swarm dashboard update @ ${snapshot.generatedAt}`));
437
+ console.log(renderSwarmDashboard(snapshot));
438
+ }
439
+ },
440
+ });
441
+
442
+ const payload = {
443
+ command: "swarm dashboard",
444
+ mode: "watch",
445
+ snapshotCount: streamedSnapshots.length,
446
+ stopReason: watchResult.stopReason,
447
+ finalSnapshot: watchResult.finalSnapshot,
448
+ };
449
+
450
+ if (emitJson) {
451
+ console.log(JSON.stringify(payload, null, 2));
452
+ return;
453
+ }
454
+
455
+ console.log("");
456
+ console.log(pc.bold("Swarm dashboard watch complete"));
457
+ console.log(pc.gray(`Snapshots: ${payload.snapshotCount}`));
458
+ console.log(pc.gray(`Stop reason: ${payload.stopReason}`));
459
+ });
460
+
461
+ swarm
462
+ .command("report")
463
+ .description("Build deterministic swarm execution report bundle from runtime artifacts")
464
+ .option("--path <path>", "Target workspace path", ".")
465
+ .option("--run-id <id>", "Runtime run id (defaults to latest swarm-runtime run)")
466
+ .option("--plan-file <path>", "Optional explicit SWARM_PLAN.json path")
467
+ .option("--output-dir <path>", "Optional artifact output root override")
468
+ .option("--json", "Emit machine-readable output")
469
+ .action(async (options, command) => {
470
+ const emitJson = shouldEmitJson(options, command);
471
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
472
+ const report = await buildSwarmExecutionReport({
473
+ targetPath,
474
+ outputDir: options.outputDir,
475
+ runId: options.runId,
476
+ planFile: options.planFile,
477
+ env: process.env,
478
+ });
479
+ const payload = {
480
+ command: "swarm report",
481
+ runtimeRunId: report.runtimeRunId,
482
+ planRunId: report.planRunId,
483
+ scenario: report.scenario,
484
+ completed: report.completed,
485
+ stop: report.stop,
486
+ usage: report.usage,
487
+ eventCount: report.eventCount,
488
+ agentSummary: report.agentSummary,
489
+ reportJsonPath: report.reportJsonPath,
490
+ reportMarkdownPath: report.reportMarkdownPath,
491
+ runtimeJsonPath: report.runtimeJsonPath,
492
+ runtimeEventsPath: report.runtimeEventsPath,
493
+ planJsonPath: report.planJsonPath,
494
+ };
495
+
496
+ if (emitJson) {
497
+ console.log(JSON.stringify(payload, null, 2));
498
+ return;
499
+ }
500
+
501
+ console.log(pc.bold("Swarm execution report generated"));
502
+ console.log(pc.gray(`Runtime run: ${payload.runtimeRunId}`));
503
+ console.log(pc.gray(`Report JSON: ${payload.reportJsonPath}`));
504
+ console.log(pc.gray(`Report Markdown: ${payload.reportMarkdownPath}`));
505
+ console.log(
506
+ `Usage: output_tokens=${payload.usage.outputTokens || 0} tool_calls=${payload.usage.toolCalls || 0} duration_ms=${payload.usage.durationMs || 0} cost_usd=${payload.usage.costUsd || 0}`
507
+ );
508
+ });
509
+
510
+ swarm
511
+ .command("run")
512
+ .description("Execute a governed swarm runtime loop (mock by default, optional Playwright adapter)")
513
+ .argument("[targetPath]", "Target workspace path", ".")
514
+ .option("--path <path>", "Target workspace path override")
515
+ .option("--plan-file <path>", "Existing `SWARM_PLAN.json` to execute")
516
+ .option("--playbook-file <path>", "Optional Playwright playbook JSON ({ actions: [...] })")
517
+ .option("--scenario-file <path>", "Scenario DSL file (.sls) for runtime actions")
518
+ .option("--registry-file <path>", "Optional custom swarm registry file (when building plan inline)")
519
+ .option("--agents <ids>", "Comma-separated agent ids for inline plan mode", "security,testing,reliability")
520
+ .option("--scenario <id>", "Scenario identifier for inline plan mode", "qa_audit")
521
+ .option(
522
+ "--objective <text>",
523
+ "Execution objective for inline plan mode",
524
+ "Run OMAR-governed runtime loop with deterministic artifact lineage."
525
+ )
526
+ .option("--max-parallel <n>", "Max specialist parallelism for inline plan mode", "3")
527
+ .option("--max-steps <n>", "Maximum runtime steps before forced stop", "20")
528
+ .option("--engine <mode>", "Runtime engine mode (`mock` or `playwright`)", "mock")
529
+ .option("--start-url <url>", "Initial URL for Playwright mode", "about:blank")
530
+ .option("--execute", "Enable live execution (default is dry-run simulation)")
531
+ .option("--max-cost-usd <n>", "Global max cost budget for inline plan mode", "5")
532
+ .option("--max-output-tokens <n>", "Global max output-token budget for inline plan mode", "20000")
533
+ .option("--max-runtime-ms <n>", "Global max runtime budget for inline plan mode", "3600000")
534
+ .option("--max-tool-calls <n>", "Global max tool-call budget for inline plan mode", "500")
535
+ .option("--warning-threshold-percent <n>", "Budget warning threshold percent", "80")
536
+ .option("--output-dir <path>", "Optional artifact output root override")
537
+ .option("--json", "Emit machine-readable output")
538
+ .action(async (targetPathArg, options, command) => {
539
+ const emitJson = shouldEmitJson(options, command);
540
+ const explicitTargetPath = normalizeString(options.path || targetPathArg);
541
+ if (normalizeString(options.playbookFile) && normalizeString(options.scenarioFile)) {
542
+ throw new Error("Use either --playbook-file or --scenario-file, not both.");
543
+ }
544
+
545
+ let playbookActions = await loadSwarmPlaybook(options.playbookFile);
546
+ let scenarioSource = "flags";
547
+ let scenarioIdOverride = "";
548
+ let startUrlOverride = "";
549
+ if (normalizeString(options.scenarioFile)) {
550
+ const parsedScenario = await parseScenarioFile(options.scenarioFile);
551
+ const validation = validateScenarioSpec(parsedScenario.spec);
552
+ if (!validation.valid) {
553
+ throw new Error(`Scenario DSL invalid: ${validation.errors.join("; ")}`);
554
+ }
555
+ playbookActions = parsedScenario.spec.actions;
556
+ scenarioSource = "scenario_dsl";
557
+ scenarioIdOverride = normalizeString(parsedScenario.spec.id);
558
+ startUrlOverride = normalizeString(parsedScenario.spec.startUrl);
559
+ }
560
+
561
+ let plan;
562
+ let inlinePlanArtifacts = null;
563
+ let targetPath = path.resolve(process.cwd(), explicitTargetPath || ".");
564
+
565
+ if (normalizeString(options.planFile)) {
566
+ plan = await loadSwarmPlanFile(options.planFile);
567
+ if (!explicitTargetPath) {
568
+ targetPath = path.resolve(String(plan.targetPath || "."));
569
+ }
570
+ } else {
571
+ const registry = await loadSwarmRegistry({
572
+ registryFile: options.registryFile,
573
+ });
574
+ const selected = selectSwarmAgents(registry.agents, options.agents);
575
+ if (selected.missing.length > 0) {
576
+ throw new Error(`Unknown agent id(s): ${selected.missing.join(", ")}`);
577
+ }
578
+ if (selected.selected.length === 0) {
579
+ throw new Error("No agents selected for swarm runtime.");
580
+ }
581
+ const selectedAgents = ensureOmarIncluded(registry.agents, selected.selected);
582
+ plan = buildSwarmExecutionPlan({
583
+ targetPath,
584
+ scenario: scenarioIdOverride || options.scenario,
585
+ objective: options.objective,
586
+ agents: selectedAgents,
587
+ maxParallel: parseMaxParallel(options.maxParallel),
588
+ globalBudget: {
589
+ maxCostUsd: parsePositiveNumber(options.maxCostUsd, "max-cost-usd"),
590
+ maxOutputTokens: parsePositiveNumber(options.maxOutputTokens, "max-output-tokens"),
591
+ maxRuntimeMs: parsePositiveNumber(options.maxRuntimeMs, "max-runtime-ms"),
592
+ maxToolCalls: parsePositiveNumber(options.maxToolCalls, "max-tool-calls"),
593
+ warningThresholdPercent: parsePositiveNumber(
594
+ options.warningThresholdPercent,
595
+ "warning-threshold-percent"
596
+ ),
597
+ },
598
+ registrySource: registry.registrySource,
599
+ registryFile: registry.registryFile,
600
+ });
601
+ inlinePlanArtifacts = await writeSwarmPlanArtifacts({
602
+ plan,
603
+ outputDir: options.outputDir,
604
+ env: process.env,
605
+ });
606
+ }
607
+
608
+ const runtime = await runSwarmRuntime({
609
+ plan,
610
+ targetPath,
611
+ engine: options.engine,
612
+ execute: Boolean(options.execute),
613
+ maxSteps: parseMaxSteps(options.maxSteps),
614
+ startUrl: startUrlOverride || options.startUrl,
615
+ playbookActions,
616
+ outputDir: options.outputDir,
617
+ env: process.env,
618
+ });
619
+
620
+ const payload = {
621
+ command: "swarm run",
622
+ targetPath: runtime.targetPath,
623
+ runtimeRunId: runtime.runId,
624
+ planRunId: runtime.planRunId,
625
+ scenario: runtime.scenario,
626
+ scenarioSource,
627
+ scenarioFile: normalizeString(options.scenarioFile),
628
+ engine: runtime.engine,
629
+ execute: runtime.execute,
630
+ completed: runtime.completed,
631
+ stop: runtime.stop,
632
+ usage: runtime.usage,
633
+ eventCount: runtime.eventCount,
634
+ runtimeDirectory: runtime.runtimeDirectory,
635
+ runtimeJsonPath: runtime.runtimeJsonPath,
636
+ runtimeMarkdownPath: runtime.runtimeMarkdownPath,
637
+ runtimeEventsPath: runtime.runtimeEventsPath,
638
+ inlinePlanPath: inlinePlanArtifacts?.planJsonPath || "",
639
+ };
640
+
641
+ if (emitJson) {
642
+ console.log(JSON.stringify(payload, null, 2));
643
+ } else {
644
+ printRuntimeSummary(payload);
645
+ }
646
+
647
+ if (!runtime.completed) {
648
+ process.exitCode = 2;
649
+ }
650
+ });
651
+ }