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/dist/config.js ADDED
@@ -0,0 +1,67 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ const ENV_URL = "RULECLOUD_API_URL";
5
+ const ENV_KEY = "RULECLOUD_API_KEY";
6
+ const LOCAL_RC = path.join(homedir(), ".rulecloudrc");
7
+ function loadDotEnv(cwd) {
8
+ for (const name of [".env", ".env.local"]) {
9
+ const p = path.join(cwd, name);
10
+ if (!existsSync(p))
11
+ continue;
12
+ try {
13
+ const raw = readFileSync(p, "utf8");
14
+ for (const line of raw.split(/\r?\n/)) {
15
+ const trimmed = line.trim();
16
+ if (!trimmed || trimmed.startsWith("#"))
17
+ continue;
18
+ const url = trimmed.match(/^RULECLOUD_API_URL=(.+)$/);
19
+ if (url)
20
+ process.env[ENV_URL] = url[1].trim().replace(/^["']|["']$/g, "");
21
+ const key = trimmed.match(/^RULECLOUD_API_KEY=(.+)$/);
22
+ if (key)
23
+ process.env[ENV_KEY] = key[1].trim().replace(/^["']|["']$/g, "");
24
+ }
25
+ }
26
+ catch {
27
+ /* ignore */
28
+ }
29
+ }
30
+ }
31
+ function loadProjectJson(cwd) {
32
+ const p = path.join(cwd, ".rulecloud.json");
33
+ if (!existsSync(p))
34
+ return {};
35
+ try {
36
+ const data = JSON.parse(readFileSync(p, "utf8"));
37
+ return {
38
+ apiUrl: data.apiUrl,
39
+ apiKey: data.apiKey,
40
+ };
41
+ }
42
+ catch {
43
+ return {};
44
+ }
45
+ }
46
+ export function loadConfig(cwd = process.cwd()) {
47
+ loadDotEnv(cwd);
48
+ const project = loadProjectJson(cwd);
49
+ const apiUrl = (project.apiUrl ||
50
+ process.env[ENV_URL] ||
51
+ process.env.NEXT_PUBLIC_API_URL ||
52
+ "https://rulecloud-production.up.railway.app").replace(/\/$/, "");
53
+ let apiKey = (project.apiKey || process.env[ENV_KEY] || "").trim();
54
+ if (!apiKey && existsSync(LOCAL_RC)) {
55
+ const raw = readFileSync(LOCAL_RC, "utf8");
56
+ const m = raw.match(/^RULECLOUD_API_KEY=(.+)$/m);
57
+ if (m)
58
+ apiKey = m[1].trim();
59
+ }
60
+ return { apiUrl, apiKey };
61
+ }
62
+ export function requireApiKey(cfg) {
63
+ if (!cfg.apiKey) {
64
+ throw new Error(`Missing API key. Set ${ENV_KEY}, add .rulecloud.json, .env, or ${LOCAL_RC}`);
65
+ }
66
+ return cfg.apiKey;
67
+ }
package/dist/eval.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { hasBlocking } from "./severity.js";
2
+ export type Finding = {
3
+ id: string;
4
+ message: string;
5
+ file: string;
6
+ line: number;
7
+ severity: string;
8
+ };
9
+ export type RuleDoc = {
10
+ include: string[];
11
+ exclude: string[];
12
+ rules: Record<string, unknown>[];
13
+ };
14
+ export declare function parseRulesYaml(text: string): RuleDoc;
15
+ export declare function evaluateFile(relpath: string, content: string, doc: RuleDoc): Finding[];
16
+ export declare function shouldIgnorePath(absPath: string, root: string): boolean;
17
+ export { hasBlocking as hasCritical, hasBlocking };
package/dist/eval.js ADDED
@@ -0,0 +1,159 @@
1
+ import yaml from "js-yaml";
2
+ import path from "node:path";
3
+ import { shouldEvaluateSourceFile } from "./exclusions.js";
4
+ import { expandExtensionIncludes, matchAny } from "./glob.js";
5
+ import { hasBlocking } from "./severity.js";
6
+ const SKIP_DIRS = new Set([
7
+ "node_modules",
8
+ ".git",
9
+ ".next",
10
+ "dist",
11
+ "venv",
12
+ ".venv",
13
+ "build",
14
+ "target",
15
+ "__pycache__",
16
+ ".cursor",
17
+ ]);
18
+ function rulePatterns(rule, include) {
19
+ for (const key of ["match", "include", "files"]) {
20
+ const val = rule[key];
21
+ if (typeof val === "string" && val.trim())
22
+ return [val.trim()];
23
+ if (Array.isArray(val) && val.length)
24
+ return val.map(String);
25
+ }
26
+ return include;
27
+ }
28
+ export function parseRulesYaml(text) {
29
+ const data = yaml.load(text);
30
+ const include = Array.isArray(data?.include)
31
+ ? data.include.map(String)
32
+ : ["**/*"];
33
+ const extFromKey = expandExtensionIncludes(data?.extensions);
34
+ const extFromInclude = expandExtensionIncludes(data?.["include.extensions"]);
35
+ for (const g of [...extFromKey, ...extFromInclude]) {
36
+ if (!include.includes(g))
37
+ include.push(g);
38
+ }
39
+ const exclude = Array.isArray(data?.exclude) ? data.exclude.map(String) : [];
40
+ const rules = Array.isArray(data?.rules)
41
+ ? data.rules.filter((r) => r?.id)
42
+ : [];
43
+ return { include, exclude, rules };
44
+ }
45
+ function evalRegex(rule, relpath, lines, patterns) {
46
+ if (!matchAny(patterns, relpath))
47
+ return [];
48
+ const raw = (rule.pattern || rule.regex);
49
+ if (!raw)
50
+ return [];
51
+ let pat = String(raw);
52
+ let flags = "";
53
+ if (pat.startsWith("(?i)")) {
54
+ pat = pat.slice(4);
55
+ flags = "i";
56
+ }
57
+ let rx;
58
+ try {
59
+ rx = new RegExp(pat, flags);
60
+ }
61
+ catch {
62
+ return [];
63
+ }
64
+ const rid = String(rule.id);
65
+ const msg = String(rule.message || rule.description || rid);
66
+ const sev = String(rule.severity || "warning");
67
+ const out = [];
68
+ for (let i = 0; i < lines.length; i++) {
69
+ if (rx.test(lines[i])) {
70
+ out.push({ id: rid, message: msg, file: relpath, line: i + 1, severity: sev });
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+ function evalLayer(rule, relpath, lines) {
76
+ const from = rule.from;
77
+ const to = rule.to;
78
+ if (!from || !to)
79
+ return [];
80
+ if (!matchAny([from], relpath))
81
+ return [];
82
+ const rid = String(rule.id);
83
+ const msg = String(rule.message || "Forbidden layer dependency");
84
+ const sev = String(rule.severity || "medium");
85
+ const toNorm = to.replace(/\\/g, "/");
86
+ const importRe = /^\s*(import|from|using)\s+/;
87
+ const out = [];
88
+ for (let i = 0; i < lines.length; i++) {
89
+ const line = lines[i];
90
+ if (!importRe.test(line))
91
+ continue;
92
+ const ln = line.replace(/\\/g, "/");
93
+ const dataLayer = /\/data\//.test(toNorm) &&
94
+ /(?:from|import)\s+['"][^'"]*(\.\.\/)+data\/|(?:from|import)\s+['"][^'"]*\/data\//.test(ln);
95
+ const segment = toNorm.replace(/\*\*/g, "").replace(/^\/+/, "");
96
+ if (dataLayer || (segment && ln.includes(segment))) {
97
+ out.push({ id: rid, message: msg, file: relpath, line: i + 1, severity: sev });
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+ function evalMaxLines(rule, relpath, lines, patterns) {
103
+ const max = rule.max_lines;
104
+ if (max == null || !matchAny(patterns, relpath))
105
+ return [];
106
+ const limit = Number(max);
107
+ if (Number.isNaN(limit) || lines.length <= limit)
108
+ return [];
109
+ return [
110
+ {
111
+ id: String(rule.id),
112
+ message: String(rule.message || `File exceeds ${limit} lines (${lines.length})`),
113
+ file: relpath,
114
+ line: 1,
115
+ severity: String(rule.severity || "warning"),
116
+ },
117
+ ];
118
+ }
119
+ export function evaluateFile(relpath, content, doc) {
120
+ if (!shouldEvaluateSourceFile(relpath, doc.rules))
121
+ return [];
122
+ if (doc.exclude.length && matchAny(doc.exclude, relpath))
123
+ return [];
124
+ if (!matchAny(doc.include, relpath))
125
+ return [];
126
+ if (!content.trim())
127
+ return [];
128
+ const lines = content.split(/\r?\n/);
129
+ const findings = [];
130
+ for (const rule of doc.rules) {
131
+ const patterns = rulePatterns(rule, doc.include);
132
+ const rtype = String(rule.type || "").toLowerCase();
133
+ if (rule.from && rule.to)
134
+ findings.push(...evalLayer(rule, relpath, lines));
135
+ if (rule.max_lines != null)
136
+ findings.push(...evalMaxLines(rule, relpath, lines, patterns));
137
+ if (rtype === "regex" || rule.pattern || rule.regex) {
138
+ findings.push(...evalRegex(rule, relpath, lines, patterns));
139
+ }
140
+ }
141
+ const seen = new Set();
142
+ return findings.filter((f) => {
143
+ const k = `${f.id}:${f.file}:${f.line}`;
144
+ if (seen.has(k))
145
+ return false;
146
+ seen.add(k);
147
+ return true;
148
+ });
149
+ }
150
+ export function shouldIgnorePath(absPath, root) {
151
+ const rel = path.relative(root, absPath);
152
+ if (!rel || rel === ".")
153
+ return false;
154
+ if (rel.startsWith(".."))
155
+ return true;
156
+ const parts = rel.split(path.sep);
157
+ return parts.some((p) => SKIP_DIRS.has(p));
158
+ }
159
+ export { hasBlocking as hasCritical, hasBlocking };
@@ -0,0 +1,4 @@
1
+ export declare function isDefaultExcludedPath(relpath: string): boolean;
2
+ /** True when a rule's match/include/files is narrower than a repo-wide glob. */
3
+ export declare function ruleExplicitlyTargets(rule: Record<string, unknown>, relpath: string): boolean;
4
+ export declare function shouldEvaluateSourceFile(relpath: string, rules: Record<string, unknown>[]): boolean;
@@ -0,0 +1,50 @@
1
+ import path from "node:path";
2
+ import { matchAny } from "./glob.js";
3
+ const CONFIG_NAMES = new Set([
4
+ ".guardrail.yml",
5
+ "guardrail.yaml",
6
+ "guardrail.yml",
7
+ ]);
8
+ const LOCKFILES = new Set([
9
+ "package-lock.json",
10
+ "yarn.lock",
11
+ "pnpm-lock.yaml",
12
+ "bun.lockb",
13
+ ]);
14
+ export function isDefaultExcludedPath(relpath) {
15
+ const norm = relpath.replace(/\\/g, "/");
16
+ const base = path.basename(norm);
17
+ if (CONFIG_NAMES.has(base))
18
+ return true;
19
+ if (LOCKFILES.has(base))
20
+ return true;
21
+ if (norm.endsWith(".md"))
22
+ return true;
23
+ if (norm.includes("/.guard/") || norm.startsWith(".guard/"))
24
+ return true;
25
+ return false;
26
+ }
27
+ /** True when a rule's match/include/files is narrower than a repo-wide glob. */
28
+ export function ruleExplicitlyTargets(rule, relpath) {
29
+ if (rule.from) {
30
+ return matchAny([String(rule.from)], relpath);
31
+ }
32
+ const patterns = [];
33
+ for (const key of ["match", "include", "files"]) {
34
+ const val = rule[key];
35
+ if (typeof val === "string" && val.trim())
36
+ patterns.push(val.trim());
37
+ if (Array.isArray(val))
38
+ patterns.push(...val.map(String));
39
+ }
40
+ const specific = patterns.filter((p) => {
41
+ const t = p.trim();
42
+ return t && t !== "**/*" && t !== "**" && t !== "*";
43
+ });
44
+ return specific.some((p) => matchAny([p], relpath));
45
+ }
46
+ export function shouldEvaluateSourceFile(relpath, rules) {
47
+ if (!isDefaultExcludedPath(relpath))
48
+ return true;
49
+ return rules.some((rule) => ruleExplicitlyTargets(rule, relpath));
50
+ }
package/dist/glob.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /** Glob → regex (aligned with server guardrail_eval semantics). */
2
+ export declare function globToRegex(pattern: string): RegExp;
3
+ export declare function globMatch(pattern: string, relpath: string): boolean;
4
+ export declare function matchAny(patterns: string[], relpath: string): boolean;
5
+ export declare function expandExtensionIncludes(extensions: unknown): string[];
package/dist/glob.js ADDED
@@ -0,0 +1,63 @@
1
+ /** Glob → regex (aligned with server guardrail_eval semantics). */
2
+ export function globToRegex(pattern) {
3
+ let p = pattern.replace(/\\/g, "/").trim();
4
+ if (p.startsWith("./"))
5
+ p = p.slice(2);
6
+ // *.ts at repo root should still match nested TypeScript files
7
+ if (/^\*\.[\w.+-]+$/.test(p)) {
8
+ p = `**/${p}`;
9
+ }
10
+ const parts = [];
11
+ let i = 0;
12
+ while (i < p.length) {
13
+ if (p.slice(i, i + 3) === "**/") {
14
+ parts.push("(?:.*/)?");
15
+ i += 3;
16
+ }
17
+ else if (p.slice(i, i + 2) === "**") {
18
+ parts.push(".*");
19
+ i += 2;
20
+ }
21
+ else if (p[i] === "*") {
22
+ parts.push("[^/]*");
23
+ i += 1;
24
+ }
25
+ else if (p[i] === "?") {
26
+ parts.push("[^/]");
27
+ i += 1;
28
+ }
29
+ else {
30
+ let j = i;
31
+ while (j < p.length && p[j] !== "*" && p[j] !== "?")
32
+ j += 1;
33
+ parts.push(p.slice(i, j).replace(/[.+^${}()|[\]\\]/g, "\\$&"));
34
+ i = j;
35
+ }
36
+ }
37
+ return new RegExp("^" + parts.join("") + "$", "i");
38
+ }
39
+ export function globMatch(pattern, relpath) {
40
+ const norm = relpath.replace(/\\/g, "/").replace(/^\.\//, "");
41
+ try {
42
+ return globToRegex(pattern).test(norm);
43
+ }
44
+ catch {
45
+ return norm.includes(pattern.replace(/\\/g, "/"));
46
+ }
47
+ }
48
+ export function matchAny(patterns, relpath) {
49
+ if (!patterns.length)
50
+ return true;
51
+ return patterns.some((p) => globMatch(p, relpath));
52
+ }
53
+ export function expandExtensionIncludes(extensions) {
54
+ if (!Array.isArray(extensions))
55
+ return [];
56
+ return extensions.map((raw) => {
57
+ const s = String(raw).trim();
58
+ if (!s)
59
+ return "";
60
+ const ext = s.startsWith(".") ? s : `.${s}`;
61
+ return `**/*${ext}`;
62
+ }).filter(Boolean);
63
+ }
package/dist/hud.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { Finding } from "./eval.js";
2
+ export type HudOptions = {
3
+ plain: boolean;
4
+ cloud: boolean;
5
+ };
6
+ export declare function printRulesWarning(reason: string, plain: boolean): void;
7
+ export declare function printHeader(opts: HudOptions & {
8
+ ruleCount: number;
9
+ configLabel: string;
10
+ findings: Finding[];
11
+ }): void;
12
+ export declare function printScanLine(rel: string, durationMs: number, count: number, plain: boolean): void;
13
+ export declare function printFinding(f: Finding, plain: boolean): void;
14
+ export declare function printStatusLine(findings: Finding[], plain: boolean): void;
package/dist/hud.js ADDED
@@ -0,0 +1,63 @@
1
+ import pc from "picocolors";
2
+ import { formatHudStatus, severityLabel, summarizeFindings } from "./severity.js";
3
+ function c(enabled, fn, s) {
4
+ return enabled ? fn(s) : s;
5
+ }
6
+ function timeStamp() {
7
+ const d = new Date();
8
+ const pad = (n) => String(n).padStart(2, "0");
9
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
10
+ }
11
+ export function printRulesWarning(reason, plain) {
12
+ const line = `⚠ ${reason}`;
13
+ console.log(plain ? line : pc.yellow(line));
14
+ }
15
+ export function printHeader(opts) {
16
+ const { plain, cloud, ruleCount, configLabel, findings } = opts;
17
+ const cloudLabel = cloud ? "ON" : "OFF";
18
+ const summary = summarizeFindings(findings);
19
+ const statusText = formatHudStatus(summary, plain);
20
+ const status = summary.kind === "pass"
21
+ ? c(plain, pc.green, statusText)
22
+ : summary.kind === "blocked"
23
+ ? c(plain, pc.red, statusText)
24
+ : c(plain, pc.yellow, statusText);
25
+ const bar = [
26
+ c(plain, pc.bold, "RuleCloud Watch"),
27
+ `Rules: ${ruleCount} loaded (${configLabel})`,
28
+ `Cloud Sync: ${cloudLabel}`,
29
+ `Status: ${status}`,
30
+ ].join(" · ");
31
+ console.log(bar);
32
+ if (!plain && process.stdin.isTTY) {
33
+ console.log(pc.dim("r rescan · f ai-fix · c clear · q quit"));
34
+ }
35
+ console.log("");
36
+ }
37
+ export function printScanLine(rel, durationMs, count, plain) {
38
+ const ts = `[${timeStamp()}]`;
39
+ if (count === 0) {
40
+ console.log(`${ts} Scanned ${rel} (${durationMs}ms) — ${c(plain, pc.green, "✓ clean")}`);
41
+ return;
42
+ }
43
+ const n = count === 1 ? "1 violation" : `${count} violations`;
44
+ console.log(`${ts} Scanned ${rel} (${durationMs}ms) — ${c(plain, pc.yellow, n)}`);
45
+ }
46
+ export function printFinding(f, plain) {
47
+ const label = severityLabel(f.severity);
48
+ const loc = `${f.file}:${f.line}`;
49
+ const color = label === "ERROR" ? pc.red : label === "WARN" ? pc.yellow : pc.dim;
50
+ const head = c(plain, color, ` ✖ [${label}] ${loc} ${f.id}`);
51
+ console.log(head);
52
+ console.log(c(plain, pc.dim, ` └─ ${f.message}`));
53
+ }
54
+ export function printStatusLine(findings, plain) {
55
+ const summary = summarizeFindings(findings);
56
+ const statusText = formatHudStatus(summary, plain);
57
+ const colored = summary.kind === "pass"
58
+ ? c(plain, pc.green, statusText)
59
+ : summary.kind === "blocked"
60
+ ? c(plain, pc.red, statusText)
61
+ : c(plain, pc.yellow, statusText);
62
+ console.log(c(plain, pc.dim, `Status: ${colored}`));
63
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import { runInit } from "./commands/init.js";
4
+ import { runCheck } from "./commands/check.js";
5
+ import { runFixCommand } from "./autofix.js";
6
+ import { runWatch } from "./commands/watch.js";
7
+ import { loadConfig } from "./config.js";
8
+ function usage() {
9
+ console.log(`RuleCloud CLI — real-time AI agent guardrails
10
+
11
+ Usage:
12
+ rulecloud init Pull Cloud Rulespacks + configure Cursor
13
+ rulecloud watch [--cloud] [--plain] [dir] Live HUD
14
+ rulecloud check [--staged] [--plain] [dir] One-shot scan
15
+ rulecloud fix [file] AI Auto-Fix via API (Pro)
16
+
17
+ Environment:
18
+ RULECLOUD_API_URL API base (default: production)
19
+ RULECLOUD_API_KEY Workspace API key (rc_live_...)
20
+ `);
21
+ process.exit(1);
22
+ }
23
+ const argv = process.argv.slice(2);
24
+ const cmd = argv[0];
25
+ const positional = argv.slice(1).filter((a) => !a.startsWith("-"));
26
+ const cwd = (cmd === "check" || cmd === "watch") && positional[0]
27
+ ? path.resolve(positional[0])
28
+ : process.cwd();
29
+ const fixFile = cmd === "fix" ? positional[0] : undefined;
30
+ if (!cmd || cmd === "-h" || cmd === "--help")
31
+ usage();
32
+ const cfg = loadConfig(cwd);
33
+ try {
34
+ if (cmd === "init") {
35
+ await runInit(cwd, cfg);
36
+ }
37
+ else if (cmd === "watch") {
38
+ const plain = argv.includes("--plain") || !process.stdout.isTTY;
39
+ const cloud = !argv.includes("--no-cloud") &&
40
+ (Boolean(cfg.apiKey) || argv.includes("--cloud"));
41
+ await runWatch(cwd, cfg, { cloud, plain });
42
+ }
43
+ else if (cmd === "fix") {
44
+ const plain = argv.includes("--plain");
45
+ await runFixCommand(cwd, cfg, fixFile, plain);
46
+ }
47
+ else if (cmd === "check") {
48
+ const staged = argv.includes("--staged");
49
+ const plain = argv.includes("--plain");
50
+ const code = runCheck(cwd, staged, plain);
51
+ process.exit(code);
52
+ }
53
+ else {
54
+ usage();
55
+ }
56
+ }
57
+ catch (err) {
58
+ console.error(err instanceof Error ? err.message : String(err));
59
+ process.exit(1);
60
+ }
@@ -0,0 +1,10 @@
1
+ import { type RuleDoc } from "./eval.js";
2
+ export type LoadedRules = {
3
+ configPath: string;
4
+ configLabel: string;
5
+ rulesText: string;
6
+ doc: RuleDoc;
7
+ ruleCount: number;
8
+ warnReason?: string;
9
+ };
10
+ export declare function loadRulesFromRepo(cwd: string): LoadedRules;
@@ -0,0 +1,33 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseRulesYaml } from "./eval.js";
4
+ const CANDIDATES = [".guardrail.yml", "guardrail.yaml", "guardrail.yml"];
5
+ export function loadRulesFromRepo(cwd) {
6
+ for (const name of CANDIDATES) {
7
+ const configPath = path.join(cwd, name);
8
+ try {
9
+ const rulesText = readFileSync(configPath, "utf8");
10
+ const doc = parseRulesYaml(rulesText);
11
+ const ruleCount = doc.rules.length;
12
+ let warnReason;
13
+ if (ruleCount === 0) {
14
+ warnReason =
15
+ "Rules file parsed but the rules array is empty — no checks will run.";
16
+ }
17
+ return {
18
+ configPath,
19
+ configLabel: name,
20
+ rulesText,
21
+ doc,
22
+ ruleCount,
23
+ warnReason,
24
+ };
25
+ }
26
+ catch (err) {
27
+ if (err.code === "ENOENT")
28
+ continue;
29
+ throw err;
30
+ }
31
+ }
32
+ throw new Error(`No guardrail config found in ${cwd} (tried ${CANDIDATES.join(", ")}) — run rulecloud init`);
33
+ }
@@ -0,0 +1,13 @@
1
+ import type { Finding } from "./eval.js";
2
+ export type SeverityTier = "error" | "warn" | "info";
3
+ export declare function severityTier(sev: string): SeverityTier;
4
+ export declare function severityLabel(sev: string): string;
5
+ export type StatusSummary = {
6
+ kind: "pass" | "blocked" | "warnings";
7
+ errorCount: number;
8
+ warnCount: number;
9
+ total: number;
10
+ };
11
+ export declare function summarizeFindings(findings: Finding[]): StatusSummary;
12
+ export declare function formatHudStatus(summary: StatusSummary, plain: boolean): string;
13
+ export declare function hasBlocking(findings: Finding[]): boolean;
@@ -0,0 +1,48 @@
1
+ export function severityTier(sev) {
2
+ const s = sev.toLowerCase();
3
+ if (s === "error" || s.includes("crit"))
4
+ return "error";
5
+ if (s === "high")
6
+ return "error";
7
+ return s === "medium" || s.includes("warn") ? "warn" : "info";
8
+ }
9
+ export function severityLabel(sev) {
10
+ const t = severityTier(sev);
11
+ if (t === "error")
12
+ return "ERROR";
13
+ if (t === "warn")
14
+ return "WARN";
15
+ return "INFO";
16
+ }
17
+ export function summarizeFindings(findings) {
18
+ let errorCount = 0;
19
+ let warnCount = 0;
20
+ for (const f of findings) {
21
+ const t = severityTier(f.severity);
22
+ if (t === "error")
23
+ errorCount += 1;
24
+ else
25
+ warnCount += 1;
26
+ }
27
+ const total = findings.length;
28
+ let kind = "pass";
29
+ if (errorCount > 0)
30
+ kind = "blocked";
31
+ else if (total > 0)
32
+ kind = "warnings";
33
+ return { kind, errorCount, warnCount, total };
34
+ }
35
+ export function formatHudStatus(summary, plain) {
36
+ if (summary.kind === "pass")
37
+ return plain ? "PASS (0)" : "PASS (0)";
38
+ if (summary.kind === "blocked") {
39
+ const n = summary.errorCount;
40
+ const label = n === 1 ? "1 error" : `${n} errors`;
41
+ return `BLOCKED (${label})`;
42
+ }
43
+ const n = summary.total;
44
+ return n === 1 ? "WARNINGS (1)" : `WARNINGS (${n})`;
45
+ }
46
+ export function hasBlocking(findings) {
47
+ return findings.some((f) => severityTier(f.severity) === "error");
48
+ }
package/dist/walk.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function walkSourceFiles(root: string, base?: string): string[];
package/dist/walk.js ADDED
@@ -0,0 +1,52 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { shouldIgnorePath } from "./eval.js";
4
+ const SCANNABLE_EXT = new Set([
5
+ ".ts",
6
+ ".tsx",
7
+ ".js",
8
+ ".jsx",
9
+ ".py",
10
+ ".cs",
11
+ ".go",
12
+ ".java",
13
+ ".rb",
14
+ ".php",
15
+ ".rs",
16
+ ".md",
17
+ ".json",
18
+ ".yaml",
19
+ ".yml",
20
+ ]);
21
+ export function walkSourceFiles(root, base = root) {
22
+ const out = [];
23
+ let entries;
24
+ try {
25
+ entries = readdirSync(root);
26
+ }
27
+ catch {
28
+ return out;
29
+ }
30
+ for (const name of entries) {
31
+ const abs = path.join(root, name);
32
+ if (shouldIgnorePath(abs, base))
33
+ continue;
34
+ let st;
35
+ try {
36
+ st = statSync(abs);
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ if (st.isDirectory()) {
42
+ out.push(...walkSourceFiles(abs, base));
43
+ }
44
+ else if (st.isFile()) {
45
+ const ext = path.extname(name).toLowerCase();
46
+ if (!ext || SCANNABLE_EXT.has(ext)) {
47
+ out.push(abs);
48
+ }
49
+ }
50
+ }
51
+ return out;
52
+ }