unslop-core 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fikri Firman Fadilah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # unslop-core
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
+ > The shared engine behind the `*-unslop-mcp` servers: comment-aware audits, suppressions with reasons, git-change discovery, toolchain checks, a CLI mode and a skill installer.
4
+
5
+ [![npm](https://img.shields.io/npm/v/unslop-core?color=cb3837&logo=npm)](https://www.npmjs.com/package/unslop-core)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
7
+
8
+ You only need this package to build a new unslop server. To use one, install a server:
9
+
10
+ | Server | Audits |
11
+ | --- | --- |
12
+ | [`frontend-unslop-mcp`](https://github.com/fikrifirmanf/frontend-unslop-mcp) | React, Next.js, Tailwind engineering |
13
+ | [`backend-unslop-mcp`](https://github.com/fikrifirmanf/backend-unslop-mcp) | APIs, SQL, security across 9 languages |
14
+ | [`ui-unslop-mcp`](https://github.com/fikrifirmanf/ui-unslop-mcp) | Visual craft, WCAG contrast, a11y, design tokens |
15
+ | [`mobile-unslop-mcp`](https://github.com/fikrifirmanf/mobile-unslop-mcp) | iOS, Android, React Native, Flutter, app manifests |
16
+ | [`copy-unslop-mcp`](https://github.com/fikrifirmanf/copy-unslop-mcp) | Copywriting (EN + ID), readability, length budgets |
17
+ | [`test-unslop-mcp`](https://github.com/fikrifirmanf/test-unslop-mcp) | Fake/flaky tests, real test runs |
18
+
19
+ ## Building a server
20
+
21
+ ```js
22
+ #!/usr/bin/env node
23
+ import { run, byExt } from "unslop-core";
24
+
25
+ await run({
26
+ packageUrl: new URL("../package.json", import.meta.url), // name + version come from here
27
+ skill: "docs-unslop", // skills/docs-unslop/SKILL.md
28
+ description: "Docs anti-slop rules.",
29
+ auditTool: "audit_docs_slop",
30
+ auditDescription: "Scans docs for ...",
31
+ accept: byExt(".md", ".mdx"), // what directory/git discovery picks up
32
+ rules: [
33
+ {
34
+ id: "NO_TODO",
35
+ severity: "ERROR", // ERROR fails the audit, WARN reports only
36
+ scope: "raw", // default "code" masks comments first
37
+ regex: /\bTODO\b/, // or check(src, file) => [{ index, message? }]
38
+ files: /\.mdx?$/, // optional include / exclude filters
39
+ message: "Unfinished TODO.",
40
+ examples: [{ file: "a.md", bad: ["TODO: write"], good: ["Done."] }],
41
+ },
42
+ ],
43
+ tools: [{ name, description, inputSchema, handler: async (args, root) => ({ status: "PASS" }) }],
44
+ });
45
+ ```
46
+
47
+ That one call gives the server:
48
+
49
+ - an MCP prompt and a `load_<skill>_rules` tool serving the SKILL.md;
50
+ - the audit tool, accepting files or directories, or defaulting to git working-tree changes. Directory walks honour `.gitignore` and skip `node_modules`, build output and minified files;
51
+ - `unslop-ignore RULE_ID -- reason` suppressions (a missing reason is itself an error), with every honoured suppression echoed in the output;
52
+ - a CLI: `audit [paths] [--json]` (exit 1 on ERROR), `rules`, `install-skills [--all]`, `--version`.
53
+
54
+ Tool handlers return a plain object; set `_failed: true` to mark the MCP result as an error.
55
+
56
+ ## Helpers
57
+
58
+ | Export | Purpose |
59
+ | --- | --- |
60
+ | `checkRuleExamples(rules)` | Returns problems where a `bad` example is missed or a `good` one flagged. Use it as your rule test. |
61
+ | `maskComments(src, file)` | Blanks comments (keeping offsets and newlines) for 20+ languages |
62
+ | `matchBracket`, `indentedBlock` | Extract brace- or indentation-delimited bodies for structural rules |
63
+ | `collectFiles`, `walk`, `inside` | Workspace-safe file discovery |
64
+ | `runCheck(cmd, args, cwd, opts)` | Runs a toolchain; a missing binary is `SKIPPED`, not `FAIL` |
65
+ | `typescriptCheck`, `localBin`, `projectDir`, `summarizeChecks` | Compile-check building blocks |
66
+
67
+ ## License
68
+
69
+ MIT © Fikri Firman Fadilah
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "unslop-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Shared engine for the *-unslop-mcp servers: comment-aware regex/structural audits, suppressions, git-change discovery, toolchain checks, CLI mode and skill installer.",
5
+ "type": "module",
6
+ "main": "src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test"
17
+ },
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "keywords": [
22
+ "mcp",
23
+ "model-context-protocol",
24
+ "anti-slop",
25
+ "lint",
26
+ "audit"
27
+ ],
28
+ "license": "MIT",
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "^1.32.1"
31
+ },
32
+ "author": "Fikri Firman Fadilah",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/fikrifirmanf/unslop-core.git"
36
+ },
37
+ "homepage": "https://github.com/fikrifirmanf/unslop-core#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/fikrifirmanf/unslop-core/issues"
40
+ }
41
+ }
package/src/audit.mjs ADDED
@@ -0,0 +1,216 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { maskComments } from "./mask.mjs";
6
+
7
+ const execFileAsync = promisify(execFile);
8
+
9
+ export const SKIP_DIRS = new Set([
10
+ "node_modules", ".git", ".next", ".nuxt", ".svelte-kit", ".turbo", ".venv", "venv", "__pycache__",
11
+ "dist", "build", "out", "coverage", "target", "vendor", "Pods", "DerivedData", ".gradle", ".dart_tool",
12
+ ]);
13
+ const MAX_BYTES = 1_000_000;
14
+ const MAX_FINDINGS = 300;
15
+ const SUPPRESS = /unslop-ignore\s+([A-Z0-9_]+(?:\s*,\s*[A-Z0-9_]+)*)(?:\s*(?:--|:)\s*(\S[^\n]*?))?\s*(?:\*\/|-->)?\s*$/;
16
+
17
+ export const inside = (root, p) => {
18
+ const rel = path.relative(root, p);
19
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
20
+ };
21
+
22
+ export async function walk(dir, accept, out = [], depth = 0) {
23
+ if (depth > 12) return out;
24
+ for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
25
+ if (SKIP_DIRS.has(e.name) || (e.name.startsWith(".") && e.isDirectory())) continue;
26
+ const p = path.join(dir, e.name);
27
+ if (e.isDirectory()) await walk(p, accept, out, depth + 1);
28
+ else if (accept(p)) out.push(p);
29
+ }
30
+ return out;
31
+ }
32
+
33
+ // Directory expansion honours .gitignore when the dir is inside a git work tree.
34
+ async function gitListed(dir) {
35
+ try {
36
+ const { stdout } = await execFileAsync("git", ["ls-files", "-co", "--exclude-standard", "-z", "."], { cwd: dir, maxBuffer: 50 * 1024 * 1024 });
37
+ return stdout.split("\0").filter(Boolean).map((f) => path.join(dir, f));
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ const isSkipped = (p) => p.split(path.sep).some((seg) => SKIP_DIRS.has(seg));
44
+
45
+ async function expandDir(dir, accept) {
46
+ const listed = await gitListed(dir);
47
+ return listed ? listed.filter((p) => accept(p) && !isSkipped(p)) : walk(dir, accept);
48
+ }
49
+
50
+ // Minified/bundled output: a very long line or a very high average line length.
51
+ export function looksGenerated(raw, file) {
52
+ if (/\.min\.\w+$|[.-]bundle\.\w+$|\.d\.ts$|\.lock$/.test(file)) return true;
53
+ const lines = raw.split("\n");
54
+ return lines.some((l) => l.length > 3000) || (raw.length > 5000 && raw.length / lines.length > 250);
55
+ }
56
+
57
+ async function gitChanged(root) {
58
+ try {
59
+ const opts = { cwd: root, maxBuffer: 10 * 1024 * 1024 };
60
+ const top = (await execFileAsync("git", ["rev-parse", "--show-toplevel"], opts)).stdout.trim();
61
+ const { stdout } = await execFileAsync("git", ["status", "--porcelain", "-uall", "--no-renames"], opts);
62
+ return stdout
63
+ .split("\n")
64
+ .filter((l) => l.length > 3 && !l.startsWith(" D") && !l.startsWith("D "))
65
+ .map((l) => path.join(top, l.slice(3).replace(/^"|"$/g, "")));
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Resolves files/directories (or, when empty, the git working-tree changes) into auditable paths.
73
+ * @returns {Promise<{files: string[], errors: object[], source: string}>}
74
+ */
75
+ export async function collectFiles(inputs, root, accept) {
76
+ const errors = [];
77
+ let source = "input";
78
+ let candidates = inputs;
79
+ if (!candidates.length) {
80
+ const changed = await gitChanged(root);
81
+ if (changed === null) return { files: [], errors: [{ file: ".", line: 0, rule: "NO_FILES", severity: "ERROR", message: "No files given and the workspace is not a git repository. Pass `files` (files or directories)." }], source: "none" };
82
+ candidates = changed;
83
+ source = "git-changes";
84
+ }
85
+ const files = new Set();
86
+ for (const rel of candidates) {
87
+ const full = path.resolve(root, rel);
88
+ if (!inside(root, full)) {
89
+ if (source === "input") errors.push({ file: rel, line: 0, rule: "OUTSIDE_WORKSPACE", severity: "ERROR", message: "Path is outside the workspace." });
90
+ continue;
91
+ }
92
+ const stat = await fs.stat(full).catch(() => null);
93
+ if (!stat) {
94
+ errors.push({ file: rel, line: 0, rule: "FILE_MISSING", severity: "ERROR", message: "File could not be read." });
95
+ continue;
96
+ }
97
+ if (stat.isDirectory()) for (const f of await expandDir(full, accept)) files.add(f);
98
+ else if (source === "input" || accept(full)) files.add(full);
99
+ }
100
+ return { files: [...files], errors, source };
101
+ }
102
+
103
+ const globalize = (re) => new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
104
+
105
+ /** Runs one rule against one file's text. Returns [{index, text}] matches. */
106
+ export function matchRule(rule, raw, file) {
107
+ if (rule.files && !rule.files.test(file)) return [];
108
+ if (rule.exclude && rule.exclude.test(file)) return [];
109
+ const src = rule.scope === "raw" ? raw : maskComments(raw, file);
110
+ if (rule.check) return rule.check(src, file, raw) ?? [];
111
+ return [...src.matchAll(globalize(rule.regex))].map((m) => ({ index: m.index, text: m[0] }));
112
+ }
113
+
114
+ function lineOf(src, index) {
115
+ let n = 1;
116
+ for (let i = 0; i < index && i < src.length; i++) if (src.charCodeAt(i) === 10) n++;
117
+ return n;
118
+ }
119
+
120
+ function suppression(lines, line, ruleId) {
121
+ for (const l of [lines[line - 1], lines[line - 2]]) {
122
+ const m = l && l.match(SUPPRESS);
123
+ if (m && m[1].split(/\s*,\s*/).includes(ruleId)) return { reason: m[2]?.trim() || null };
124
+ }
125
+ return null;
126
+ }
127
+
128
+ export function auditSource(raw, file, rules) {
129
+ const findings = [];
130
+ const suppressed = [];
131
+ const lines = raw.split("\n");
132
+ for (const rule of rules) {
133
+ for (const m of matchRule(rule, raw, file)) {
134
+ const line = lineOf(raw, m.index);
135
+ const finding = {
136
+ file,
137
+ line,
138
+ rule: rule.id,
139
+ severity: rule.severity,
140
+ message: m.message || rule.message,
141
+ snippet: (lines[line - 1] ?? m.text ?? "").trim().slice(0, 140),
142
+ };
143
+ const s = suppression(lines, line, rule.id);
144
+ if (s?.reason) suppressed.push({ file, line, rule: rule.id, reason: s.reason });
145
+ else if (s) findings.push({ ...finding, severity: "ERROR", rule: "SUPPRESSION_WITHOUT_REASON", message: `unslop-ignore ${rule.id} needs a reason: \`unslop-ignore ${rule.id} -- why this is safe\`.` });
146
+ else findings.push(finding);
147
+ }
148
+ }
149
+ return { findings, suppressed };
150
+ }
151
+
152
+ /**
153
+ * @param {{files?: string[]}} args
154
+ * @param {string} root workspace root; paths cannot escape it
155
+ * @param {{rules: object[], accept: (p: string) => boolean}} cfg
156
+ */
157
+ export async function audit(args, root, cfg) {
158
+ const inputs = Array.isArray(args.files) ? args.files.filter((f) => typeof f === "string" && f) : [];
159
+ const { files, errors, source } = await collectFiles(inputs, root, cfg.accept);
160
+ const findings = [...errors];
161
+ const suppressed = [];
162
+ const skippedGenerated = [];
163
+ const explicit = new Set(inputs.map((f) => path.resolve(root, f)));
164
+ for (const full of files) {
165
+ const stat = await fs.stat(full).catch(() => null);
166
+ if (!stat || stat.size > MAX_BYTES) continue;
167
+ const raw = await fs.readFile(full, "utf8").catch(() => null);
168
+ if (raw === null || raw.includes("\u0000")) continue;
169
+ if (!explicit.has(full) && looksGenerated(raw, full)) {
170
+ skippedGenerated.push(path.relative(root, full));
171
+ continue;
172
+ }
173
+ const r = auditSource(raw, path.relative(root, full) || path.basename(full), cfg.rules);
174
+ findings.push(...r.findings);
175
+ suppressed.push(...r.suppressed);
176
+ }
177
+ findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "ERROR" ? -1 : 1));
178
+ const errorCount = findings.filter((f) => f.severity === "ERROR").length;
179
+ const byRule = {};
180
+ for (const f of findings) byRule[f.rule] = (byRule[f.rule] || 0) + 1;
181
+ const failed = errorCount > 0;
182
+ return {
183
+ status: failed ? "FAIL" : "PASS",
184
+ filesScanned: files.length - skippedGenerated.length,
185
+ ...(skippedGenerated.length ? { skippedGenerated: skippedGenerated.slice(0, 20) } : {}),
186
+ fileSource: source,
187
+ errors: errorCount,
188
+ warnings: findings.length - errorCount,
189
+ byRule,
190
+ findings: findings.slice(0, MAX_FINDINGS),
191
+ ...(findings.length > MAX_FINDINGS ? { truncated: findings.length - MAX_FINDINGS } : {}),
192
+ ...(suppressed.length ? { suppressed } : {}),
193
+ instruction: failed
194
+ ? "Fix every ERROR finding at its root cause and re-run the audit. Use `unslop-ignore RULE_ID -- reason` only for verified false positives."
195
+ : files.length - skippedGenerated.length === 0
196
+ ? "No matching files were scanned. Pass the modified files or directories explicitly."
197
+ : "All anti-slop checks passed. Review WARN findings before finishing.",
198
+ _failed: failed,
199
+ };
200
+ }
201
+
202
+ /** Verifies every rule's `examples`: each `bad` snippet must trigger the rule and each `good` must not. */
203
+ export function checkRuleExamples(rules) {
204
+ const problems = [];
205
+ const ids = new Set();
206
+ for (const rule of rules) {
207
+ if (ids.has(rule.id)) problems.push(`${rule.id}: duplicate rule id`);
208
+ ids.add(rule.id);
209
+ if (!rule.examples?.length) problems.push(`${rule.id}: no examples`);
210
+ for (const ex of rule.examples ?? []) {
211
+ for (const bad of ex.bad ?? []) if (!matchRule(rule, bad, ex.file).length) problems.push(`${rule.id}: missed bad example in ${ex.file}: ${JSON.stringify(bad)}`);
212
+ for (const good of ex.good ?? []) if (matchRule(rule, good, ex.file).length) problems.push(`${rule.id}: flagged good example in ${ex.file}: ${JSON.stringify(good)}`);
213
+ }
214
+ }
215
+ return problems;
216
+ }
package/src/exec.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { inside } from "./audit.mjs";
6
+
7
+ const execFileAsync = promisify(execFile);
8
+
9
+ /**
10
+ * Runs a toolchain command. A missing binary is SKIPPED (not FAIL) so agents do not loop on
11
+ * environment problems they cannot fix.
12
+ * @returns {Promise<{status: "PASS"|"FAIL"|"SKIPPED", cmd: string, output?: string}>}
13
+ */
14
+ export async function runCheck(cmd, args, cwd, { timeout = 180_000, label, env } = {}) {
15
+ const shown = label || `${cmd} ${args.join(" ")}`.slice(0, 300);
16
+ try {
17
+ const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, timeout, maxBuffer: 20 * 1024 * 1024, ...(env ? { env } : {}) });
18
+ return { status: "PASS", cmd: shown, output: `${stdout}\n${stderr}`.trim().slice(-4000) || undefined };
19
+ } catch (err) {
20
+ if (err.code === "ENOENT") return { status: "SKIPPED", cmd: shown, output: `\`${cmd}\` is not installed or not on PATH.` };
21
+ const output = `${err.stdout || ""}\n${err.stderr || ""}`.trim() || err.message;
22
+ return { status: "FAIL", cmd: shown, output: (err.killed ? `Timed out after ${timeout / 1000}s.\n` : "") + output.slice(-20000) };
23
+ }
24
+ }
25
+
26
+ /** Resolves a workspace-relative project dir; returns null if it escapes the workspace. */
27
+ export function projectDir(root, projectRoot) {
28
+ const cwd = path.resolve(root, projectRoot || ".");
29
+ return inside(root, cwd) ? cwd : null;
30
+ }
31
+
32
+ /** Locally installed binary in node_modules/.bin, searched upward to the workspace root. */
33
+ export function localBin(cwd, root, name) {
34
+ for (let dir = cwd; inside(root, dir); dir = path.dirname(dir)) {
35
+ const p = path.join(dir, "node_modules", ".bin", name);
36
+ if (existsSync(p)) return p;
37
+ if (dir === path.dirname(dir)) break;
38
+ }
39
+ return null;
40
+ }
41
+
42
+ export async function typescriptCheck(cwd, root) {
43
+ const tsc = localBin(cwd, root, "tsc");
44
+ if (!tsc) return { lang: "typescript", status: "SKIPPED", cmd: "tsc --noEmit", output: "typescript is not installed in this project (npm i -D typescript)." };
45
+ return { lang: "typescript", ...(await runCheck(tsc, ["--noEmit", "--pretty", "false"], cwd, { label: "tsc --noEmit" })) };
46
+ }
47
+
48
+ /** Folds check results into one tool response. SKIPPED never fails, but is reported. */
49
+ export function summarizeChecks(checks, { none = "No toolchain detected in projectRoot; nothing to verify." } = {}) {
50
+ if (!checks.length) return { status: "PASS", message: none, _failed: false };
51
+ const failed = checks.filter((c) => c.status === "FAIL");
52
+ const ran = checks.filter((c) => c.status !== "SKIPPED");
53
+ return {
54
+ status: failed.length ? "FAIL" : ran.length ? "PASS" : "SKIPPED",
55
+ checks: checks.map((c) => (c.status === "PASS" ? { ...c, output: undefined } : c)),
56
+ instruction: failed.length
57
+ ? "Fix every reported error and re-run until PASS."
58
+ : ran.length
59
+ ? "All available checks passed."
60
+ : "No check could run because the toolchain is missing. Tell the user verification was skipped; do not claim it passed.",
61
+ _failed: failed.length > 0,
62
+ };
63
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,11 @@
1
+ export { run } from "./server.mjs";
2
+ export { audit, auditSource, matchRule, collectFiles, walk, inside, checkRuleExamples, SKIP_DIRS } from "./audit.mjs";
3
+ export { maskComments, syntaxFor, matchBracket, indentedBlock } from "./mask.mjs";
4
+ export { runCheck, projectDir, localBin, typescriptCheck, summarizeChecks } from "./exec.mjs";
5
+ export { installSkills } from "./install.mjs";
6
+
7
+ /** Builds an `accept` predicate from a list of extensions, e.g. byExt(".ts", ".py"). */
8
+ export const byExt = (...exts) => {
9
+ const set = new Set(exts.map((e) => e.toLowerCase()));
10
+ return (p) => set.has(p.slice(p.lastIndexOf(".")).toLowerCase());
11
+ };
@@ -0,0 +1,33 @@
1
+ import fs from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const home = os.homedir();
7
+
8
+ // [client, skills dir, dir whose existence means the client is installed]
9
+ const TARGETS = [
10
+ ["claude-code", path.join(home, ".claude", "skills"), path.join(home, ".claude")],
11
+ ["codex", path.join(home, ".codex", "skills"), path.join(home, ".codex")],
12
+ ["antigravity", path.join(home, ".gemini", "config", "skills"), path.join(home, ".gemini")],
13
+ ["antigravity-legacy", path.join(home, ".gemini", "antigravity", "skills"), path.join(home, ".gemini", "antigravity")],
14
+ ];
15
+
16
+ /** Copies every skill folder in `skillsDir` into each installed client. `all` installs everywhere. */
17
+ export async function installSkills(skillsDir, { all = false } = {}) {
18
+ const names = (await fs.readdir(skillsDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
19
+ const targets = TARGETS.filter(([, , marker]) => all || existsSync(marker));
20
+ if (!targets.length) targets.push(TARGETS[0]);
21
+ for (const [client, dir] of targets) {
22
+ for (const name of names) {
23
+ const dest = path.join(dir, name);
24
+ await fs.rm(dest, { recursive: true, force: true });
25
+ await fs.mkdir(dir, { recursive: true });
26
+ await fs.cp(path.join(skillsDir, name), dest, { recursive: true });
27
+ console.log(`[${client}] skill installed -> ${dest}`);
28
+ }
29
+ }
30
+ const skipped = TARGETS.filter((t) => !targets.includes(t)).map(([c]) => c);
31
+ if (skipped.length) console.log(`Skipped (not installed): ${skipped.join(", ")}. Use --all to install anyway.`);
32
+ console.log("Claude Desktop: upload the skill folder via Settings > Capabilities > Skills (zip), or use the MCP prompt/tool instead.");
33
+ }
package/src/mask.mjs ADDED
@@ -0,0 +1,98 @@
1
+ // Comment masking: replaces comment text with spaces (newlines kept) so line numbers stay exact
2
+ // and rules scoped to "code" never fire on prose inside comments.
3
+
4
+ const C_LIKE = { line: ["//"], block: [["/*", "*/"]] };
5
+ const HASH = { line: ["#"], block: [] };
6
+ const HTML = { line: [], block: [["<!--", "-->"]] };
7
+
8
+ const SYNTAX = [
9
+ [/\.(?:[cm]?[jt]sx?|java|kts?|cs|go|swift|scala|dart|c|cc|cpp|h|hpp|m|mm|scss|less)$/, { ...C_LIKE, quotes: "\"'`" }],
10
+ [/\.css$/, { line: [], block: [["/*", "*/"]], quotes: "\"'" }],
11
+ [/\.rs$/, { ...C_LIKE, quotes: "\"" }],
12
+ [/\.php$/, { line: ["//", "#"], block: [["/*", "*/"]], quotes: "\"'" }],
13
+ [/\.(?:py|rb|sh|bash|zsh|ya?ml|toml|r|ex|exs|tf)$/, { ...HASH, quotes: "\"'" }],
14
+ [/\.sql$/, { line: ["--"], block: [["/*", "*/"]], quotes: "'\"" }],
15
+ [/\.(?:html?|xml|plist|svg|md|mdx)$/, { ...HTML, quotes: "" }],
16
+ [/\.(?:vue|svelte|astro)$/, { line: ["//"], block: [["/*", "*/"], ["<!--", "-->"]], quotes: "\"'`" }],
17
+ ];
18
+
19
+ export function syntaxFor(file) {
20
+ return SYNTAX.find(([re]) => re.test(file))?.[1] ?? null;
21
+ }
22
+
23
+ const blank = (s) => s.replace(/[^\n]/g, " ");
24
+
25
+ export function maskComments(src, file) {
26
+ const syn = syntaxFor(file);
27
+ if (!syn) return src;
28
+ let out = "";
29
+ let quote = null;
30
+ let i = 0;
31
+ while (i < src.length) {
32
+ const c = src[i];
33
+ if (quote) {
34
+ if (c === "\\") {
35
+ out += src.slice(i, i + 2);
36
+ i += 2;
37
+ continue;
38
+ }
39
+ // Unterminated single-line strings (apostrophes in JSX text, Rust lifetimes) end at the newline.
40
+ if (c === quote || (c === "\n" && quote !== "`")) quote = null;
41
+ out += c;
42
+ i++;
43
+ continue;
44
+ }
45
+ if (syn.quotes.includes(c)) {
46
+ quote = c;
47
+ out += c;
48
+ i++;
49
+ continue;
50
+ }
51
+ const blk = syn.block.find(([open]) => src.startsWith(open, i));
52
+ if (blk) {
53
+ const end = src.indexOf(blk[1], i + blk[0].length);
54
+ const stop = end === -1 ? src.length : end + blk[1].length;
55
+ out += blank(src.slice(i, stop));
56
+ i = stop;
57
+ continue;
58
+ }
59
+ if (syn.line.some((open) => src.startsWith(open, i))) {
60
+ const end = src.indexOf("\n", i);
61
+ const stop = end === -1 ? src.length : end;
62
+ out += blank(src.slice(i, stop));
63
+ i = stop;
64
+ continue;
65
+ }
66
+ out += c;
67
+ i++;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ // Returns the index just past the matching close bracket for the opener at `open`, or -1.
73
+ export function matchBracket(src, open, pair = "{}") {
74
+ let depth = 0;
75
+ for (let i = open; i < src.length; i++) {
76
+ if (src[i] === pair[0]) depth++;
77
+ else if (src[i] === pair[1] && --depth === 0) return i + 1;
78
+ }
79
+ return -1;
80
+ }
81
+
82
+ // Returns the body of the indentation block that starts on the line after `index` (Python, YAML).
83
+ export function indentedBlock(src, index) {
84
+ const lineEnd = src.indexOf("\n", index);
85
+ if (lineEnd === -1) return "";
86
+ const head = src.slice(src.lastIndexOf("\n", index) + 1, lineEnd);
87
+ const baseIndent = head.match(/^[ \t]*/)[0].length;
88
+ const lines = [];
89
+ for (const line of src.slice(lineEnd + 1).split("\n")) {
90
+ if (line.trim() === "") {
91
+ lines.push(line);
92
+ continue;
93
+ }
94
+ if (line.match(/^[ \t]*/)[0].length <= baseIndent) break;
95
+ lines.push(line);
96
+ }
97
+ return lines.join("\n");
98
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,107 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema,
6
+ ListPromptsRequestSchema,
7
+ GetPromptRequestSchema,
8
+ } from "@modelcontextprotocol/sdk/types.js";
9
+ import fs from "node:fs/promises";
10
+ import { readFileSync } from "node:fs";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { audit } from "./audit.mjs";
14
+ import { installSkills } from "./install.mjs";
15
+
16
+ const respond = (obj) => {
17
+ if (typeof obj === "string") return { content: [{ type: "text", text: obj }], isError: false };
18
+ const { _failed, ...rest } = obj;
19
+ return { content: [{ type: "text", text: JSON.stringify(rest, null, 2) }], isError: Boolean(_failed) };
20
+ };
21
+
22
+ /**
23
+ * @typedef {{name: string, description: string, inputSchema: object, handler: (args: object, root: string) => Promise<object|string>}} Tool
24
+ * @param {{
25
+ * packageUrl: URL, // the server package's package.json
26
+ * skill: string, // skill folder name under skills/
27
+ * description: string,
28
+ * auditTool: string,
29
+ * auditDescription: string,
30
+ * rules: object[],
31
+ * accept: (p: string) => boolean, // which files directory/git discovery picks up
32
+ * tools?: Tool[],
33
+ * }} cfg
34
+ */
35
+ export async function run(cfg) {
36
+ const pkg = JSON.parse(readFileSync(fileURLToPath(cfg.packageUrl), "utf8"));
37
+ const pkgDir = path.dirname(fileURLToPath(cfg.packageUrl));
38
+ const skillsDir = path.join(pkgDir, "skills");
39
+ const loadSkill = () => fs.readFile(path.join(skillsDir, cfg.skill, "SKILL.md"), "utf8");
40
+ const loadTool = `load_${cfg.skill.replace(/-/g, "_")}_rules`;
41
+ const tools = cfg.tools ?? [];
42
+ const root = process.cwd();
43
+
44
+ const [cmd, ...rest] = process.argv.slice(2);
45
+ if (cmd === "install-skills") return installSkills(skillsDir, { all: rest.includes("--all") });
46
+ if (cmd === "audit") return cliAudit(rest, root, cfg);
47
+ if (cmd === "rules") {
48
+ for (const r of cfg.rules) console.log(`${r.severity.padEnd(5)} ${r.id.padEnd(32)} ${r.message}`);
49
+ return;
50
+ }
51
+ if (cmd === "--version" || cmd === "-v") return console.log(pkg.version);
52
+ if (cmd === "--help" || cmd === "-h") {
53
+ console.log(`${pkg.name} ${pkg.version}\n\nUsage:\n ${pkg.name} start the MCP server (stdio)\n ${pkg.name} audit [paths] [--json] audit files/dirs (default: git changes); exit 1 on FAIL\n ${pkg.name} rules list rules\n ${pkg.name} install-skills [--all] copy the skill into Claude Code / Codex / Antigravity`);
54
+ return;
55
+ }
56
+
57
+ const server = new Server({ name: pkg.name, version: pkg.version }, { capabilities: { tools: {}, prompts: {} } });
58
+
59
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: [{ name: cfg.skill, description: cfg.description }] }));
60
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
61
+ if (req.params.name !== cfg.skill) throw new Error(`Unknown prompt: ${req.params.name}`);
62
+ return { messages: [{ role: "user", content: { type: "text", text: await loadSkill() } }] };
63
+ });
64
+
65
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
66
+ tools: [
67
+ { name: loadTool, description: `Returns the full ${cfg.skill} ruleset. Call before writing code if the ${cfg.skill} skill is not already loaded.`, inputSchema: { type: "object", properties: {} } },
68
+ {
69
+ name: cfg.auditTool,
70
+ description: `${cfg.auditDescription} Accepts files or directories; with no files it audits the git working-tree changes. Suppress a verified false positive with a \`unslop-ignore RULE_ID -- reason\` comment on or above the line.`,
71
+ inputSchema: {
72
+ type: "object",
73
+ properties: { files: { type: "array", items: { type: "string" }, description: "Workspace-relative files or directories. Omit to audit git changes." } },
74
+ },
75
+ },
76
+ ...tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
77
+ ],
78
+ }));
79
+
80
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
81
+ const { name, arguments: args = {} } = req.params;
82
+ if (name === loadTool) return respond(await loadSkill());
83
+ if (name === cfg.auditTool) return respond(await audit(args, root, cfg));
84
+ const tool = tools.find((t) => t.name === name);
85
+ if (!tool) throw new Error(`Unknown tool: ${name}`);
86
+ try {
87
+ return respond(await tool.handler(args, root));
88
+ } catch (err) {
89
+ return respond({ status: "FAIL", message: `${name} crashed: ${err.message}`, _failed: true });
90
+ }
91
+ });
92
+
93
+ await server.connect(new StdioServerTransport());
94
+ }
95
+
96
+ async function cliAudit(argv, root, cfg) {
97
+ const json = argv.includes("--json");
98
+ const result = await audit({ files: argv.filter((a) => !a.startsWith("--")) }, root, cfg);
99
+ const { _failed, ...rest } = result;
100
+ if (json) console.log(JSON.stringify(rest, null, 2));
101
+ else {
102
+ for (const f of result.findings) console.log(`${f.file}:${f.line} ${f.severity.padEnd(5)} ${f.rule} ${f.message}${f.snippet ? `\n ${f.snippet}` : ""}`);
103
+ if (result.truncated) console.log(`... ${result.truncated} more findings`);
104
+ console.log(`\n${result.status}: ${result.errors} error(s), ${result.warnings} warning(s) in ${result.filesScanned} file(s) [${result.fileSource}]`);
105
+ }
106
+ process.exitCode = _failed ? 1 : 0;
107
+ }