rulecloud 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # rulecloud CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Real-time guardrails for AI coding agents. Pulls **Cloud Rulespacks** from your RuleCloud workspace, watches file saves, and reports violations in the terminal (optionally syncing to the Live Agent Monitor).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g rulecloud
9
+ # or run without installing:
10
+ npx rulecloud init
11
+ npx rulecloud watch
12
+ ```
13
+
14
+ Develop from the monorepo `cli/` folder:
15
+
16
+ ```bash
17
+ npm install
18
+ npm run build
19
+ npm link
20
+ ```
21
+
22
+ ## Configure
23
+
24
+ ```bash
25
+ export RULECLOUD_API_URL=https://rulecloud-production.up.railway.app
26
+ export RULECLOUD_API_KEY=rc_live_...
27
+ ```
28
+
29
+ Create API keys in the [RuleCloud console](https://rulecloud.vercel.app/dashboard/keys).
30
+
31
+ ## Commands
32
+
33
+ | Command | Description |
34
+ |---------|-------------|
35
+ | `rulecloud init` | Download merged `.guardrail.yml`, wire `.cursor/mcp.json` + agent rule |
36
+ | `rulecloud watch` | Live HUD: initial scan + file saves (`r` rescan, `c` clear, `q` quit) |
37
+ | `rulecloud watch --plain` | No colors / no TTY shortcuts (CI) |
38
+ | `rulecloud watch` | Cloud Sync **ON** automatically when `RULECLOUD_API_KEY` or `.rulecloud.json` is set |
39
+ | `rulecloud fix [file]` | Pro AI Auto-Fix via API (`f` in watch) |
40
+ | `rulecloud check` | Scan entire repo; exit `1` on high/critical violations |
41
+ | `rulecloud check --staged` | Pre-commit scan of staged git files only |
42
+
43
+ ## Ignored paths
44
+
45
+ `node_modules`, `.git`, `.next`, `dist`, `venv`, `.venv`, `build`, `target`, `__pycache__`
package/dist/api.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { CliConfig } from "./config.js";
2
+ export type BundleResult = {
3
+ rules_yaml: string;
4
+ etag: string;
5
+ notModified?: boolean;
6
+ source: "rulespacks" | "defaults";
7
+ };
8
+ export declare function fetchBundle(cfg: CliConfig, etag?: string): Promise<BundleResult>;
9
+ export type AutofixResult = {
10
+ explanation?: string;
11
+ patched_code?: string;
12
+ suggestion_lines?: string;
13
+ diff?: string;
14
+ error?: string;
15
+ detail?: string;
16
+ };
17
+ export declare function postAutofix(cfg: CliConfig, payload: {
18
+ code: string;
19
+ violation: Record<string, unknown>;
20
+ rules_yaml: string;
21
+ }): Promise<{
22
+ status: number;
23
+ body: AutofixResult;
24
+ }>;
25
+ export declare function postWatchEvent(cfg: CliConfig, payload: {
26
+ file: string;
27
+ findings: Record<string, unknown>[];
28
+ duration_ms: number;
29
+ repo_label?: string;
30
+ }): Promise<void>;
package/dist/api.js ADDED
@@ -0,0 +1,74 @@
1
+ import { createHash } from "node:crypto";
2
+ async function fetchDefaults(cfg) {
3
+ const res = await fetch(`${cfg.apiUrl}/api/defaults`);
4
+ if (!res.ok) {
5
+ const text = await res.text();
6
+ throw new Error(`/api/defaults failed (${res.status}): ${text}`);
7
+ }
8
+ const data = (await res.json());
9
+ const yaml = data.rules_yaml || "";
10
+ const etag = createHash("sha256").update(yaml).digest("hex").slice(0, 16);
11
+ return { rules_yaml: yaml, etag, source: "defaults" };
12
+ }
13
+ export async function fetchBundle(cfg, etag) {
14
+ const headers = {
15
+ "X-API-Key": cfg.apiKey,
16
+ };
17
+ if (etag)
18
+ headers["If-None-Match"] = `"${etag}"`;
19
+ const bundleUrl = `${cfg.apiUrl}/api/rulespacks/bundle`;
20
+ const res = await fetch(bundleUrl, { headers });
21
+ if (res.status === 304) {
22
+ return {
23
+ rules_yaml: "",
24
+ etag: etag || "",
25
+ notModified: true,
26
+ source: "rulespacks",
27
+ };
28
+ }
29
+ if (res.status === 404) {
30
+ console.warn(`Cloud Rulespacks API is not on ${cfg.apiUrl} yet (404).\n` +
31
+ " → Deploy the latest RuleCloud API and run supabase/migrations/010_rulespacks.sql\n" +
32
+ " → Or point at a local server: export RULECLOUD_API_URL=http://127.0.0.1:8000\n" +
33
+ "Using /api/defaults for now.");
34
+ return fetchDefaults(cfg);
35
+ }
36
+ if (!res.ok) {
37
+ const text = await res.text();
38
+ throw new Error(`Bundle fetch failed (${res.status}) from ${bundleUrl}: ${text}`);
39
+ }
40
+ const data = (await res.json());
41
+ return { ...data, source: "rulespacks" };
42
+ }
43
+ export async function postAutofix(cfg, payload) {
44
+ const res = await fetch(`${cfg.apiUrl}/api/ai/autofix`, {
45
+ method: "POST",
46
+ headers: {
47
+ "Content-Type": "application/json",
48
+ "X-API-Key": cfg.apiKey,
49
+ },
50
+ body: JSON.stringify(payload),
51
+ });
52
+ let body = {};
53
+ try {
54
+ body = (await res.json());
55
+ }
56
+ catch {
57
+ body = { detail: await res.text() };
58
+ }
59
+ return { status: res.status, body };
60
+ }
61
+ export async function postWatchEvent(cfg, payload) {
62
+ const res = await fetch(`${cfg.apiUrl}/api/watch/events`, {
63
+ method: "POST",
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ "X-API-Key": cfg.apiKey,
67
+ },
68
+ body: JSON.stringify(payload),
69
+ });
70
+ if (!res.ok && res.status !== 202) {
71
+ const text = await res.text();
72
+ throw new Error(`Watch event failed (${res.status}): ${text}`);
73
+ }
74
+ }
@@ -0,0 +1,14 @@
1
+ import type { CliConfig } from "./config.js";
2
+ import type { Finding } from "./eval.js";
3
+ export declare function runAutofixForFile(opts: {
4
+ cwd: string;
5
+ cfg: CliConfig;
6
+ relPath: string;
7
+ absPath: string;
8
+ code: string;
9
+ findings: Finding[];
10
+ rulesYaml: string;
11
+ plain: boolean;
12
+ interactive: boolean;
13
+ }): Promise<boolean>;
14
+ export declare function runFixCommand(cwd: string, cfg: CliConfig, relFile: string | undefined, plain: boolean): Promise<void>;
@@ -0,0 +1,124 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import readline from "node:readline";
4
+ import pc from "picocolors";
5
+ import { postAutofix } from "./api.js";
6
+ import { requireApiKey } from "./config.js";
7
+ import { severityTier } from "./severity.js";
8
+ function printColoredDiff(diff, plain) {
9
+ for (const line of diff.split(/\r?\n/)) {
10
+ if (!line)
11
+ continue;
12
+ if (line.startsWith("+++") || line.startsWith("---")) {
13
+ console.log(plain ? line : pc.cyan(line));
14
+ }
15
+ else if (line.startsWith("+")) {
16
+ console.log(plain ? line : pc.green(line));
17
+ }
18
+ else if (line.startsWith("-")) {
19
+ console.log(plain ? line : pc.red(line));
20
+ }
21
+ else {
22
+ console.log(plain ? line : pc.dim(line));
23
+ }
24
+ }
25
+ }
26
+ async function confirm(prompt) {
27
+ const rl = readline.createInterface({
28
+ input: process.stdin,
29
+ output: process.stdout,
30
+ });
31
+ return new Promise((resolve) => {
32
+ rl.question(prompt, (answer) => {
33
+ rl.close();
34
+ resolve(/^y(es)?$/i.test(answer.trim()));
35
+ });
36
+ });
37
+ }
38
+ export async function runAutofixForFile(opts) {
39
+ requireApiKey(opts.cfg);
40
+ const targets = opts.findings
41
+ .filter((f) => f.file === opts.relPath)
42
+ .sort((a, b) => {
43
+ const rank = (f) => severityTier(f.severity) === "error" ? 0 : severityTier(f.severity) === "warn" ? 1 : 2;
44
+ return rank(a) - rank(b) || a.line - b.line;
45
+ });
46
+ if (targets.length === 0) {
47
+ console.log(pc.yellow(`No violations in ${opts.relPath}`));
48
+ return false;
49
+ }
50
+ const violation = targets[0];
51
+ const { status, body } = await postAutofix(opts.cfg, {
52
+ code: opts.code,
53
+ violation: violation,
54
+ rules_yaml: opts.rulesYaml,
55
+ });
56
+ if (status === 402) {
57
+ const msg = body.detail || "AI Auto-Fix requires RuleCloud Pro";
58
+ console.log(opts.plain ? msg : pc.yellow(msg));
59
+ console.log(opts.plain
60
+ ? "Upgrade: https://rulecloud.vercel.app/dashboard/billing"
61
+ : pc.cyan("Upgrade: https://rulecloud.vercel.app/dashboard/billing"));
62
+ return false;
63
+ }
64
+ if (status >= 400) {
65
+ throw new Error(body.detail || body.error || `Auto-fix failed (${status})`);
66
+ }
67
+ if (body.explanation) {
68
+ console.log(opts.plain ? body.explanation : pc.bold(body.explanation));
69
+ }
70
+ if (body.diff) {
71
+ printColoredDiff(body.diff, opts.plain);
72
+ }
73
+ const patched = (body.patched_code || "").trim();
74
+ if (!patched) {
75
+ console.log(opts.plain ? "No patched_code returned" : pc.yellow("No patched_code returned"));
76
+ return false;
77
+ }
78
+ if (!opts.interactive)
79
+ return false;
80
+ const ok = await confirm(`Apply fix to ${opts.relPath}? [y/N] `);
81
+ if (!ok)
82
+ return false;
83
+ writeFileSync(opts.absPath, patched, "utf8");
84
+ console.log(opts.plain ? "Applied." : pc.green("Applied."));
85
+ return true;
86
+ }
87
+ export async function runFixCommand(cwd, cfg, relFile, plain) {
88
+ const { loadRulesFromRepo } = await import("./rules-config.js");
89
+ const { evaluateFile } = await import("./eval.js");
90
+ const { readFileSync } = await import("node:fs");
91
+ const loaded = loadRulesFromRepo(cwd);
92
+ let targetRel = relFile;
93
+ if (!targetRel) {
94
+ const { walkSourceFiles } = await import("./walk.js");
95
+ const { evaluateFile } = await import("./eval.js");
96
+ const { severityTier } = await import("./severity.js");
97
+ for (const abs of walkSourceFiles(cwd)) {
98
+ const rel = path.relative(cwd, abs).replace(/\\/g, "/");
99
+ const findings = evaluateFile(rel, readFileSync(abs, "utf8"), loaded.doc);
100
+ if (findings.some((f) => severityTier(f.severity) === "error")) {
101
+ targetRel = rel;
102
+ break;
103
+ }
104
+ }
105
+ }
106
+ if (!targetRel) {
107
+ console.log(plain ? "No file with errors found" : pc.yellow("No file with errors found"));
108
+ return;
109
+ }
110
+ const absPath = path.join(cwd, targetRel);
111
+ const code = readFileSync(absPath, "utf8");
112
+ const findings = evaluateFile(targetRel, code, loaded.doc);
113
+ await runAutofixForFile({
114
+ cwd,
115
+ cfg,
116
+ relPath: targetRel.replace(/\\/g, "/"),
117
+ absPath,
118
+ code,
119
+ findings,
120
+ rulesYaml: loaded.rulesText,
121
+ plain,
122
+ interactive: true,
123
+ });
124
+ }
@@ -0,0 +1 @@
1
+ export declare function runCheck(cwd: string, staged: boolean, plain?: boolean): number;
@@ -0,0 +1,65 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+ import pc from "picocolors";
5
+ import { evaluateFile } from "../eval.js";
6
+ import { hasBlocking } from "../severity.js";
7
+ import { printFinding, printRulesWarning } from "../hud.js";
8
+ import { loadRulesFromRepo } from "../rules-config.js";
9
+ import { shouldIgnorePath } from "../eval.js";
10
+ import { walkSourceFiles } from "../walk.js";
11
+ function stagedFiles(cwd) {
12
+ const r = spawnSync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACMR"], {
13
+ cwd,
14
+ encoding: "utf8",
15
+ });
16
+ if (r.status !== 0)
17
+ return null;
18
+ return r.stdout
19
+ .split(/\r?\n/)
20
+ .map((l) => l.trim())
21
+ .filter(Boolean)
22
+ .map((rel) => path.join(cwd, rel));
23
+ }
24
+ export function runCheck(cwd, staged, plain = false) {
25
+ const loaded = loadRulesFromRepo(cwd);
26
+ console.log(plain
27
+ ? `Loaded ${loaded.configLabel} — ${loaded.ruleCount} rules`
28
+ : pc.cyan(`Loaded ${loaded.configLabel} — ${loaded.ruleCount} rules`));
29
+ if (loaded.warnReason)
30
+ printRulesWarning(loaded.warnReason, plain);
31
+ const doc = loaded.doc;
32
+ const files = staged ? stagedFiles(cwd) : walkSourceFiles(cwd);
33
+ if (staged && files === null) {
34
+ console.error(pc.red("git not available — scanning full tree"));
35
+ return runCheck(cwd, false, plain);
36
+ }
37
+ const targets = files ?? walkSourceFiles(cwd);
38
+ const all = [];
39
+ for (const abs of targets) {
40
+ if (shouldIgnorePath(abs, cwd))
41
+ continue;
42
+ const rel = path.relative(cwd, abs).replace(/\\/g, "/");
43
+ let content;
44
+ try {
45
+ content = readFileSync(abs, "utf8");
46
+ }
47
+ catch {
48
+ continue;
49
+ }
50
+ all.push(...evaluateFile(rel, content, doc));
51
+ }
52
+ const unique = all.filter((f, i, arr) => {
53
+ const k = `${f.id}:${f.file}:${f.line}`;
54
+ return arr.findIndex((x) => `${x.id}:${x.file}:${x.line}` === k) === i;
55
+ });
56
+ if (unique.length === 0) {
57
+ console.log(plain ? "PASS (0)" : pc.green("✓ PASS (0)"));
58
+ return 0;
59
+ }
60
+ for (const f of unique) {
61
+ printFinding(f, plain);
62
+ }
63
+ console.log(plain ? `\n${unique.length} finding(s)` : pc.dim(`\n${unique.length} finding(s)`));
64
+ return hasBlocking(unique) ? 1 : 0;
65
+ }
@@ -0,0 +1,2 @@
1
+ import type { CliConfig } from "../config.js";
2
+ export declare function runInit(cwd: string, cfg: CliConfig): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fetchBundle } from "../api.js";
4
+ import { requireApiKey } from "../config.js";
5
+ const CURSOR_RULE = `---
6
+ description: Run RuleCloud guardrail checks before finishing edits
7
+ globs:
8
+ - "**/*"
9
+ alwaysApply: true
10
+ ---
11
+
12
+ Before marking a coding task complete:
13
+
14
+ 1. Run \`rulecloud check\` on changed files (or use the RuleCloud MCP \`scan_code\` tool).
15
+ 2. Fix any \`[BLOCKED]\` violations before proceeding.
16
+ 3. Keep \`.guardrail.yml\` synced via \`rulecloud init\` when Cloud Rulespacks change in the console.
17
+ `;
18
+ export async function runInit(cwd, cfg) {
19
+ requireApiKey(cfg);
20
+ console.log(`API: ${cfg.apiUrl}`);
21
+ console.log("Fetching Cloud Rulespacks bundle…");
22
+ const bundle = await fetchBundle(cfg);
23
+ if (bundle.source === "defaults") {
24
+ console.log("(Starter defaults — redeploy API for full Cloud Rulespacks merge)");
25
+ }
26
+ const guardrailPath = path.join(cwd, ".guardrail.yml");
27
+ writeFileSync(guardrailPath, bundle.rules_yaml, "utf8");
28
+ console.log(`Wrote ${guardrailPath} (etag: ${bundle.etag})`);
29
+ const rcPath = path.join(cwd, ".rulecloud.json");
30
+ writeFileSync(rcPath, JSON.stringify({
31
+ apiUrl: cfg.apiUrl,
32
+ apiKey: cfg.apiKey,
33
+ }, null, 2) + "\n", "utf8");
34
+ console.log(`Wrote ${rcPath} (Cloud Sync enabled for watch)`);
35
+ const cursorDir = path.join(cwd, ".cursor");
36
+ mkdirSync(cursorDir, { recursive: true });
37
+ mkdirSync(path.join(cursorDir, "rules"), { recursive: true });
38
+ const mcpJson = {
39
+ mcpServers: {
40
+ rulecloud: {
41
+ url: `${cfg.apiUrl}/mcp/`,
42
+ headers: {
43
+ "X-API-Key": "${env:RULECLOUD_API_KEY}",
44
+ },
45
+ },
46
+ },
47
+ };
48
+ writeFileSync(path.join(cursorDir, "mcp.json"), JSON.stringify(mcpJson, null, 2) + "\n", "utf8");
49
+ writeFileSync(path.join(cursorDir, "rules", "rulecloud.mdc"), CURSOR_RULE, "utf8");
50
+ console.log("Configured .cursor/mcp.json and .cursor/rules/rulecloud.mdc");
51
+ console.log("\nNext: rulecloud watch # real-time agent guardrails");
52
+ }
@@ -0,0 +1,6 @@
1
+ import type { CliConfig } from "../config.js";
2
+ export type WatchOpts = {
3
+ cloud: boolean;
4
+ plain: boolean;
5
+ };
6
+ export declare function runWatch(cwd: string, cfg: CliConfig, opts: WatchOpts): Promise<void>;
@@ -0,0 +1,251 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import readline from "node:readline";
4
+ import pc from "picocolors";
5
+ import chokidar from "chokidar";
6
+ import { runAutofixForFile } from "../autofix.js";
7
+ import { postWatchEvent } from "../api.js";
8
+ import { evaluateFile } from "../eval.js";
9
+ import { printFinding, printHeader, printRulesWarning, printScanLine, printStatusLine, } from "../hud.js";
10
+ import { loadRulesFromRepo } from "../rules-config.js";
11
+ import { walkSourceFiles } from "../walk.js";
12
+ function readFileContent(absPath) {
13
+ try {
14
+ return readFileSync(absPath, "utf8");
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export async function runWatch(cwd, cfg, opts) {
21
+ const loaded = loadRulesFromRepo(cwd);
22
+ const doc = loaded.doc;
23
+ const debounce = new Map();
24
+ const allByKey = new Map();
25
+ let lastRel = null;
26
+ let lastAbs = null;
27
+ let lastFindings = [];
28
+ const cloudOn = opts.cloud && Boolean(cfg.apiKey);
29
+ const allFindings = () => [...allByKey.values()];
30
+ const hudArgs = () => ({
31
+ plain: opts.plain,
32
+ cloud: cloudOn,
33
+ ruleCount: loaded.ruleCount,
34
+ configLabel: loaded.configLabel,
35
+ findings: allFindings(),
36
+ });
37
+ const syncCloud = (rel, findings, duration_ms) => {
38
+ if (!cloudOn || !findings.length)
39
+ return;
40
+ void postWatchEvent(cfg, {
41
+ file: rel,
42
+ findings: findings,
43
+ duration_ms,
44
+ repo_label: path.basename(cwd),
45
+ }).catch((err) => {
46
+ if (!opts.plain)
47
+ console.log(pc.dim(`cloud sync: ${err.message}`));
48
+ });
49
+ };
50
+ const mergeFindings = (rel, findings) => {
51
+ for (const [key, f] of [...allByKey.entries()]) {
52
+ if (f.file === rel)
53
+ allByKey.delete(key);
54
+ }
55
+ for (const f of findings) {
56
+ allByKey.set(`${f.id}:${f.file}:${f.line}`, f);
57
+ }
58
+ };
59
+ const renderViolations = (findings) => {
60
+ for (const f of findings) {
61
+ printFinding(f, opts.plain);
62
+ }
63
+ };
64
+ const scanFile = (absPath) => {
65
+ const rel = path.relative(cwd, absPath).replace(/\\/g, "/");
66
+ const content = readFileContent(absPath);
67
+ if (content === null)
68
+ return;
69
+ const start = Date.now();
70
+ const findings = evaluateFile(rel, content, doc);
71
+ const duration_ms = Date.now() - start;
72
+ mergeFindings(rel, findings);
73
+ lastRel = rel;
74
+ lastAbs = absPath;
75
+ lastFindings = findings;
76
+ printScanLine(rel, duration_ms, findings.length, opts.plain);
77
+ if (findings.length)
78
+ renderViolations(findings);
79
+ syncCloud(rel, findings, duration_ms);
80
+ printStatusLine(allFindings(), opts.plain);
81
+ };
82
+ const rescanAll = () => {
83
+ if (!opts.plain)
84
+ console.clear();
85
+ console.log(opts.plain
86
+ ? `Loaded ${loaded.configLabel} (${loaded.ruleCount} rules)`
87
+ : pc.cyan(`Loaded ${loaded.configLabel} (${loaded.ruleCount} rules)`));
88
+ allByKey.clear();
89
+ const files = walkSourceFiles(cwd);
90
+ let filesWithIssues = 0;
91
+ for (const abs of files) {
92
+ const rel = path.relative(cwd, abs).replace(/\\/g, "/");
93
+ const content = readFileContent(abs);
94
+ if (content === null)
95
+ continue;
96
+ const start = Date.now();
97
+ const findings = evaluateFile(rel, content, doc);
98
+ const duration_ms = Date.now() - start;
99
+ mergeFindings(rel, findings);
100
+ if (findings.length) {
101
+ filesWithIssues += 1;
102
+ printScanLine(rel, duration_ms, findings.length, opts.plain);
103
+ renderViolations(findings);
104
+ if (!lastRel) {
105
+ lastRel = rel;
106
+ lastAbs = abs;
107
+ lastFindings = findings;
108
+ }
109
+ }
110
+ }
111
+ if (filesWithIssues === 0) {
112
+ console.log(opts.plain
113
+ ? "Initial scan: all files clean"
114
+ : pc.green("Initial scan: all files clean"));
115
+ }
116
+ printHeader(hudArgs());
117
+ if (!opts.plain) {
118
+ console.log(pc.dim(`Watching ${files.length} files under ${cwd} (awaitWriteFinish 200ms)…`));
119
+ }
120
+ else {
121
+ console.log(`Watching ${files.length} files…`);
122
+ }
123
+ };
124
+ const runFix = async () => {
125
+ if (!lastAbs || !lastRel) {
126
+ console.log(opts.plain
127
+ ? "No recent file — save a file or press r to rescan first"
128
+ : pc.yellow("No recent file — save a file or press r to rescan first"));
129
+ return;
130
+ }
131
+ const content = readFileContent(lastAbs);
132
+ if (content === null)
133
+ return;
134
+ if (process.stdin.isTTY) {
135
+ try {
136
+ process.stdin.setRawMode(false);
137
+ }
138
+ catch {
139
+ /* noop */
140
+ }
141
+ }
142
+ const targets = lastFindings.length > 0
143
+ ? lastFindings
144
+ : evaluateFile(lastRel, content, doc);
145
+ try {
146
+ await runAutofixForFile({
147
+ cwd,
148
+ cfg,
149
+ relPath: lastRel,
150
+ absPath: lastAbs,
151
+ code: content,
152
+ findings: targets,
153
+ rulesYaml: loaded.rulesText,
154
+ plain: opts.plain,
155
+ interactive: true,
156
+ });
157
+ }
158
+ finally {
159
+ if (process.stdin.isTTY && !opts.plain) {
160
+ readline.emitKeypressEvents(process.stdin);
161
+ process.stdin.setRawMode(true);
162
+ process.stdin.resume();
163
+ }
164
+ }
165
+ scanFile(lastAbs);
166
+ };
167
+ console.log(opts.plain
168
+ ? `Config: ${loaded.configLabel}`
169
+ : pc.bold(`Config: ${pc.white(loaded.configLabel)}`));
170
+ console.log(`Rules: ${loaded.ruleCount} active`);
171
+ if (loaded.warnReason) {
172
+ printRulesWarning(loaded.warnReason, opts.plain);
173
+ }
174
+ rescanAll();
175
+ const schedule = (absPath) => {
176
+ const prev = debounce.get(absPath);
177
+ if (prev)
178
+ clearTimeout(prev);
179
+ debounce.set(absPath, setTimeout(() => {
180
+ debounce.delete(absPath);
181
+ scanFile(absPath);
182
+ }, 200));
183
+ };
184
+ const watcher = chokidar.watch(cwd, {
185
+ ignored: (watchPath) => {
186
+ if (watchPath === cwd)
187
+ return false;
188
+ return path
189
+ .relative(cwd, watchPath)
190
+ .split(path.sep)
191
+ .some((p) => [
192
+ "node_modules",
193
+ ".git",
194
+ ".next",
195
+ "dist",
196
+ ".cursor",
197
+ "venv",
198
+ ".venv",
199
+ ].includes(p));
200
+ },
201
+ ignoreInitial: true,
202
+ persistent: true,
203
+ awaitWriteFinish: {
204
+ stabilityThreshold: 200,
205
+ pollInterval: 50,
206
+ },
207
+ atomic: true,
208
+ depth: 99,
209
+ });
210
+ watcher.on("change", schedule);
211
+ watcher.on("add", schedule);
212
+ const stop = async () => {
213
+ await watcher.close();
214
+ for (const t of debounce.values())
215
+ clearTimeout(t);
216
+ if (process.stdin.isTTY && !opts.plain) {
217
+ try {
218
+ process.stdin.setRawMode(false);
219
+ }
220
+ catch {
221
+ /* noop */
222
+ }
223
+ }
224
+ process.exit(0);
225
+ };
226
+ process.on("SIGINT", () => {
227
+ void stop();
228
+ });
229
+ if (process.stdin.isTTY && !opts.plain) {
230
+ readline.emitKeypressEvents(process.stdin);
231
+ process.stdin.setRawMode(true);
232
+ process.stdin.resume();
233
+ process.stdin.on("keypress", (str, key) => {
234
+ if (key?.ctrl && key.name === "c") {
235
+ void stop();
236
+ return;
237
+ }
238
+ const ch = (str || "").toLowerCase();
239
+ if (ch === "q")
240
+ void stop();
241
+ else if (ch === "c") {
242
+ console.clear();
243
+ printHeader(hudArgs());
244
+ }
245
+ else if (ch === "r")
246
+ rescanAll();
247
+ else if (ch === "f")
248
+ void runFix();
249
+ });
250
+ }
251
+ }
@@ -0,0 +1,6 @@
1
+ export type CliConfig = {
2
+ apiUrl: string;
3
+ apiKey: string;
4
+ };
5
+ export declare function loadConfig(cwd?: string): CliConfig;
6
+ export declare function requireApiKey(cfg: CliConfig): string;