sentinelayer-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "sentinelayer-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Scaffold Sentinelayer spec/prompt/guide artifacts with secure browser auth and token bootstrap.",
5
5
  "type": "module",
6
6
  "scripts": {
7
- "check": "node --check bin/sentinelayer-cli.js && node --check bin/create-sentinelayer.js && node --check bin/sl.js && node --check src/cli.js && node --check src/legacy-cli.js && node --check src/commands/config.js && node --check src/commands/ingest.js && node --check src/commands/spec.js && node --check src/commands/prompt.js && node --check src/commands/scan.js && node --check src/commands/guide.js && node --check src/commands/cost.js && node --check src/commands/telemetry.js && node --check src/commands/auth.js && node --check src/commands/watch.js && node --check src/commands/mcp.js && node --check src/commands/plugin.js && node --check src/commands/ai.js && node --check src/commands/review.js && node --check src/commands/chat.js && node --check src/commands/policy.js && node --check src/commands/swarm.js && node --check src/commands/daemon.js && node --check src/commands/audit.js && node --check src/config/service.js && node --check src/ingest/engine.js && node --check src/spec/generator.js && node --check src/spec/regenerate.js && node --check src/spec/templates.js && node --check src/prompt/generator.js && node --check src/scan/generator.js && node --check src/guide/generator.js && node --check src/cost/tracker.js && node --check src/cost/history.js && node --check src/cost/budget.js && node --check src/ai/client.js && node --check src/ai/aidenid.js && node --check src/ai/identity-store.js && node --check src/ai/domain-target-store.js && node --check src/ai/site-store.js && node --check src/review/local-review.js && node --check src/review/ai-review.js && node --check src/review/report.js && node --check src/review/replay.js && node --check src/audit/registry.js && node --check src/audit/orchestrator.js && node --check src/audit/package.js && node --check src/audit/replay.js && node --check src/audit/agents/security.js && node --check src/audit/agents/architecture.js && node --check src/audit/agents/testing.js && node --check src/audit/agents/performance.js && node --check src/audit/agents/compliance.js && node --check src/audit/agents/documentation.js && node --check src/swarm/registry.js && node --check src/swarm/factory.js && node --check src/swarm/runtime.js && node --check src/swarm/scenario-dsl.js && node --check src/swarm/dashboard.js && node --check src/swarm/report.js && node --check src/swarm/pentest.js && node --check src/daemon/error-worker.js && node --check src/daemon/assignment-ledger.js && node --check src/daemon/jira-lifecycle.js && node --check src/daemon/budget-governor.js && node --check src/daemon/operator-control.js && node --check src/daemon/artifact-lineage.js && node --check src/daemon/ast-parser-layer.js && node --check src/daemon/callgraph-overlay.js && node --check src/daemon/hybrid-mapper.js && node --check src/daemon/reliability-lane.js && node --check src/daemon/watchdog.js && node --check src/telemetry/ledger.js && node --check src/auth/http.js && node --check src/auth/session-store.js && node --check src/auth/service.js && node --check src/mcp/registry.js && node --check src/memory/blackboard.js && node --check src/memory/retrieval.js && node --check src/plugin/manifest.js && node --check src/policy/packs.js && node --check src/ui/markdown.js && node --check src/ui/progress.js && node --check src/agents/jules/tools/file-read.js && node --check src/agents/jules/tools/grep.js && node --check src/agents/jules/tools/glob.js && node --check src/agents/jules/tools/shell.js && node --check src/agents/jules/tools/file-edit.js && node --check src/agents/jules/tools/dispatch.js && node --check src/agents/jules/tools/index.js && node --check src/agents/jules/tools/frontend-analyze.js && node --check src/agents/jules/swarm/sub-agent.js && node --check src/agents/jules/swarm/file-scanner.js && node --check src/agents/jules/swarm/pattern-hunter.js && node --check src/agents/jules/swarm/index.js && node --check src/agents/jules/swarm/orchestrator.js && node --check src/agents/jules/config/definition.js && node --check src/agents/jules/loop.js && node --check src/agents/jules/stream.js && node --check src/agents/jules/fix-cycle.js && node --check src/agents/jules/error-intake.js && node --check src/agents/jules/tools/runtime-audit.js && node --check src/agents/jules/config/system-prompt.js && node --check src/agents/jules/tools/auth-audit.js",
7
+ "check": "node --check bin/sentinelayer-cli.js && node --check bin/create-sentinelayer.js && node --check bin/sl.js && node --check src/cli.js && node --check src/legacy-cli.js && node --check src/commands/config.js && node --check src/commands/ingest.js && node --check src/commands/spec.js && node --check src/commands/prompt.js && node --check src/commands/scan.js && node --check src/commands/guide.js && node --check src/commands/cost.js && node --check src/commands/telemetry.js && node --check src/commands/auth.js && node --check src/commands/watch.js && node --check src/commands/mcp.js && node --check src/commands/plugin.js && node --check src/commands/ai.js && node --check src/commands/review.js && node --check src/commands/chat.js && node --check src/commands/policy.js && node --check src/commands/swarm.js && node --check src/commands/daemon.js && node --check src/commands/audit.js && node --check src/config/service.js && node --check src/ingest/engine.js && node --check src/spec/generator.js && node --check src/spec/regenerate.js && node --check src/spec/templates.js && node --check src/prompt/generator.js && node --check src/scan/generator.js && node --check src/guide/generator.js && node --check src/cost/tracker.js && node --check src/cost/history.js && node --check src/cost/budget.js && node --check src/ai/client.js && node --check src/ai/aidenid.js && node --check src/ai/identity-store.js && node --check src/ai/domain-target-store.js && node --check src/ai/site-store.js && node --check src/review/local-review.js && node --check src/review/ai-review.js && node --check src/review/report.js && node --check src/review/replay.js && node --check src/audit/registry.js && node --check src/audit/orchestrator.js && node --check src/audit/package.js && node --check src/audit/replay.js && node --check src/audit/agents/security.js && node --check src/audit/agents/architecture.js && node --check src/audit/agents/testing.js && node --check src/audit/agents/performance.js && node --check src/audit/agents/compliance.js && node --check src/audit/agents/documentation.js && node --check src/swarm/registry.js && node --check src/swarm/factory.js && node --check src/swarm/runtime.js && node --check src/swarm/scenario-dsl.js && node --check src/swarm/dashboard.js && node --check src/swarm/report.js && node --check src/swarm/pentest.js && node --check src/daemon/error-worker.js && node --check src/daemon/assignment-ledger.js && node --check src/daemon/jira-lifecycle.js && node --check src/daemon/budget-governor.js && node --check src/daemon/operator-control.js && node --check src/daemon/artifact-lineage.js && node --check src/daemon/ast-parser-layer.js && node --check src/daemon/callgraph-overlay.js && node --check src/daemon/hybrid-mapper.js && node --check src/daemon/reliability-lane.js && node --check src/daemon/watchdog.js && node --check src/telemetry/ledger.js && node --check src/auth/http.js && node --check src/auth/session-store.js && node --check src/auth/service.js && node --check src/mcp/registry.js && node --check src/memory/blackboard.js && node --check src/memory/retrieval.js && node --check src/plugin/manifest.js && node --check src/policy/packs.js && node --check src/ui/markdown.js && node --check src/ui/progress.js && node --check src/agents/jules/tools/file-read.js && node --check src/agents/jules/tools/grep.js && node --check src/agents/jules/tools/glob.js && node --check src/agents/jules/tools/shell.js && node --check src/agents/jules/tools/file-edit.js && node --check src/agents/jules/tools/dispatch.js && node --check src/agents/jules/tools/index.js && node --check src/agents/jules/tools/frontend-analyze.js && node --check src/agents/jules/swarm/sub-agent.js && node --check src/agents/jules/swarm/file-scanner.js && node --check src/agents/jules/swarm/pattern-hunter.js && node --check src/agents/jules/swarm/index.js && node --check src/agents/jules/swarm/orchestrator.js && node --check src/agents/jules/config/definition.js && node --check src/agents/jules/loop.js && node --check src/agents/jules/stream.js && node --check src/agents/jules/fix-cycle.js && node --check src/agents/jules/error-intake.js && node --check src/agents/jules/tools/runtime-audit.js && node --check src/agents/jules/config/system-prompt.js && node --check src/agents/jules/tools/auth-audit.js && node --check src/auth/gate.js && node --check src/telemetry/sync.js && node --check src/telemetry/session-tracker.js && node --check src/interactive/workspace.js && node --check src/interactive/auto-ingest.js && node --check src/interactive/action-menu.js && node --check src/interactive/index.js && node --check src/daemon/ingest-refresh.js",
8
8
  "test": "npm run test:unit && npm run test:e2e",
9
9
  "test:unit": "node --test tests/unit*.test.mjs",
10
10
  "test:e2e": "node --test tests/e2e.test.mjs",
@@ -18,7 +18,7 @@ const LIGHTHOUSE_TIMEOUT_MS = 120000;
18
18
  * @param {{ operation: string, url?: string, path?: string }} input
19
19
  * @returns {object} Structured result per operation
20
20
  */
21
- export function runtimeAudit(input) {
21
+ export async function runtimeAudit(input) {
22
22
  if (!RUNTIME_OPS.has(input.operation)) {
23
23
  throw new RuntimeAuditError(
24
24
  "Unknown operation: " + input.operation + ". Valid: " + [...RUNTIME_OPS].join(", "),
@@ -49,7 +49,7 @@ const RUNTIME_DISPATCH = {
49
49
  * Run Lighthouse via npx (no install required).
50
50
  * Returns performance, accessibility, best-practices, SEO scores + key metrics.
51
51
  */
52
- function lighthouseScan(input) {
52
+ async function lighthouseScan(input) {
53
53
  const url = input.url;
54
54
  if (!url) {
55
55
  throw new RuntimeAuditError("lighthouse_scan requires a url parameter");
@@ -58,6 +58,13 @@ function lighthouseScan(input) {
58
58
  throw new RuntimeAuditError("Invalid URL: " + url);
59
59
  }
60
60
 
61
+ // Prefer SentinelLayer API scanner (authenticated, server-side Lighthouse).
62
+ // Falls back to local npx lighthouse if API unavailable.
63
+ try {
64
+ const apiResult = await callScannerApi(url);
65
+ if (apiResult.available) return apiResult;
66
+ } catch { /* API unavailable — fall back to local */ }
67
+
61
68
  try {
62
69
  const outputPath = path.join(
63
70
  input.path || process.cwd(),
@@ -76,6 +83,7 @@ function lighthouseScan(input) {
76
83
  encoding: "utf-8",
77
84
  timeout: LIGHTHOUSE_TIMEOUT_MS,
78
85
  stdio: ["pipe", "pipe", "pipe"],
86
+ shell: true, // Windows: npx is npx.cmd, needs shell resolution
79
87
  });
80
88
 
81
89
  if (!fs.existsSync(outputPath)) {
@@ -401,6 +409,82 @@ function sanitizeUrlForShell(url) {
401
409
  }
402
410
  }
403
411
 
412
+ /**
413
+ * Call the SentinelLayer API scanner endpoint for server-side Lighthouse.
414
+ * Requires authenticated session (token from sl auth login).
415
+ * Returns structured result or throws if unavailable.
416
+ */
417
+ async function callScannerApi(url) {
418
+ let session;
419
+ try {
420
+ const { readStoredSession } = await import("../../../auth/session-store.js");
421
+ session = await readStoredSession();
422
+ } catch { /* session read failed */ }
423
+
424
+ if (!session || !session.token) {
425
+ return { available: false, reason: "Not authenticated — run sl auth login" };
426
+ }
427
+
428
+ const apiUrl = session.apiUrl || "https://api.sentinelayer.com";
429
+ const scanEndpoint = apiUrl + "/api/v1/scan/url";
430
+
431
+ // Submit scan
432
+ const submitResponse = await fetch(scanEndpoint, {
433
+ method: "POST",
434
+ headers: {
435
+ "Content-Type": "application/json",
436
+ "Authorization": "Bearer " + session.token,
437
+ },
438
+ body: JSON.stringify({ url, scan_type: "lighthouse" }),
439
+ signal: AbortSignal.timeout(15000),
440
+ });
441
+
442
+ if (!submitResponse.ok) {
443
+ return { available: false, reason: "Scanner API returned " + submitResponse.status };
444
+ }
445
+
446
+ const submitData = await submitResponse.json();
447
+ const scanId = submitData.scan_id || submitData.id;
448
+ if (!scanId) {
449
+ return { available: false, reason: "Scanner did not return scan_id" };
450
+ }
451
+
452
+ // Poll for completion (max 90s)
453
+ const pollUrl = apiUrl + "/api/v1/scan/url/" + scanId;
454
+ for (let attempt = 0; attempt < 30; attempt++) {
455
+ await new Promise(r => setTimeout(r, 3000));
456
+ try {
457
+ const pollResponse = await fetch(pollUrl, {
458
+ headers: { "Authorization": "Bearer " + session.token },
459
+ signal: AbortSignal.timeout(10000),
460
+ });
461
+ if (!pollResponse.ok) continue;
462
+ const pollData = await pollResponse.json();
463
+ if (pollData.status === "completed" || pollData.status === "complete") {
464
+ const scores = pollData.scores || pollData.lighthouse_scores || {};
465
+ return {
466
+ available: true,
467
+ source: "sentinelayer-api",
468
+ scanId,
469
+ reportPath: null,
470
+ scores: {
471
+ performance: scores.performance ?? null,
472
+ accessibility: scores.accessibility ?? null,
473
+ bestPractices: scores.best_practices ?? scores.bestPractices ?? null,
474
+ seo: scores.seo ?? null,
475
+ },
476
+ metrics: pollData.metrics || {},
477
+ opportunities: pollData.opportunities || [],
478
+ };
479
+ }
480
+ if (pollData.status === "failed" || pollData.status === "error") {
481
+ return { available: false, reason: "Scanner reported failure: " + (pollData.error || pollData.status) };
482
+ }
483
+ } catch { /* poll failed, retry */ }
484
+ }
485
+ return { available: false, reason: "Scanner timed out after 90s" };
486
+ }
487
+
404
488
  export class RuntimeAuditError extends Error {
405
489
  constructor(message) {
406
490
  super(message);
@@ -0,0 +1,92 @@
1
+ import process from "node:process";
2
+ import pc from "picocolors";
3
+ import { readStoredSession } from "./session-store.js";
4
+
5
+ /**
6
+ * Auth gate — ensures user is logged in before running any command.
7
+ *
8
+ * Commands that bypass auth:
9
+ * - auth login, auth status, auth --help
10
+ * - --help, --version, -h, -v
11
+ * - config (read-only config inspection)
12
+ *
13
+ * All other commands require a valid session.
14
+ * If not authenticated, prints instructions and exits.
15
+ */
16
+
17
+ const AUTH_BYPASS_COMMANDS = new Set([
18
+ "auth", // auth subcommands handle their own auth
19
+ "--help",
20
+ "-h",
21
+ "--version",
22
+ "-v",
23
+ ]);
24
+
25
+ // Commands that work without auth (read-only, no API calls)
26
+ const NO_AUTH_REQUIRED = new Set([
27
+ "config", // local config inspection
28
+ ]);
29
+
30
+ /**
31
+ * Check if the current command requires authentication.
32
+ * Returns true if auth is required but user is not logged in.
33
+ *
34
+ * @param {string[]} args - CLI arguments (after normalization)
35
+ * @returns {Promise<{ authenticated: boolean, session: object|null, bypassReason: string|null }>}
36
+ */
37
+ export async function checkAuthGate(args) {
38
+ const first = String(args[0] || "").trim().toLowerCase();
39
+
40
+ // Bypass commands
41
+ if (!first || AUTH_BYPASS_COMMANDS.has(first)) {
42
+ return { authenticated: true, session: null, bypassReason: "auth_bypass_command" };
43
+ }
44
+
45
+ if (NO_AUTH_REQUIRED.has(first)) {
46
+ return { authenticated: true, session: null, bypassReason: "no_auth_required" };
47
+ }
48
+
49
+ // CI/test bypass — allows automated testing without auth
50
+ if (process.env.SENTINELAYER_CLI_SKIP_AUTH === "1" || process.env.CI === "true") {
51
+ return { authenticated: true, session: null, bypassReason: "env_bypass" };
52
+ }
53
+
54
+ // Check for stored session
55
+ try {
56
+ const session = await readStoredSession();
57
+ if (session && session.token) {
58
+ // Check if token is expired
59
+ if (session.tokenExpiresAt) {
60
+ const expiresAt = new Date(session.tokenExpiresAt).getTime();
61
+ if (expiresAt < Date.now()) {
62
+ return { authenticated: false, session: null, bypassReason: null };
63
+ }
64
+ }
65
+ return { authenticated: true, session, bypassReason: null };
66
+ }
67
+ } catch {
68
+ // Session read failed — treat as not authenticated
69
+ }
70
+
71
+ return { authenticated: false, session: null, bypassReason: null };
72
+ }
73
+
74
+ /**
75
+ * Print auth required message and exit.
76
+ */
77
+ export function printAuthRequired() {
78
+ console.error("");
79
+ console.error(pc.bold(pc.red("Authentication required.")));
80
+ console.error("");
81
+ console.error(" Log in to SentinelLayer to use CLI commands:");
82
+ console.error("");
83
+ console.error(" " + pc.cyan("sl auth login"));
84
+ console.error("");
85
+ console.error(" This opens your browser to authenticate via GitHub or Google.");
86
+ console.error(" Your session is encrypted and stored locally.");
87
+ console.error("");
88
+ console.error(" " + pc.gray("Why? All CLI operations sync to your SentinelLayer account —"));
89
+ console.error(" " + pc.gray("audit reports, findings, cost tracking, and run history."));
90
+ console.error("");
91
+ process.exitCode = 1;
92
+ }
package/src/cli.js CHANGED
@@ -230,6 +230,14 @@ export async function runCli(rawArgs = process.argv.slice(2)) {
230
230
  // Normalize slash commands (/omargate → omargate, /audit → audit, etc.)
231
231
  const normalizedArgs = normalizeSlashArgs(rawArgs);
232
232
 
233
+ // Auth gate — require login for all commands except auth/help/version/config
234
+ const { checkAuthGate, printAuthRequired } = await import("./auth/gate.js");
235
+ const authResult = await checkAuthGate(normalizedArgs);
236
+ if (!authResult.authenticated) {
237
+ printAuthRequired();
238
+ return;
239
+ }
240
+
233
241
  if (shouldBypassCommander(normalizedArgs)) {
234
242
  await runLegacyCliWithErrorHandling(normalizedArgs);
235
243
  return;
@@ -1009,6 +1009,25 @@ export function registerAuditCommand(program, invokeLegacy) {
1009
1009
  process.stderr.write("Summary: " + allFindings.length + " findings (P0=" + severityCounts.P0 + " P1=" + severityCounts.P1 + " P2=" + severityCounts.P2 + ")\n");
1010
1010
  }
1011
1011
 
1012
+ // Sync run to dashboard (fire-and-forget)
1013
+ try {
1014
+ const { syncRunToDashboard } = await import("../telemetry/sync.js");
1015
+ const syncResult = await syncRunToDashboard({
1016
+ command: "audit frontend",
1017
+ persona: JULES_DEFINITION.persona,
1018
+ mode: options.mode,
1019
+ framework: ingest?.frameworks?.[0] || "unknown",
1020
+ summary: { total: allFindings.length, ...severityCounts, blocking: severityCounts.P0 > 0 || severityCounts.P1 > 0 },
1021
+ usage: report?.usage || {},
1022
+ stopReason: report?.usage?.stopReason || "completed",
1023
+ reconciliation: reconciliation.summary,
1024
+ runtime: runtimeResult ? { ran: true, url: runtimeResult.url } : { ran: false },
1025
+ });
1026
+ if (!emitJson && !emitStream && syncResult.synced) {
1027
+ process.stderr.write(JULES_DEFINITION.avatar + " Run synced to dashboard" + (syncResult.runId ? " (run:" + syncResult.runId + ")" : "") + "\n");
1028
+ }
1029
+ } catch { /* sync failure never blocks CLI */ }
1030
+
1012
1031
  if (severityCounts.P0 > 0 || severityCounts.P1 > 0) {
1013
1032
  process.exitCode = 2;
1014
1033
  }
@@ -0,0 +1,195 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { collectCodebaseIngest, generateCodebaseIngest } from "../ingest/engine.js";
4
+
5
+ /**
6
+ * Pulse Ingest Refresh — periodic codebase re-index.
7
+ *
8
+ * Detects when the file count changes vs the last ingest.
9
+ * If delta detected: re-runs ingest + AST + domain assignment.
10
+ * Budget-gated: aborts if refresh takes > maxDurationMs.
11
+ *
12
+ * Inspired by src/utils/cronScheduler.ts file watcher pattern.
13
+ */
14
+
15
+ const DEFAULT_CHECK_INTERVAL_MS = 60_000; // 1 minute
16
+ const DEFAULT_MAX_DURATION_MS = 30_000; // 30 seconds
17
+ const STALE_FILE_COUNT_THRESHOLD = 5; // re-ingest if >= 5 files changed
18
+
19
+ /**
20
+ * Check if the codebase has changed since last ingest.
21
+ *
22
+ * @param {string} targetPath - Repository root
23
+ * @returns {{ changed: boolean, currentFileCount: number, lastFileCount: number, delta: number }}
24
+ */
25
+ export function detectIngestDrift(targetPath) {
26
+ const ingestPath = path.join(targetPath, ".sentinelayer", "CODEBASE_INGEST.json");
27
+
28
+ let lastFileCount = 0;
29
+ try {
30
+ const ingest = JSON.parse(fs.readFileSync(ingestPath, "utf-8"));
31
+ lastFileCount = ingest?.summary?.filesScanned || 0;
32
+ } catch {
33
+ return { changed: true, currentFileCount: 0, lastFileCount: 0, delta: 0 };
34
+ }
35
+
36
+ // Quick file count via directory scan (fast, no deep analysis)
37
+ let currentFileCount = 0;
38
+ try {
39
+ currentFileCount = countFilesQuick(targetPath);
40
+ } catch {
41
+ return { changed: false, currentFileCount: 0, lastFileCount, delta: 0 };
42
+ }
43
+
44
+ const delta = Math.abs(currentFileCount - lastFileCount);
45
+ return {
46
+ changed: delta >= STALE_FILE_COUNT_THRESHOLD,
47
+ currentFileCount,
48
+ lastFileCount,
49
+ delta,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Run a budget-gated ingest refresh.
55
+ * Aborts if refresh takes longer than maxDurationMs.
56
+ *
57
+ * @param {string} targetPath
58
+ * @param {object} [options]
59
+ * @param {number} [options.maxDurationMs] - Max refresh time (default 30s)
60
+ * @param {function} [options.onEvent] - Event callback
61
+ * @returns {Promise<{ refreshed: boolean, reason: string, durationMs: number }>}
62
+ */
63
+ export async function refreshIngestIfNeeded(targetPath, options = {}) {
64
+ const maxDurationMs = options.maxDurationMs || DEFAULT_MAX_DURATION_MS;
65
+ const drift = detectIngestDrift(targetPath);
66
+
67
+ if (!drift.changed) {
68
+ return { refreshed: false, reason: "no_drift", durationMs: 0, ...drift };
69
+ }
70
+
71
+ if (options.onEvent) {
72
+ options.onEvent({
73
+ stream: "sl_event",
74
+ event: "ingest_refresh_start",
75
+ payload: { delta: drift.delta, currentFiles: drift.currentFileCount, lastFiles: drift.lastFileCount },
76
+ });
77
+ }
78
+
79
+ const startMs = Date.now();
80
+
81
+ // Budget gate: abort if taking too long
82
+ const timeout = setTimeout(() => {
83
+ if (options.onEvent) {
84
+ options.onEvent({
85
+ stream: "sl_event",
86
+ event: "ingest_refresh_timeout",
87
+ payload: { maxDurationMs, elapsed: Date.now() - startMs },
88
+ });
89
+ }
90
+ }, maxDurationMs);
91
+
92
+ try {
93
+ let ingest;
94
+ try {
95
+ ingest = await generateCodebaseIngest({
96
+ rootPath: targetPath,
97
+ outputDir: path.join(targetPath, ".sentinelayer"),
98
+ refresh: true,
99
+ });
100
+ } catch {
101
+ ingest = await collectCodebaseIngest({ rootPath: targetPath });
102
+ }
103
+
104
+ const durationMs = Date.now() - startMs;
105
+
106
+ if (options.onEvent) {
107
+ options.onEvent({
108
+ stream: "sl_event",
109
+ event: "ingest_refresh_complete",
110
+ payload: {
111
+ durationMs,
112
+ filesScanned: ingest?.summary?.filesScanned || 0,
113
+ delta: drift.delta,
114
+ },
115
+ });
116
+ }
117
+
118
+ return {
119
+ refreshed: true,
120
+ reason: "drift_detected",
121
+ durationMs,
122
+ filesScanned: ingest?.summary?.filesScanned || 0,
123
+ ...drift,
124
+ };
125
+ } catch (err) {
126
+ return {
127
+ refreshed: false,
128
+ reason: "refresh_failed: " + err.message,
129
+ durationMs: Date.now() - startMs,
130
+ ...drift,
131
+ };
132
+ } finally {
133
+ clearTimeout(timeout);
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Start a periodic ingest refresh watcher.
139
+ * Checks for drift every checkIntervalMs and refreshes if needed.
140
+ *
141
+ * @param {string} targetPath
142
+ * @param {object} [options]
143
+ * @param {number} [options.checkIntervalMs] - Check interval (default 60s)
144
+ * @param {number} [options.maxDurationMs] - Max refresh time (default 30s)
145
+ * @param {function} [options.onEvent] - Event callback
146
+ * @returns {{ stop: function }} - Call stop() to stop watching
147
+ */
148
+ export function startPeriodicRefresh(targetPath, options = {}) {
149
+ const checkIntervalMs = options.checkIntervalMs || DEFAULT_CHECK_INTERVAL_MS;
150
+ let running = true;
151
+
152
+ const check = async () => {
153
+ if (!running) return;
154
+ await refreshIngestIfNeeded(targetPath, options);
155
+ if (running) {
156
+ setTimeout(check, checkIntervalMs);
157
+ }
158
+ };
159
+
160
+ // Start first check after one interval
161
+ const timer = setTimeout(check, checkIntervalMs);
162
+
163
+ return {
164
+ stop() {
165
+ running = false;
166
+ clearTimeout(timer);
167
+ },
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Quick file count — counts source files without deep analysis.
173
+ * Much faster than full ingest for drift detection.
174
+ */
175
+ function countFilesQuick(rootPath) {
176
+ const IGNORE = new Set([
177
+ ".git", "node_modules", ".next", "dist", "build", "coverage",
178
+ ".turbo", ".venv", "__pycache__", ".cache", ".sentinelayer",
179
+ ]);
180
+ let count = 0;
181
+
182
+ function walk(dir) {
183
+ try {
184
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
185
+ for (const entry of entries) {
186
+ if (IGNORE.has(entry.name)) continue;
187
+ if (entry.isDirectory()) walk(path.join(dir, entry.name));
188
+ else if (entry.isFile()) count++;
189
+ }
190
+ } catch { /* skip unreadable */ }
191
+ }
192
+
193
+ walk(rootPath);
194
+ return count;
195
+ }
@@ -0,0 +1,132 @@
1
+ import prompts from "prompts";
2
+ import pc from "picocolors";
3
+
4
+ import { PERSONA_VISUALS, listPersonaIds } from "../agents/jules/config/definition.js";
5
+
6
+ /**
7
+ * Interactive action menu — presented after ingest completes.
8
+ * Arrow-key navigation for primary actions + submenus.
9
+ */
10
+
11
+ /**
12
+ * Present the main action menu.
13
+ *
14
+ * @returns {Promise<{ action: string, subAction?: string, input?: string }>}
15
+ */
16
+ export async function showActionMenu() {
17
+ const response = await prompts({
18
+ type: "select",
19
+ name: "action",
20
+ message: "What would you like to do?",
21
+ choices: [
22
+ { title: pc.red("🔍 Audit"), value: "audit", description: "Run security + quality audit (baseline + personas)" },
23
+ { title: pc.yellow("📝 Review"), value: "review", description: "Quick review of current changes" },
24
+ { title: pc.green("🏗️ Add Feature"), value: "feature", description: "Describe a feature and generate spec + prompt" },
25
+ { title: pc.blue("🆕 Create Project"), value: "create", description: "Scaffold a new project with spec + Omar Gate" },
26
+ { title: pc.gray("⚙️ More options..."), value: "more", description: "Config, cost, telemetry, watch, plugins" },
27
+ ],
28
+ });
29
+
30
+ if (!response.action) return { action: "exit" };
31
+
32
+ // Route to submenu
33
+ if (response.action === "audit") return showAuditMenu();
34
+ if (response.action === "review") return showReviewMenu();
35
+ if (response.action === "feature") return showFeaturePrompt();
36
+ if (response.action === "more") return showMoreMenu();
37
+
38
+ return { action: response.action };
39
+ }
40
+
41
+ /**
42
+ * Audit submenu — all 13 personas + full audit.
43
+ */
44
+ async function showAuditMenu() {
45
+ const personaIds = listPersonaIds();
46
+ const choices = [
47
+ {
48
+ title: pc.bold("🎯 Full Audit (all 13 personas in parallel)"),
49
+ value: { action: "audit", subAction: "deep" },
50
+ description: "Omar baseline → 13 specialist agents → reconciliation",
51
+ },
52
+ ];
53
+
54
+ for (const id of personaIds) {
55
+ const visual = PERSONA_VISUALS[id];
56
+ if (!visual) continue;
57
+ choices.push({
58
+ title: (visual.avatar || "") + " " + visual.fullName + pc.gray(" (" + id + ")"),
59
+ value: { action: "audit", subAction: id },
60
+ description: visual.specialty ? visual.specialty.slice(0, 80) : visual.domain || id,
61
+ });
62
+ }
63
+
64
+ const response = await prompts({
65
+ type: "select",
66
+ name: "choice",
67
+ message: "Which audit?",
68
+ choices,
69
+ });
70
+
71
+ return response.choice || { action: "exit" };
72
+ }
73
+
74
+ /**
75
+ * Review submenu.
76
+ */
77
+ async function showReviewMenu() {
78
+ const response = await prompts({
79
+ type: "select",
80
+ name: "choice",
81
+ message: "Review mode?",
82
+ choices: [
83
+ { title: "📋 Full review", value: { action: "review", subAction: "full" }, description: "Scan entire codebase (22-rule deterministic + AI)" },
84
+ { title: "📝 Diff review", value: { action: "review", subAction: "diff" }, description: "Review only uncommitted changes" },
85
+ { title: "📌 Staged review", value: { action: "review", subAction: "staged" }, description: "Review only staged files" },
86
+ ],
87
+ });
88
+
89
+ return response.choice || { action: "exit" };
90
+ }
91
+
92
+ /**
93
+ * Feature description prompt.
94
+ */
95
+ async function showFeaturePrompt() {
96
+ const response = await prompts({
97
+ type: "text",
98
+ name: "description",
99
+ message: "Describe the feature you want to add:",
100
+ validate: v => (v && v.trim().length > 5) ? true : "Please describe the feature (at least a few words)",
101
+ });
102
+
103
+ if (!response.description) return { action: "exit" };
104
+
105
+ return {
106
+ action: "feature",
107
+ input: response.description.trim(),
108
+ };
109
+ }
110
+
111
+ /**
112
+ * More options submenu.
113
+ */
114
+ async function showMoreMenu() {
115
+ const response = await prompts({
116
+ type: "select",
117
+ name: "choice",
118
+ message: "More options:",
119
+ choices: [
120
+ { title: "📊 Cost & usage summary", value: { action: "cost" }, description: "View token usage and cost tracking" },
121
+ { title: "📈 Telemetry", value: { action: "telemetry" }, description: "View run event telemetry" },
122
+ { title: "⚙️ Config", value: { action: "config" }, description: "View and edit configuration" },
123
+ { title: "👤 Auth status", value: { action: "auth-status" }, description: "Check authentication" },
124
+ { title: "🔌 Plugins", value: { action: "plugins" }, description: "List installed plugins" },
125
+ { title: "📡 Watch events", value: { action: "watch" }, description: "Stream runtime events" },
126
+ { title: "🤖 AI identity", value: { action: "ai" }, description: "AIdenID provisioning" },
127
+ { title: "🐛 Daemon status", value: { action: "daemon" }, description: "Error queue and budget status" },
128
+ ],
129
+ });
130
+
131
+ return response.choice || { action: "exit" };
132
+ }
@@ -0,0 +1,111 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import pc from "picocolors";
4
+
5
+ import { collectCodebaseIngest, generateCodebaseIngest } from "../ingest/engine.js";
6
+
7
+ /**
8
+ * Auto-ingest with live progress output.
9
+ *
10
+ * Checks if CODEBASE_INGEST.json exists and is fresh.
11
+ * If stale or missing, runs ingest with real-time status updates.
12
+ * Returns the ingest result.
13
+ */
14
+
15
+ const STALE_THRESHOLD_MS = 300_000; // 5 minutes
16
+
17
+ /**
18
+ * Check if ingest exists and is fresh enough.
19
+ *
20
+ * @param {string} targetPath - Repository root
21
+ * @returns {{ exists: boolean, stale: boolean, age: number|null, path: string }}
22
+ */
23
+ export function checkIngestFreshness(targetPath) {
24
+ const ingestPath = path.join(targetPath, ".sentinelayer", "CODEBASE_INGEST.json");
25
+ if (!fs.existsSync(ingestPath)) {
26
+ return { exists: false, stale: true, age: null, path: ingestPath };
27
+ }
28
+
29
+ try {
30
+ const stat = fs.statSync(ingestPath);
31
+ const age = Date.now() - stat.mtimeMs;
32
+ return {
33
+ exists: true,
34
+ stale: age > STALE_THRESHOLD_MS,
35
+ age,
36
+ path: ingestPath,
37
+ };
38
+ } catch {
39
+ return { exists: false, stale: true, age: null, path: ingestPath };
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Run auto-ingest with live progress output to stderr.
45
+ * If ingest exists and is fresh, reads from cache.
46
+ * Otherwise runs full ingest with status updates.
47
+ *
48
+ * @param {string} targetPath
49
+ * @param {object} [options]
50
+ * @param {boolean} [options.force] - Force re-ingest even if fresh
51
+ * @param {boolean} [options.quiet] - Suppress progress output
52
+ * @returns {Promise<object>} Ingest result
53
+ */
54
+ export async function autoIngestWithProgress(targetPath, options = {}) {
55
+ const freshness = checkIngestFreshness(targetPath);
56
+
57
+ if (freshness.exists && !freshness.stale && !options.force) {
58
+ if (!options.quiet) {
59
+ const ageSec = Math.floor((freshness.age || 0) / 1000);
60
+ process.stderr.write(pc.gray("Using cached ingest (" + ageSec + "s old)\n"));
61
+ }
62
+ try {
63
+ const cached = JSON.parse(fs.readFileSync(freshness.path, "utf-8"));
64
+ return cached;
65
+ } catch { /* fall through to re-ingest */ }
66
+ }
67
+
68
+ // Run ingest with progress
69
+ if (!options.quiet) {
70
+ process.stderr.write(pc.cyan("⟳") + " Indexing codebase...\n");
71
+ }
72
+
73
+ const startMs = Date.now();
74
+
75
+ if (!options.quiet) {
76
+ process.stderr.write(pc.gray(" ├─ Scanning files and directories\n"));
77
+ }
78
+
79
+ let ingest;
80
+ try {
81
+ ingest = await generateCodebaseIngest({
82
+ rootPath: targetPath,
83
+ outputDir: path.join(targetPath, ".sentinelayer"),
84
+ refresh: true,
85
+ });
86
+ } catch {
87
+ ingest = await collectCodebaseIngest({ rootPath: targetPath });
88
+ }
89
+
90
+ const durationMs = Date.now() - startMs;
91
+
92
+ if (!options.quiet) {
93
+ const files = ingest?.summary?.filesScanned || 0;
94
+ const loc = ingest?.summary?.totalLoc || 0;
95
+ const surfaces = (ingest?.riskSurfaces || []).length;
96
+ const frameworks = (ingest?.frameworks || []).join(", ") || "none";
97
+
98
+ process.stderr.write(pc.gray(" ├─ Building AST + import graph\n"));
99
+ process.stderr.write(pc.gray(" ├─ Assigning domain surfaces\n"));
100
+ process.stderr.write(pc.gray(" └─ ") + pc.green("Done") + pc.gray(" (" + (durationMs / 1000).toFixed(1) + "s)\n"));
101
+ process.stderr.write("\n");
102
+ process.stderr.write(pc.bold(" Codebase Summary\n"));
103
+ process.stderr.write(pc.gray(" Files: ") + pc.white(String(files)) + "\n");
104
+ process.stderr.write(pc.gray(" LOC: ") + pc.white(String(loc)) + "\n");
105
+ process.stderr.write(pc.gray(" Frameworks: ") + pc.white(frameworks) + "\n");
106
+ process.stderr.write(pc.gray(" Risk surfaces: ") + pc.white(String(surfaces)) + "\n");
107
+ process.stderr.write("\n");
108
+ }
109
+
110
+ return ingest;
111
+ }
@@ -0,0 +1,95 @@
1
+ import pc from "picocolors";
2
+ import { selectRepo } from "./workspace.js";
3
+ import { autoIngestWithProgress } from "./auto-ingest.js";
4
+ import { showActionMenu } from "./action-menu.js";
5
+
6
+ /**
7
+ * Interactive CLI mode — the "sl" experience with no args.
8
+ *
9
+ * Flow:
10
+ * 1. Detect repos in workspace → select if multiple
11
+ * 2. Auto-ingest with live progress
12
+ * 3. Present action menu
13
+ * 4. Route to the selected command
14
+ */
15
+
16
+ /**
17
+ * Run the interactive flow.
18
+ *
19
+ * @param {object} [options]
20
+ * @param {function} [options.executeCommand] - Command executor (receives action + args)
21
+ * @returns {Promise<void>}
22
+ */
23
+ export async function runInteractiveMode(options = {}) {
24
+ console.error("");
25
+ console.error(pc.bold(" SentinelLayer CLI") + pc.gray(" — security-first development platform"));
26
+ console.error("");
27
+
28
+ // Step 1: Repo selection
29
+ const repo = await selectRepo();
30
+ if (!repo) {
31
+ console.error(pc.yellow("No repository selected. Run sl --help for available commands."));
32
+ return;
33
+ }
34
+
35
+ // Step 2: Auto-ingest
36
+ const ingest = await autoIngestWithProgress(repo.path);
37
+
38
+ // Step 3: Action menu
39
+ const choice = await showActionMenu();
40
+ if (choice.action === "exit") {
41
+ return;
42
+ }
43
+
44
+ // Step 4: Route to command
45
+ console.error("");
46
+ if (options.executeCommand) {
47
+ await options.executeCommand(choice, repo, ingest);
48
+ } else {
49
+ // Print the equivalent CLI command for the user
50
+ const cmd = buildEquivalentCommand(choice, repo);
51
+ if (cmd) {
52
+ console.error(pc.gray(" Equivalent command: ") + pc.cyan(cmd));
53
+ console.error("");
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Build the equivalent CLI command string for a menu choice.
60
+ */
61
+ function buildEquivalentCommand(choice, repo) {
62
+ const pathFlag = " --path " + repo.path;
63
+
64
+ switch (choice.action) {
65
+ case "audit":
66
+ if (choice.subAction === "deep") return "sl audit" + pathFlag + " --json";
67
+ return "sl audit " + choice.subAction + pathFlag + " --stream";
68
+ case "review":
69
+ if (choice.subAction === "diff") return "sl review scan --mode diff" + pathFlag + " --json";
70
+ if (choice.subAction === "staged") return "sl review scan --mode staged" + pathFlag + " --json";
71
+ return "sl review scan --mode full" + pathFlag + " --json";
72
+ case "feature":
73
+ return "sl spec generate --description \"" + (choice.input || "").slice(0, 50) + "...\"" + pathFlag;
74
+ case "create":
75
+ return "sl init";
76
+ case "cost":
77
+ return "sl cost show" + pathFlag + " --json";
78
+ case "telemetry":
79
+ return "sl telemetry show" + pathFlag + " --json";
80
+ case "config":
81
+ return "sl config list --json";
82
+ case "auth-status":
83
+ return "sl auth status --json";
84
+ case "plugins":
85
+ return "sl plugin list --json";
86
+ case "watch":
87
+ return "sl watch history" + pathFlag + " --json";
88
+ case "ai":
89
+ return "sl ai provision-email --json";
90
+ case "daemon":
91
+ return "sl daemon budget status" + pathFlag + " --json";
92
+ default:
93
+ return null;
94
+ }
95
+ }
@@ -0,0 +1,92 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import prompts from "prompts";
4
+ import pc from "picocolors";
5
+
6
+ /**
7
+ * Multi-repo workspace detection + interactive repo selection.
8
+ *
9
+ * Scans the current directory and parent for git repositories.
10
+ * If multiple found, presents arrow-key selector.
11
+ * If single found, auto-selects it.
12
+ */
13
+
14
+ /**
15
+ * Detect git repositories in the workspace.
16
+ * Scans cwd and one level up for directories containing .git.
17
+ *
18
+ * @param {string} [startPath] - Starting directory (default: cwd)
19
+ * @returns {{ repos: Array<{name, path, isCurrentDir}>, parentDir: string }}
20
+ */
21
+ export function detectRepos(startPath) {
22
+ const cwd = path.resolve(startPath || process.cwd());
23
+ const parentDir = path.dirname(cwd);
24
+ const repos = [];
25
+
26
+ // Check if cwd itself is a git repo
27
+ if (fs.existsSync(path.join(cwd, ".git"))) {
28
+ repos.push({
29
+ name: path.basename(cwd),
30
+ path: cwd,
31
+ isCurrentDir: true,
32
+ });
33
+ }
34
+
35
+ // Scan parent directory for sibling repos
36
+ try {
37
+ const siblings = fs.readdirSync(parentDir, { withFileTypes: true });
38
+ for (const entry of siblings) {
39
+ if (!entry.isDirectory()) continue;
40
+ const siblingPath = path.join(parentDir, entry.name);
41
+ if (siblingPath === cwd) continue; // skip self (already added if it's a repo)
42
+ if (fs.existsSync(path.join(siblingPath, ".git"))) {
43
+ repos.push({
44
+ name: entry.name,
45
+ path: siblingPath,
46
+ isCurrentDir: false,
47
+ });
48
+ }
49
+ }
50
+ } catch { /* parent unreadable — only current dir */ }
51
+
52
+ return { repos, parentDir };
53
+ }
54
+
55
+ /**
56
+ * Interactive repo selector.
57
+ * If single repo: auto-selects.
58
+ * If multiple: presents arrow-key menu.
59
+ * If none: returns null.
60
+ *
61
+ * @param {object} [options]
62
+ * @param {string} [options.startPath]
63
+ * @returns {Promise<{name, path}|null>}
64
+ */
65
+ export async function selectRepo(options = {}) {
66
+ const { repos } = detectRepos(options.startPath);
67
+
68
+ if (repos.length === 0) {
69
+ console.error(pc.yellow("No git repositories found in this workspace."));
70
+ return null;
71
+ }
72
+
73
+ if (repos.length === 1) {
74
+ console.error(pc.gray("Repository: " + repos[0].name + " (" + repos[0].path + ")"));
75
+ return repos[0];
76
+ }
77
+
78
+ // Multiple repos — present selection
79
+ console.error(pc.bold("Multiple repositories detected:"));
80
+ const response = await prompts({
81
+ type: "select",
82
+ name: "repo",
83
+ message: "Which repository?",
84
+ choices: repos.map(r => ({
85
+ title: r.name + (r.isCurrentDir ? pc.gray(" (current)") : ""),
86
+ value: r,
87
+ description: r.path,
88
+ })),
89
+ });
90
+
91
+ return response.repo || null;
92
+ }
@@ -0,0 +1,118 @@
1
+ import pc from "picocolors";
2
+
3
+ /**
4
+ * Session Tracker — tracks tokens, tool calls, cost, and time per CLI run.
5
+ *
6
+ * Inspired by src/bootstrap/state.ts and src/cost-tracker.ts patterns:
7
+ * - Single global session state initialized once
8
+ * - Accumulator functions for each metric
9
+ * - Summary getter for final report
10
+ * - Print summary on completion
11
+ */
12
+
13
+ let SESSION = null;
14
+
15
+ /**
16
+ * Initialize a new tracking session.
17
+ * Call this at the start of any auditable command.
18
+ */
19
+ export function startSession(command) {
20
+ SESSION = {
21
+ command: command || "unknown",
22
+ startedAt: Date.now(),
23
+ inputTokens: 0,
24
+ outputTokens: 0,
25
+ costUsd: 0,
26
+ toolCalls: 0,
27
+ llmCalls: 0,
28
+ findings: { P0: 0, P1: 0, P2: 0, P3: 0 },
29
+ };
30
+ return SESSION;
31
+ }
32
+
33
+ /**
34
+ * Record token usage from an LLM call.
35
+ */
36
+ export function recordLlmUsage({ inputTokens = 0, outputTokens = 0, costUsd = 0 } = {}) {
37
+ if (!SESSION) return;
38
+ SESSION.inputTokens += inputTokens;
39
+ SESSION.outputTokens += outputTokens;
40
+ SESSION.costUsd += costUsd;
41
+ SESSION.llmCalls += 1;
42
+ }
43
+
44
+ /**
45
+ * Record a tool call.
46
+ */
47
+ export function recordToolCall() {
48
+ if (!SESSION) return;
49
+ SESSION.toolCalls += 1;
50
+ }
51
+
52
+ /**
53
+ * Record findings.
54
+ */
55
+ export function recordFindings(summary) {
56
+ if (!SESSION) return;
57
+ if (summary?.P0) SESSION.findings.P0 += summary.P0;
58
+ if (summary?.P1) SESSION.findings.P1 += summary.P1;
59
+ if (summary?.P2) SESSION.findings.P2 += summary.P2;
60
+ if (summary?.P3) SESSION.findings.P3 += summary.P3;
61
+ }
62
+
63
+ /**
64
+ * Get the current session summary.
65
+ */
66
+ export function getSessionSummary() {
67
+ if (!SESSION) return null;
68
+ const durationMs = Date.now() - SESSION.startedAt;
69
+ return {
70
+ command: SESSION.command,
71
+ durationMs,
72
+ inputTokens: SESSION.inputTokens,
73
+ outputTokens: SESSION.outputTokens,
74
+ totalTokens: SESSION.inputTokens + SESSION.outputTokens,
75
+ costUsd: SESSION.costUsd,
76
+ toolCalls: SESSION.toolCalls,
77
+ llmCalls: SESSION.llmCalls,
78
+ findings: { ...SESSION.findings },
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Print the session summary to stderr.
84
+ * Called at the end of any auditable command.
85
+ */
86
+ export function printSessionSummary() {
87
+ const summary = getSessionSummary();
88
+ if (!summary) return;
89
+
90
+ const duration = summary.durationMs < 60000
91
+ ? (summary.durationMs / 1000).toFixed(1) + "s"
92
+ : (summary.durationMs / 60000).toFixed(1) + "m";
93
+
94
+ const tokens = summary.totalTokens > 1000
95
+ ? (summary.totalTokens / 1000).toFixed(1) + "K"
96
+ : String(summary.totalTokens);
97
+
98
+ const parts = [];
99
+ parts.push(pc.gray("Run complete:"));
100
+ parts.push(pc.white(tokens + " tokens"));
101
+ parts.push(pc.white(summary.toolCalls + " tools"));
102
+ if (summary.costUsd > 0) parts.push(pc.white("$" + summary.costUsd.toFixed(2)));
103
+ parts.push(pc.white(duration));
104
+
105
+ const findingParts = [];
106
+ if (summary.findings.P0 > 0) findingParts.push(pc.red("P0=" + summary.findings.P0));
107
+ if (summary.findings.P1 > 0) findingParts.push(pc.yellow("P1=" + summary.findings.P1));
108
+ if (summary.findings.P2 > 0) findingParts.push(pc.cyan("P2=" + summary.findings.P2));
109
+ if (summary.findings.P3 > 0) findingParts.push(pc.gray("P3=" + summary.findings.P3));
110
+
111
+ process.stderr.write("\n" + parts.join(" · "));
112
+ if (findingParts.length > 0) {
113
+ process.stderr.write(" | " + findingParts.join(" "));
114
+ }
115
+ process.stderr.write("\n");
116
+
117
+ return summary;
118
+ }
@@ -0,0 +1,153 @@
1
+ import { readStoredSession } from "../auth/session-store.js";
2
+
3
+ /**
4
+ * Telemetry Sync — uploads CLI run results to sentinelayer-api.
5
+ *
6
+ * Called after audit, review, omargate commands complete.
7
+ * Fire-and-forget: never blocks the CLI, never crashes on failure.
8
+ * The API stores this data and the web dashboard renders it.
9
+ *
10
+ * What syncs:
11
+ * - Run metadata (command, persona, mode, framework detected)
12
+ * - Findings summary (P0/P1/P2/P3 counts, blocking status)
13
+ * - Usage telemetry (tokens, cost, duration, tool calls)
14
+ * - Stop reason (budget exhausted, max turns, completed, etc.)
15
+ *
16
+ * What stays local:
17
+ * - Full finding details (file:line evidence) — too large for sync
18
+ * - Ingest artifacts — regenerated locally
19
+ * - Spec/prompt/guide files — project artifacts
20
+ */
21
+
22
+ const SYNC_TIMEOUT_MS = 10000;
23
+
24
+ /**
25
+ * Sync a CLI run to the user's sentinelayer dashboard.
26
+ *
27
+ * @param {object} runData
28
+ * @param {string} runData.command - e.g., "audit frontend", "omargate deep", "review scan"
29
+ * @param {string} [runData.persona] - e.g., "Jules Tanaka"
30
+ * @param {string} [runData.mode] - e.g., "primary", "deep", "diff"
31
+ * @param {object} [runData.summary] - { total, P0, P1, P2, P3, blocking }
32
+ * @param {object} [runData.usage] - { tokens, costUsd, durationMs, toolCalls }
33
+ * @param {string} [runData.stopReason] - e.g., "completed", "budget_exhausted"
34
+ * @param {string} [runData.framework] - e.g., "next.js"
35
+ * @param {object} [runData.reconciliation] - baseline reconciliation summary
36
+ * @param {object} [runData.runtime] - runtime audit summary (lighthouse scores, headers)
37
+ * @returns {Promise<{ synced: boolean, reason?: string }>}
38
+ */
39
+ export async function syncRunToDashboard(runData) {
40
+ let session;
41
+ try {
42
+ session = await readStoredSession();
43
+ } catch {
44
+ return { synced: false, reason: "no_session" };
45
+ }
46
+
47
+ if (!session || !session.token) {
48
+ return { synced: false, reason: "not_authenticated" };
49
+ }
50
+
51
+ const apiUrl = session.apiUrl || "https://api.sentinelayer.com";
52
+
53
+ try {
54
+ // Create a run record
55
+ const response = await fetch(apiUrl + "/api/v1/runs", {
56
+ method: "POST",
57
+ headers: {
58
+ "Content-Type": "application/json",
59
+ "Authorization": "Bearer " + session.token,
60
+ },
61
+ body: JSON.stringify({
62
+ mode: mapCommandToMode(runData.command),
63
+ runtime_profile: "cli_local",
64
+ repo: detectRepoName(),
65
+ ref: detectGitRef(),
66
+ orchestrator_model: runData.persona || "cli",
67
+ subagent_model: "deterministic",
68
+ budget: {
69
+ max_cost_usd: runData.usage?.maxCostUsd || 5.0,
70
+ max_iterations: runData.usage?.maxTurns || 25,
71
+ },
72
+ max_iterations: 1,
73
+ }),
74
+ signal: AbortSignal.timeout(SYNC_TIMEOUT_MS),
75
+ });
76
+
77
+ if (!response.ok) {
78
+ return { synced: false, reason: "api_" + response.status };
79
+ }
80
+
81
+ const created = await response.json();
82
+ const runId = created.run_id;
83
+
84
+ // Post a completion event with telemetry
85
+ if (runId) {
86
+ await fetch(apiUrl + "/api/v1/runs/" + runId + "/complete", {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/json",
90
+ "Authorization": "Bearer " + session.token,
91
+ },
92
+ body: JSON.stringify({
93
+ exit_reason: runData.stopReason || "completed",
94
+ stop_class: runData.summary?.blocking ? "BLOCKING_FINDINGS" : "CLEAN",
95
+ summary: {
96
+ command: runData.command,
97
+ persona: runData.persona || null,
98
+ mode: runData.mode || null,
99
+ framework: runData.framework || null,
100
+ findings: runData.summary || { total: 0, P0: 0, P1: 0, P2: 0, P3: 0 },
101
+ usage: {
102
+ token_usage: runData.usage?.tokens || runData.usage?.outputTokens || 0,
103
+ cost_usd: runData.usage?.costUsd || 0,
104
+ duration_ms: runData.usage?.durationMs || 0,
105
+ tool_calls: runData.usage?.toolCalls || 0,
106
+ },
107
+ reconciliation: runData.reconciliation || null,
108
+ runtime: runData.runtime || null,
109
+ },
110
+ }),
111
+ signal: AbortSignal.timeout(SYNC_TIMEOUT_MS),
112
+ }).catch(() => {}); // completion event is best-effort
113
+ }
114
+
115
+ return { synced: true, runId };
116
+ } catch (err) {
117
+ return { synced: false, reason: err.message };
118
+ }
119
+ }
120
+
121
+ function mapCommandToMode(command) {
122
+ if (!command) return "audit_readonly";
123
+ const lower = String(command).toLowerCase();
124
+ if (lower.includes("review")) return "audit_readonly";
125
+ if (lower.includes("omargate")) return "audit_readonly";
126
+ if (lower.includes("audit")) return "audit_readonly";
127
+ if (lower.includes("fix")) return "edit_gated";
128
+ return "audit_readonly";
129
+ }
130
+
131
+ function detectRepoName() {
132
+ try {
133
+ const { execFileSync } = require("node:child_process");
134
+ const remote = execFileSync("git", ["remote", "get-url", "origin"], {
135
+ encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
136
+ }).trim();
137
+ const match = remote.match(/\/([^/]+?)(?:\.git)?$/);
138
+ return match ? match[1] : "unknown";
139
+ } catch {
140
+ return "local";
141
+ }
142
+ }
143
+
144
+ function detectGitRef() {
145
+ try {
146
+ const { execFileSync } = require("node:child_process");
147
+ return execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
148
+ encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
149
+ }).trim() || "main";
150
+ } catch {
151
+ return "main";
152
+ }
153
+ }