@kroos-dev/code-advisor 0.0.0-stage → 0.2.1

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,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kroos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # Kroos Code Advisor
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
+ A local MCP server for Claude Code and other MCP clients. It connects your project to [Kroos](https://kroos.ai) for:
4
+
5
+ - **Business advice from a summary.** `fingerprint_repo` reads the project on your machine and builds a short summary: stack, payments, auth, AI SDKs, data categories and launch gaps. It contains no code or secrets. `get_business_advice` sends that summary only after you confirm it.
6
+ - **Full code reviews.** `bundle_project` collects source files locally. It skips dependencies, builds, lockfiles, binaries, `.env` files and keys, and hides secrets. It then shows you what would be shared. `share_project` sends the files only after you say yes, and Kroos reviews the whole project: what it does, how it scales, risks, running costs and what it means for the business. `review_files` handles follow-up questions about specific files.
7
+ - **Access check.** `check_access` tells you whether the advisor is connected to your Kroos account, and how to connect it if it isn't.
8
+
9
+ Kroos explains and plans. It never writes or changes your code. Code goes straight from this process to Kroos, without passing through the AI app's context. Kroos keeps what it learns about the project, not the code.
10
+
11
+ ## Install
12
+
13
+ 1. Create a pairing token: open https://kroos.ai/chat#/projects, sign in (a free account works) and choose **Create pairing token**. The token is shown once.
14
+ 2. Add the advisor in your own terminal. Don't paste the token into a chat.
15
+
16
+ ```bash
17
+ claude mcp add -s user kroos-code-advisor -e KROOS_PROJECT_TOKEN=<token> -- npx -y @kroos-dev/code-advisor
18
+ ```
19
+
20
+ 3. Restart Claude Code, or run `/mcp`, then ask: "check Kroos access".
21
+
22
+ Other MCP clients:
23
+
24
+ ```json
25
+ { "mcpServers": { "kroos-code-advisor": { "command": "npx", "args": ["-y", "@kroos-dev/code-advisor"], "env": { "KROOS_PROJECT_TOKEN": "<token>" } } } }
26
+ ```
27
+
28
+ ## Settings
29
+
30
+ | Variable | Meaning |
31
+ |---|---|
32
+ | `KROOS_PROJECT_TOKEN` | Pairing token from Kroos → Projects (required to share code) |
33
+ | `KROOS_ADVISOR_URL` | Optional. Defaults to `https://api.kroos.ai/api/advisor/fingerprint` |
34
+
35
+ There are no dependencies. It needs Node.js 18 or later.
package/bundle.mjs ADDED
@@ -0,0 +1,270 @@
1
+ // Kroos Code Advisor — LOCAL project bundle. Collects a project's source files for Kroos to review, on the
2
+ // developer's machine: respects .gitignore (via git when available), skips dependencies, builds, lockfiles,
3
+ // binaries, minified files, .env files and keys, and hides secrets before anything can leave the machine.
4
+ // It makes NO network requests; share() sends a bundle only when the person has confirmed it.
5
+ import { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
6
+ import { join, relative, extname, basename, resolve, sep } from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import { gzipSync } from "node:zlib";
10
+
11
+ /** Big enough for a real monorepo's source; when a project is bigger, the most important files go first. */
12
+ export const LIMITS = { files: 3000, perFile: 200_000, total: 12_000_000 };
13
+ /** Kroos's API host inspects request bodies up to 64 KB; batches stay under it with room for JSON. */
14
+ export const BATCH_BYTES = 56_000;
15
+
16
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "out", ".next", ".nuxt", ".svelte-kit", "vendor", ".venv", "venv", "env", "__pycache__", "target", ".gradle", "Pods", "coverage", ".turbo", ".cache", ".terraform", ".idea", ".vscode", "bin", "obj", "DerivedData", ".dart_tool"]);
17
+ const TEXT_EXT = new Set([".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".go", ".rb", ".php", ".java", ".kt", ".kts", ".swift", ".dart", ".cs", ".rs", ".c", ".h", ".cpp", ".hpp", ".m", ".scala", ".ex", ".exs", ".erl", ".clj", ".lua", ".r", ".sql", ".prisma", ".graphql", ".gql", ".vue", ".svelte", ".astro", ".html", ".css", ".scss", ".sass", ".less", ".json", ".yml", ".yaml", ".toml", ".xml", ".gradle", ".tf", ".hcl", ".sh", ".bash", ".zsh", ".ps1", ".md", ".mdx", ".txt", ".ini", ".cfg", ".conf", ".proto", ".sol", ".plist", ".entitlements", ".xcconfig", ".properties", ".mm"]);
18
+ const TEXT_NAMES = new Set(["Dockerfile", "Makefile", "Procfile", "Gemfile", "Rakefile", "Podfile", "Jenkinsfile", "Caddyfile", ".env.example", ".env.sample"]);
19
+ const LOCKFILES = new Set(["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb", "Cargo.lock", "poetry.lock", "Gemfile.lock", "composer.lock", "Pipfile.lock", "go.sum", "pubspec.lock", "Podfile.lock", "packages.lock.json", "uv.lock"]);
20
+ const MANIFESTS = new Set(["package.json", "requirements.txt", "pyproject.toml", "go.mod", "composer.json", "pubspec.yaml", "Gemfile", "pom.xml", "build.gradle", "build.gradle.kts", "Cargo.toml", "Package.swift", "Dockerfile"]);
21
+ const SENSITIVE = /(^|\/)(\.env(\.(?!example$|sample$)[\w.-]+)?|.*\.(pem|key|p12|pfx|jks|keystore|crt|cer|der)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|\.npmrc|\.pypirc|\.netrc|credentials(\.json)?|service[-_]?account.*\.json|.*\.tfstate(\.backup)?|.*\.tfvars|local\.properties|keystore\.properties|signing\.properties|.*\.mobileprovision|.*\.p8|GoogleService-Info\.plist|google-services\.json|Local\.xcconfig|Secrets?\.xcconfig)$/i;
22
+
23
+ // Secrets are replaced before sending (Kroos hides them again on arrival).
24
+ const SECRET_PATTERNS = [
25
+ /\b(?:sk|rk)_live_[0-9a-zA-Z]{10,}/g, /\bsk_test_[0-9a-zA-Z]{10,}/g, /\bsk-ant-[\w-]{10,}/g, /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}/g,
26
+ /\bAKIA[0-9A-Z]{16}\b/g, /\bgh[pousr]_[A-Za-z0-9]{30,}/g, /\bxox[baprs]-[\w-]{10,}/g, /\bAIza[0-9A-Za-z_-]{30,}/g, /\bSG\.[\w-]{16,}\.[\w-]{16,}/g,
27
+ /\bkroos_(?:sk|pt|oa|or)_[\w-]{16,}/g, /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g,
28
+ ];
29
+ const PRIVATE_KEY = /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/g;
30
+ const GENERIC_SECRET = /\b(password|passwd|pwd|secret|api_?key|apikey|access_?token|auth_?token|client_?secret|private_?key)\b["']?\s*[:=]>?\s*["']([^"'\s]{6,})["']/gi;
31
+ const CONN_STRING = /\b[a-z][\w+.-]*:\/\/[^\s:/@'"]+:([^\s@'"$]{3,})@[\w.-]+/gi;
32
+ const PLACEHOLDER = /your|xxx|changeme|change_me|example|placeholder|\*{3}|<[^>]*>|\$\{|dummy|sample|redacted|test1?2?3?$|^password$/i;
33
+
34
+ export function redact(text) {
35
+ let n = 0;
36
+ let out = text.replace(PRIVATE_KEY, () => { n++; return "[private key redacted]"; });
37
+ for (const re of SECRET_PATTERNS) out = out.replace(re, (m) => { n++; return `${m.slice(0, 4)}…[redacted]`; });
38
+ out = out.replace(GENERIC_SECRET, (m, _k, v) => { if (PLACEHOLDER.test(v)) return m; n++; return m.replace(v, `${v.slice(0, 2)}…[redacted]`); });
39
+ out = out.replace(CONN_STRING, (m, pw) => { n++; return m.replace(`:${pw}@`, ":[redacted]@"); });
40
+ return { text: out, redactions: n };
41
+ }
42
+
43
+ /** The project's files: git's view when it's a repository (respects .gitignore), otherwise a filtered walk. */
44
+ function listFiles(root) {
45
+ try {
46
+ const out = execFileSync("git", ["ls-files", "-co", "--exclude-standard", "-z"], { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
47
+ const files = out.split("\0").filter(Boolean).filter((p) => !p.split("/").some((d) => SKIP_DIRS.has(d)));
48
+ if (files.length) return files;
49
+ } catch { /* not a git repository, or git isn't installed */ }
50
+ const files = [];
51
+ const stack = [root];
52
+ while (stack.length && files.length < 20_000) {
53
+ const dir = stack.pop();
54
+ let entries = [];
55
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
56
+ for (const e of entries) {
57
+ const p = join(dir, e.name);
58
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !(e.name.startsWith(".") && e.name !== ".github")) stack.push(p); }
59
+ else if (e.isFile()) files.push(relative(root, p).split(sep).join("/"));
60
+ }
61
+ }
62
+ return files;
63
+ }
64
+
65
+ const depth = (p) => p.split("/").length;
66
+ const CODE_EXT = new Set([".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".go", ".rb", ".php", ".java", ".kt", ".kts", ".swift", ".dart", ".cs", ".rs", ".c", ".h", ".cpp", ".hpp", ".m", ".scala", ".ex", ".exs", ".erl", ".clj", ".lua", ".r", ".sql", ".prisma", ".graphql", ".gql", ".vue", ".svelte", ".astro", ".sol", ".proto"]);
67
+ const CONFIG_EXT = new Set([".plist", ".entitlements", ".xcconfig", ".properties", ".json", ".yml", ".yaml", ".toml", ".xml", ".gradle", ".tf", ".hcl", ".sh", ".bash", ".zsh", ".ps1", ".ini", ".cfg", ".conf", ".html", ".css", ".scss", ".sass", ".less"]);
68
+ const TEST_PATH = /(^|\/)(tests?|__tests__|spec|specs|e2e|cypress|playwright|__mocks__|fixtures?|testdata)(\/|$)|\.(test|spec|stories)\.[\w]+$|_test\.(go|py)$|(^|\/)test_[\w]+\.py$/i;
69
+ const DOC_PATH = /\.(md|mdx|txt|rst|adoc)$/i;
70
+ const SCRATCH = /(^|\/)(\.[\w-]+|examples?|samples?|demo|scratch|tmp|temp|archive|old|legacy|generated|__generated__|migrations?\/\d)(\/|$)/i;
71
+ /**
72
+ * What matters most when a project doesn't fit: manifests, then application code, then configuration and
73
+ * infrastructure, then tests, then docs (README first), then scratch, examples and hidden folders.
74
+ */
75
+ export function priority(p) {
76
+ const name = basename(p), ext = extname(p).toLowerCase();
77
+ if (MANIFESTS.has(name) && depth(p) <= 3) return 0;
78
+ if (/^readme\.(md|txt)$/i.test(name) && depth(p) === 1) return 1;
79
+ const scratch = SCRATCH.test(p) && !/(^|\/)\.github\//.test(p);
80
+ if (scratch) return 7;
81
+ if (TEST_PATH.test(p)) return 4;
82
+ if (CODE_EXT.has(ext)) return 2;
83
+ if (CONFIG_EXT.has(ext) || TEXT_NAMES.has(name) || MANIFESTS.has(name)) return 3;
84
+ if (DOC_PATH.test(p)) return /^readme\./i.test(name) ? 5 : 6;
85
+ return 6;
86
+ }
87
+ const isText = (p) => TEXT_EXT.has(extname(p).toLowerCase()) || TEXT_NAMES.has(basename(p));
88
+
89
+ /**
90
+ * Build a bundle of the project's source files. `include` limits it to some folders or files (e.g. ["src"]).
91
+ * Returns the files (secrets hidden) and a summary to show the person before anything is shared.
92
+ */
93
+ export function bundle(rootIn, opts = {}) {
94
+ const root = resolve(rootIn ?? process.cwd());
95
+ if (!existsSync(root) || !statSync(root).isDirectory()) throw new Error(`Not a folder: ${root}`);
96
+ const include = (opts.include ?? []).map((x) => String(x).replace(/\\/g, "/").replace(/^\.?\/+|\/+$/g, "")).filter(Boolean);
97
+ const skipped = { dependencies_or_build: 0, sensitive: [], lockfiles: 0, not_source: 0, too_large: [], minified: 0, binary: 0, over_limit: 0, over_limit_examples: [] };
98
+ let candidates = listFiles(root);
99
+ if (include.length) candidates = candidates.filter((p) => include.some((i) => p === i || p.startsWith(`${i}/`)));
100
+ candidates.sort((a, b) => priority(a) - priority(b) || depth(a) - depth(b) || a.localeCompare(b));
101
+ const limits = { ...LIMITS, ...(opts.limits ?? {}) };
102
+ const files = [];
103
+ let total = 0, redactions = 0;
104
+ for (const p of candidates) {
105
+ if (p.split("/").some((d) => SKIP_DIRS.has(d))) { skipped.dependencies_or_build++; continue; }
106
+ if (SENSITIVE.test(p)) { skipped.sensitive.push(p); continue; }
107
+ if (LOCKFILES.has(basename(p))) { skipped.lockfiles++; continue; }
108
+ if (!isText(p) || /\.min\.(js|css)$/i.test(p) || /\.map$/i.test(p)) { if (/\.min\.(js|css)$/i.test(p)) skipped.minified++; else skipped.not_source++; continue; }
109
+ let buf;
110
+ try { const st = statSync(join(root, p)); if (st.size > limits.perFile) { skipped.too_large.push(p); continue; } buf = readFileSync(join(root, p)); } catch { continue; }
111
+ if (buf.includes(0)) { skipped.binary++; continue; }
112
+ const raw = buf.toString("utf8");
113
+ const lines = raw.split("\n");
114
+ if (lines.length && raw.length / lines.length > 1500) { skipped.minified++; continue; }
115
+ if (files.length >= limits.files || total + raw.length > limits.total) { skipped.over_limit++; skipped.over_limit_examples.push(p); continue; }
116
+ const r = redact(raw);
117
+ redactions += r.redactions;
118
+ files.push({ path: p, text: r.text });
119
+ total += r.text.length;
120
+ }
121
+ const folders = {};
122
+ for (const f of files) { const top = f.path.includes("/") ? `${f.path.split("/")[0]}/` : "(root)"; folders[top] = (folders[top] ?? 0) + 1; }
123
+ const id = `bnd_${randomBytes(6).toString("hex")}`;
124
+ const summary = {
125
+ bundleId: id, root, project: opts.project ?? basename(root), files: files.length, characters: total,
126
+ folders: Object.entries(folders).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([folder, n]) => ({ folder, files: n })),
127
+ secretsHidden: redactions,
128
+ skipped: { ...skipped, sensitive: skipped.sensitive.slice(0, 20), too_large: skipped.too_large.slice(0, 20), over_limit_examples: skipped.over_limit_examples.slice(0, 10) },
129
+ kinds: files.reduce((k, f) => { const t = ["manifest", "readme", "code", "config", "tests", "docs", "docs", "scratch"][priority(f.path)]; k[t] = (k[t] ?? 0) + 1; return k; }, {}),
130
+ limits, include,
131
+ };
132
+ return { id, root, project: summary.project, files, summary };
133
+ }
134
+
135
+ export function summaryMarkdown(s) {
136
+ const sk = s.skipped;
137
+ const lines = [
138
+ `**Ready to share with Kroos: ${s.project}** (${s.root})`,
139
+ `- ${s.files} files, ${s.characters.toLocaleString("en-US")} characters${s.include.length ? ` (only ${s.include.join(", ")})` : ""}`,
140
+ `- Folders: ${s.folders.map((f) => `${f.folder} ${f.files}`).join(", ") || "none"}`,
141
+ `- What's in it: ${Object.entries(s.kinds ?? {}).map(([k, n]) => `${n} ${k}`).join(", ") || "nothing"} (application code first when a project doesn't fit)`,
142
+ `- Secrets hidden before sending: ${s.secretsHidden}`,
143
+ `- Left out: ${[sk.sensitive.length ? `${sk.sensitive.length} sensitive files (${sk.sensitive.slice(0, 5).join(", ")}${sk.sensitive.length > 5 ? "…" : ""})` : "", sk.lockfiles ? `${sk.lockfiles} lockfiles` : "", sk.binary ? `${sk.binary} binary files` : "", sk.minified ? `${sk.minified} minified files` : "", sk.too_large.length ? `${sk.too_large.length} files over ${s.limits.perFile.toLocaleString("en-US")} characters` : "", sk.over_limit ? `${sk.over_limit} files past the project limit of ${s.limits.files.toLocaleString("en-US")} files / ${s.limits.total.toLocaleString("en-US")} characters (e.g. ${sk.over_limit_examples.slice(0, 3).join(", ")}; share a folder with include to focus)` : "", sk.not_source ? `${sk.not_source} non-source files` : ""].filter(Boolean).join("; ") || "nothing"}`,
144
+ ];
145
+ return lines.join("\n");
146
+ }
147
+
148
+ /** Split files into request-sized batches; a file bigger than one batch is sent in parts (same path, in order). */
149
+ export function batches(files, maxBytes = BATCH_BYTES) {
150
+ const out = [];
151
+ let cur = [], size = 0;
152
+ const push = (f) => {
153
+ const n = JSON.stringify(f).length + 1;
154
+ if (cur.length && size + n > maxBytes) { out.push(cur); cur = []; size = 0; }
155
+ cur.push(f); size += n;
156
+ };
157
+ for (const f of files) {
158
+ if (JSON.stringify(f).length + 1 <= maxBytes) { push(f); continue; }
159
+ // Cut by characters so each part's JSON stays under the batch size (escaping can grow text up to 6x).
160
+ let text = f.text;
161
+ while (text.length) {
162
+ let take = Math.min(text.length, Math.floor(maxBytes / 2));
163
+ while (take > 256 && JSON.stringify({ path: f.path, text: text.slice(0, take) }).length + 1 > maxBytes) take = Math.floor(take * 0.7);
164
+ push({ path: f.path, text: text.slice(0, take) });
165
+ text = text.slice(take);
166
+ }
167
+ }
168
+ if (cur.length) out.push(cur);
169
+ return out;
170
+ }
171
+
172
+ /**
173
+ * Compressed batches: groups of files, gzipped and base64-encoded, each request body under maxBytes. Code
174
+ * compresses 4–6×, so a large project needs far fewer requests than plain JSON batches.
175
+ */
176
+ export function packedBatches(files, maxBytes = BATCH_BYTES) {
177
+ const pack = (group) => gzipSync(Buffer.from(JSON.stringify(group))).toString("base64");
178
+ const out = [];
179
+ const flush = (group) => {
180
+ if (!group.length) return;
181
+ const gz = pack(group);
182
+ if (gz.length + 300 <= maxBytes) { out.push({ gz, count: group.length }); return; }
183
+ if (group.length === 1) { for (const part of batches(group, Math.floor(maxBytes * 0.9))) flushRaw(part); return; }
184
+ const mid = Math.ceil(group.length / 2);
185
+ flush(group.slice(0, mid)); flush(group.slice(mid));
186
+ };
187
+ // A single file too big even compressed: split it into plain parts, then compress each.
188
+ const flushRaw = (group) => { const gz = pack(group); if (gz.length + 300 <= maxBytes) out.push({ gz, count: group.length }); else for (const f of group) for (const p of batches([f], Math.floor(maxBytes / 2))) out.push({ gz: pack(p), count: p.length }); };
189
+ let cur = [], raw = 0;
190
+ for (const f of files) {
191
+ const n = f.text.length + f.path.length + 16;
192
+ if (cur.length && raw + n > maxBytes * 4) { flush(cur); cur = []; raw = 0; }
193
+ cur.push(f); raw += n;
194
+ }
195
+ flush(cur);
196
+ return out;
197
+ }
198
+
199
+ /**
200
+ * What the person has to do to give the Code Advisor access. The AI app can't do it for them: the token is a
201
+ * credential, so it goes into their own terminal, never into the chat.
202
+ */
203
+ export function accessSteps(reason = "The Kroos Code Advisor isn't connected to a Kroos account yet.") {
204
+ return [
205
+ reason,
206
+ "To connect it (one time, about a minute):",
207
+ "1. Open https://kroos.ai/chat#/projects, sign in (a free account works), and choose Create pairing token (label it e.g. \"Claude Code\"; it's shown once).",
208
+ "2. In your own terminal (don't paste the token into this chat), re-add the advisor with it:",
209
+ " claude mcp remove kroos-code-advisor -s user; claude mcp add -s user kroos-code-advisor -e KROOS_PROJECT_TOKEN=<token> -- npx -y @kroos-dev/code-advisor",
210
+ "3. Restart Claude Code (or run /mcp and reconnect), then ask again.",
211
+ ].join("\n");
212
+ }
213
+ /** Plain-words reason for a refused request, with what to do about it. */
214
+ export function explainRefusal(status, j, what) {
215
+ const msg = j?.error?.message ?? `HTTP ${status}`;
216
+ if (status === 401) return accessSteps(`Kroos didn't accept the Code Advisor's token (${msg}).`);
217
+ if (status === 402 || status === 429) return `${what}: ${msg}${j?.error?.fix?.href ? ` (${new URL(j.error.fix.href, "https://kroos.ai").href})` : ""}`;
218
+ if (status === 413) return `${what}: ${msg} Share one folder at a time with bundle_project's include (e.g. ["src"]).`;
219
+ return `${what}: ${msg}`;
220
+ }
221
+ /** Is the token set, and does Kroos accept it? */
222
+ export async function checkAccess({ url, token, fetchImpl = fetch } = {}) {
223
+ if (!token) return { ok: false, reason: "no_token", message: accessSteps() };
224
+ try {
225
+ const res = await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify({ mode: "check" }) });
226
+ const j = await res.json().catch(() => ({}));
227
+ if (!res.ok) return { ok: false, reason: res.status === 401 ? "token_rejected" : "refused", message: explainRefusal(res.status, j, "Kroos refused the connection check") };
228
+ return { ok: true, app: j.app ?? null, limits: j.limits, message: `Connected to Kroos${j.app ? ` as "${j.app}"` : ""}. Projects you share appear in Kroos → Projects.` };
229
+ } catch (e) { return { ok: false, reason: "unreachable", message: `Couldn't reach Kroos at ${url} (${e.message}). Check the internet connection, or KROOS_CODE_URL / KROOS_ADVISOR_URL if you set them.` }; }
230
+ }
231
+
232
+ /** Send a confirmed bundle to Kroos in compressed batches; the last batch returns Kroos's review. */
233
+ export async function share(b, { url, token, question, conversationId, fetchImpl = fetch } = {}) {
234
+ if (!token) throw new Error(accessSteps());
235
+ if (!b.files.length) throw new Error("Nothing to share: no source files were found.");
236
+ const parts = packedBatches(b.files);
237
+ let uploadId;
238
+ for (let i = 0; i < parts.length; i++) {
239
+ const final = i === parts.length - 1;
240
+ const res = await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify({ project: b.project, gz: parts[i].gz, uploadId, final, source: "claude-code", ...(final ? { question, conversationId } : {}) }) });
241
+ const j = await res.json().catch(() => ({}));
242
+ if (!res.ok) throw new Error(explainRefusal(res.status, j, `Kroos couldn't take batch ${i + 1} of ${parts.length}`));
243
+ if (!final) { uploadId = j.uploadId; continue; }
244
+ return { ...j, batches: parts.length };
245
+ }
246
+ }
247
+
248
+ /** Read a few files from disk (current versions), hide secrets, and send them with a question. */
249
+ export async function review(rootIn, paths, { url, token, question, conversationId, fetchImpl = fetch } = {}) {
250
+ if (!token) throw new Error(accessSteps());
251
+ const root = resolve(rootIn ?? process.cwd());
252
+ const files = [];
253
+ let total = 0;
254
+ for (const p of (paths ?? []).slice(0, 20)) {
255
+ const rel = String(p).replace(/\\/g, "/").replace(/^\.?\/+/, "");
256
+ const abs = resolve(root, rel);
257
+ if (!abs.startsWith(root + sep)) throw new Error(`${p} is outside the project.`);
258
+ if (SENSITIVE.test(rel)) throw new Error(`${rel} looks like a secrets file; it isn't sent.`);
259
+ const raw = readFileSync(abs, "utf8");
260
+ const r = redact(raw);
261
+ total += r.text.length;
262
+ if (total > 50_000) throw new Error("Too much for one question (50,000 characters): send fewer or smaller files, or share the project.");
263
+ files.push({ path: rel, text: r.text });
264
+ }
265
+ if (!files.length) throw new Error("Name the files to review.");
266
+ const res = await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify({ mode: "review", files, question, conversationId, source: "claude-code" }) });
267
+ const j = await res.json().catch(() => ({}));
268
+ if (!res.ok) throw new Error(explainRefusal(res.status, j, "Kroos couldn't review those files"));
269
+ return j;
270
+ }
package/cli.mjs ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ // kroos-fingerprint CLI.
3
+ // node cli.mjs [repo-path] print the fingerprint (local only)
4
+ // node cli.mjs [repo-path] --json print JSON
5
+ // node cli.mjs [repo-path] --send after showing it, ask for confirmation, then send ONLY the fingerprint
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fingerprint, toMarkdown } from "./fingerprint.mjs";
8
+
9
+ const args = process.argv.slice(2);
10
+ const path = args.find((a) => !a.startsWith("--")) ?? process.cwd();
11
+ const fp = fingerprint(path);
12
+ if (args.includes("--json")) { console.log(JSON.stringify(fp, null, 2)); process.exit(0); }
13
+ console.log(toMarkdown(fp));
14
+ if (args.includes("--send")) {
15
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
16
+ const ok = (await rl.question("\nShare THIS fingerprint (no code) with the KroosAI advisor? [y/N] ")).trim().toLowerCase() === "y";
17
+ rl.close();
18
+ if (!ok) { console.log("Not sent."); process.exit(0); }
19
+ const url = process.env.KROOS_ADVISOR_URL ?? "https://api.kroos.ai/api/advisor/fingerprint";
20
+ // The advisor needs a KroosAI account: pair this machine in KroosAI → Projects and set KROOS_PROJECT_TOKEN.
21
+ const token = process.env.KROOS_PROJECT_TOKEN;
22
+ const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify({ fingerprint: fp, retain: false }) });
23
+ const j = await res.json();
24
+ console.log(res.ok ? `\n${j.markdown}` : `Advisor error: ${j.error?.message}`);
25
+ }
@@ -0,0 +1,135 @@
1
+ // Kroos Code Advisor — LOCAL Business Fingerprint (file 02 §2.14, file 03 §5).
2
+ // Runs on the developer's machine. Reads the repo, produces a non-code summary of what the
3
+ // product is and needs. It makes NO network requests. Secrets are counted, never copied.
4
+ // The developer reviews/edits the fingerprint; only a confirmed fingerprint may be sent.
5
+ import { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
6
+ import { join, relative, extname, basename } from "node:path";
7
+ import { classifyProduct, identifiersFrom } from "./productModel.mjs";
8
+
9
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "out", ".next", "vendor", ".venv", "venv", "__pycache__", "target", ".gradle", "Pods", "coverage", ".turbo", ".cache"]);
10
+ const CODE_EXT = new Set([".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".py", ".go", ".rb", ".php", ".java", ".kt", ".swift", ".dart", ".cs", ".sql", ".prisma", ".graphql", ".vue", ".svelte"]);
11
+ const MAX_FILES = 6000, MAX_BYTES = 400_000;
12
+
13
+ const SIGNATURES = {
14
+ payments: { stripe: /\bstripe\b/i, braintree: /braintree/i, square: /squareup|square\/web-sdk|@square\//i, adyen: /@adyen\//i, paddle: /@paddle|paddle\.(js|com)|paddle-sdk/i, lemonsqueezy: /lemonsqueezy|lemon-squeezy/i, paypal: /paypal/i, authorize_net: /authorizenet|authorize\.net/i, plaid: /\bplaid\b/i },
15
+ tax: { stripe_tax: /stripe\.tax|automatic_tax/i, avalara: /avalara|avatax/i, taxjar: /taxjar/i, anrok: /anrok/i },
16
+ auth: { nextauth: /next-auth|authjs/i, clerk: /@clerk\//i, auth0: /auth0/i, firebase_auth: /firebase\/auth|firebase-admin/i, supabase: /@supabase\//i, passport: /\bpassport\b/i, keycloak: /keycloak/i, cognito: /cognito/i, django_auth: /django\.contrib\.auth/i },
17
+ llm: { anthropic: /@anthropic-ai\/sdk|\banthropic\b/i, openai: /\bopenai\b/i, gemini: /@google\/(generative-ai|genai)|google-generativeai/i, langchain: /langchain/i, mistral: /mistralai/i, ollama: /ollama/i },
18
+ analytics: { posthog: /posthog/i, mixpanel: /mixpanel/i, segment: /@segment\//i, google_analytics: /gtag\(|googletagmanager/i, plausible: /plausible/i },
19
+ email: { resend: /\bresend\b/i, sendgrid: /sendgrid/i, nodemailer: /nodemailer/i, postmark: /postmark/i, ses: /client-ses|aws-sdk.*ses/i },
20
+ sms: { twilio: /twilio/i, africastalking: /africastalking/i, arkesel: /arkesel/i, termii: /termii/i },
21
+ database: { prisma: /@prisma\/client|prisma/i, postgres: /\bpg\b|postgres|psycopg/i, mysql: /mysql/i, mongodb: /mongoose|mongodb/i, sqlite: /sqlite/i, firestore: /firestore/i, supabase_db: /@supabase\/supabase-js/i },
22
+ monitoring: { sentry: /@sentry\/|sentry_sdk/i, datadog: /datadog|dd-trace/i, opentelemetry: /opentelemetry/i },
23
+ ratelimit: { ratelimit: /rate-?limit|ratelimit|throttl/i },
24
+ };
25
+ const FRAMEWORKS = { "Next.js": /"next"\s*:/, React: /"react"\s*:/, Vue: /"vue"\s*:/, Svelte: /"svelte"\s*:/, Express: /"express"\s*:/, Fastify: /"fastify"\s*:/, NestJS: /"@nestjs\/core"/, Django: /django/i, FastAPI: /fastapi/i, Flask: /flask/i, Laravel: /laravel/i, Rails: /\brails\b/, Flutter: /flutter:/, "React Native": /"react-native"\s*:/, "Spring Boot": /spring-boot/, Go: /^module /m };
26
+
27
+ const MODEL_HINTS = {
28
+ multi_tenant: /\b(organization_id|org_id|tenant_id|workspace_id|team_id)\b/i,
29
+ seats: /\b(seats?|member_count|max_users)\b/i,
30
+ subscriptions: /\b(subscription|plan_id|billing_cycle|trial_ends|entitlement)/i,
31
+ usage_metering: /\b(usage_events?|meter(ed)?|usage_record|credits?_balance|quota)\b/i,
32
+ marketplace: /\b(payout|seller|vendor_id|connect(ed)?_account|split_payment|commission)\b/i,
33
+ webhooks: /\bwebhooks?\b/i,
34
+ webhook_verification: /constructEvent|verify_?signature|stripe-signature|verif(y|ied)[-_ ]?webhook|hmac/i,
35
+ invoices: /\binvoices?\b/i,
36
+ tax: /\b(vat|sales_tax|tax_rate|tax_id)\b/i,
37
+ dunning: /\b(dunning|past_due|payment_failed|retry_payment)\b/i,
38
+ feature_flags: /\b(feature_?flags?|launchdarkly|unleash)\b/i,
39
+ };
40
+ const DATA_CATEGORIES = {
41
+ personal: /\b(email|phone|first_name|last_name|address|date_of_birth|dob)\b/i,
42
+ payment_cards: /\b(card_number|pan|cvv|cvc)\b/i,
43
+ health: /\b(patient|diagnosis|prescription|medical_record|hipaa|ehr)\b/i,
44
+ minors: /\b(child|minor|guardian|parental_consent|age_verification)\b/i,
45
+ education: /\b(student|grade|transcript|enrollment)\b/i,
46
+ financial: /\b(balance|ledger|wallet|loan|kyc|bvn)\b/i,
47
+ location: /\b(latitude|longitude|geolocation|gps)\b/i,
48
+ };
49
+ const SECRET_PATTERNS = [/sk_live_[0-9a-zA-Z]{10,}/, /sk-ant-[A-Za-z0-9_-]{20,}/, /sk-[A-Za-z0-9]{32,}/, /AKIA[0-9A-Z]{16}/, /-----BEGIN (RSA |EC )?PRIVATE KEY-----/, /xox[baprs]-[0-9A-Za-z-]{10,}/, /ghp_[0-9A-Za-z]{30,}/, /sk_test_[0-9a-zA-Z]{10,}/, /kroos_sk_[A-Za-z0-9_-]{20,}/];
50
+ const CURRENCIES = ["USD", "CAD", "EUR", "GBP", "MXN"];
51
+
52
+ function walk(root) {
53
+ const files = [];
54
+ const stack = [root];
55
+ while (stack.length && files.length < MAX_FILES) {
56
+ const dir = stack.pop();
57
+ let entries = [];
58
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
59
+ for (const e of entries) {
60
+ if (e.name.startsWith(".") && ![".env.example"].includes(e.name) && e.isDirectory()) continue;
61
+ const p = join(dir, e.name);
62
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) stack.push(p); }
63
+ else files.push(p);
64
+ }
65
+ }
66
+ return files;
67
+ }
68
+
69
+ const read = (p) => { try { const s = statSync(p); return s.size <= MAX_BYTES ? readFileSync(p, "utf8") : ""; } catch { return ""; } };
70
+
71
+ export function fingerprint(root = process.cwd()) {
72
+ if (!existsSync(root)) throw new Error(`Path not found: ${root}`);
73
+ const files = walk(root);
74
+ const manifests = files.filter((f) => ["package.json", "requirements.txt", "pyproject.toml", "go.mod", "composer.json", "pubspec.yaml", "Gemfile", "pom.xml", "build.gradle", "build.gradle.kts", "Cargo.toml"].includes(basename(f)));
75
+ const manifestText = manifests.map(read).join("\n");
76
+ const code = files.filter((f) => CODE_EXT.has(extname(f)));
77
+ const languages = {};
78
+ for (const f of code) languages[extname(f)] = (languages[extname(f)] ?? 0) + 1;
79
+
80
+ const found = Object.fromEntries(Object.keys(SIGNATURES).map((k) => [k, new Set()]));
81
+ const model = Object.fromEntries(Object.keys(MODEL_HINTS).map((k) => [k, 0]));
82
+ const data = Object.fromEntries(Object.keys(DATA_CATEGORIES).map((k) => [k, 0]));
83
+ const currencies = new Set();
84
+ let secretFiles = 0;
85
+ const identifiers = [];
86
+ for (const [cat, sigs] of Object.entries(SIGNATURES)) for (const [name, re] of Object.entries(sigs)) if (re.test(manifestText)) found[cat].add(name);
87
+ for (const f of code.concat(files.filter((x) => /\.(env\.example|ya?ml|json|toml)$/i.test(x) && !/package-lock|yarn\.lock|pnpm-lock/.test(x))).slice(0, 4000)) {
88
+ const t = read(f);
89
+ if (!t) continue;
90
+ // Integrations count only when actually imported (not merely mentioned in strings or docs).
91
+ const imports = t.split(/\r?\n/).filter((l) => /^\s*(import\s|from\s+\S+\s+import|export\s.+\sfrom\s|use\s|require\s|using\s)|\brequire\(\s*['"]|\bimport\(\s*['"]/.test(l)).join("\n");
92
+ if (imports) for (const [cat, sigs] of Object.entries(SIGNATURES)) for (const [name, re] of Object.entries(sigs)) if (re.test(imports)) found[cat].add(name);
93
+ for (const [k, re] of Object.entries(MODEL_HINTS)) if (re.test(t)) model[k]++;
94
+ for (const [k, re] of Object.entries(DATA_CATEGORIES)) if (re.test(t)) data[k]++;
95
+ for (const c of CURRENCIES) if (new RegExp(`['"\`]${c}['"\`]`).test(t)) currencies.add(c);
96
+ if (SECRET_PATTERNS.some((re) => re.test(t))) secretFiles++;
97
+ if (/.(prisma|sql|ts|py|rb|go|java|kt|php|cs)$/i.test(f) && identifiers.length < 2000) identifiers.push(...identifiersFrom(t));
98
+ }
99
+ const frameworks = Object.entries(FRAMEWORKS).filter(([, re]) => re.test(manifestText)).map(([n]) => n);
100
+ const has = (n) => files.some((f) => basename(f).toLowerCase() === n.toLowerCase());
101
+ const tests = files.some((f) => /(^|[\\/])(tests?|__tests__|spec)([\\/])|\.(test|spec)\.[a-z]+$/i.test(relative(root, f)));
102
+ const privacy = files.some((f) => /privacy/i.test(basename(f)));
103
+
104
+ const flags = (o) => Object.entries(o).filter(([, v]) => v > 0).map(([k]) => k);
105
+ const fp = {
106
+ kroos_fingerprint: "0.1",
107
+ generated_locally: true,
108
+ stack: { languages: Object.entries(languages).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([e, n]) => `${e} (${n})`), frameworks, deploy: ["Dockerfile", "vercel.json", "fly.toml", "netlify.toml", "app.yaml", "serverless.yml"].filter(has) },
109
+ integrations: Object.fromEntries(Object.entries(found).map(([k, v]) => [k, [...v]])),
110
+ product_model: flags(model),
111
+ product_type: classifyProduct(identifiers), // M10 (local model; identifiers never leave the machine)
112
+ data_categories: flags(data),
113
+ currencies: [...currencies],
114
+ launch_signals: { tests, error_monitoring: found.monitoring.size > 0, rate_limiting: found.ratelimit.size > 0, webhook_signature_verification: model.webhook_verification > 0, privacy_page: privacy },
115
+ secrets_detected_in_files: secretFiles,
116
+ size: { files: files.length, code_files: code.length },
117
+ notes: secretFiles ? ["Secret-looking values were found in some files. They are NOT included here. Rotate them and move them to environment variables."] : [],
118
+ };
119
+ return fp;
120
+ }
121
+
122
+ export function toMarkdown(fp) {
123
+ const list = (a) => (a && a.length ? a.join(", ") : "none detected");
124
+ return `# Business Fingerprint (generated locally — review before sharing)
125
+ - **Stack:** ${list(fp.stack.frameworks)} · ${list(fp.stack.languages)} · deploy: ${list(fp.stack.deploy)}
126
+ - **Payments:** ${list(fp.integrations.payments)} · **Auth:** ${list(fp.integrations.auth)} · **AI/LLM:** ${list(fp.integrations.llm)}
127
+ - **Email/SMS:** ${list([...fp.integrations.email, ...fp.integrations.sms])} · **Analytics:** ${list(fp.integrations.analytics)} · **DB:** ${list(fp.integrations.database)}
128
+ - **Product type (M10, local):** ${fp.product_type?.label ?? "unknown"} (${Math.round((fp.product_type?.confidence ?? 0) * 100)}%)
129
+ - **Product model signals:** ${list(fp.product_model)}
130
+ - **Data categories:** ${list(fp.data_categories)}
131
+ - **Currencies in code:** ${list(fp.currencies)}
132
+ - **Launch signals:** tests ${fp.launch_signals.tests ? "✓" : "✗"}, error monitoring ${fp.launch_signals.error_monitoring ? "✓" : "✗"}, rate limiting ${fp.launch_signals.rate_limiting ? "✓" : "✗"}, webhook verification ${fp.launch_signals.webhook_signature_verification ? "✓" : "✗"}, privacy page ${fp.launch_signals.privacy_page ? "✓" : "✗"}
133
+ ${fp.secrets_detected_in_files ? `- ⚠ Secret-looking values in ${fp.secrets_detected_in_files} file(s) (not included).` : ""}
134
+ No source code is included. Nothing has been sent anywhere.`;
135
+ }
package/mcp.mjs ADDED
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ // kroos-fingerprint — local MCP server (stdio, JSON-RPC 2.0). Zero dependencies.
3
+ // Tools:
4
+ // fingerprint_repo { path } → local only, no network
5
+ // get_business_advice { fingerprint, confirmed } → sends ONLY the fingerprint, and only when confirmed=true
6
+ // bundle_project { path, include? } → local only: collects source files, hides secrets, shows a summary
7
+ // share_project { bundleId, confirmed } → sends that bundle's code to Kroos for review, only when confirmed=true
8
+ // review_files { path, files, question, confirmed } → re-reads a few files from disk and asks Kroos about them
9
+ // Code goes straight from this process to Kroos: it never passes through the AI app's context.
10
+ // The advisor is advisory: it never writes or changes code.
11
+ // Add to an MCP client, e.g.: { "command": "node", "args": ["<path>/tools/kroos-fingerprint/mcp.mjs"] }
12
+ import { createInterface } from "node:readline";
13
+ import { readFileSync } from "node:fs";
14
+ import { fingerprint, toMarkdown } from "./fingerprint.mjs";
15
+ import { bundle, summaryMarkdown, share, review, checkAccess } from "./bundle.mjs";
16
+
17
+ const ADVISOR_URL = process.env.KROOS_ADVISOR_URL ?? "https://api.kroos.ai/api/advisor/fingerprint";
18
+ // Optional: a pairing token from KroosAI → Projects. With it, confirmed advice becomes a Project you
19
+ // can continue on the web or phone. Only the fingerprint (never code) is sent.
20
+ const PROJECT_TOKEN = process.env.KROOS_PROJECT_TOKEN;
21
+ const PROJECT_URL = process.env.KROOS_PROJECT_URL ?? ADVISOR_URL.replace(/\/api\/advisor\/fingerprint$/, "/api/projects/ide");
22
+ const CODE_URL = process.env.KROOS_CODE_URL ?? ADVISOR_URL.replace(/\/api\/advisor\/fingerprint$/, "/api/projects/code");
23
+ const bundles = new Map(); // bundleId → bundle (this process only; never written to disk)
24
+ // Versions negotiated by "initialize" (newest first). Newer clients that ask for one we don't know get the
25
+ // newest of these; 2026-07-28 clients use server/discover, which this stdio server doesn't need.
26
+ const VERSION = (() => { try { return JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version; } catch { return "0.0.0"; } })();
27
+ const SUPPORTED = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
28
+
29
+ const TOOLS = [
30
+ {
31
+ name: "check_access",
32
+ description: "Check whether the Kroos Code Advisor can share code with Kroos: is it paired with a Kroos account, and does Kroos accept the token. If not, it returns the exact steps for the user to connect it (they do it themselves; never ask them to paste a token into the chat). Call this first when the user wants a code review, or after any access error.",
33
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
34
+ },
35
+ {
36
+ name: "fingerprint_repo",
37
+ description: "Analyze a code repository LOCALLY and return a Business Fingerprint (stack, payments, auth, AI SDKs, product model, data categories, launch gaps). No code and no secrets are included, and nothing leaves the machine. Show it to the user for review.",
38
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "Absolute path to the repository root" } }, required: ["path"], additionalProperties: false },
39
+ },
40
+ {
41
+ name: "get_business_advice",
42
+ description: "Send a user-CONFIRMED Business Fingerprint (not code) to the KroosAI advisor and get advice on payments, billing, pricing, compliance, AI cost and launch readiness. Only call after the user has reviewed the fingerprint and agreed to share it. KroosAI gives advice; it does not write code.",
43
+ inputSchema: { type: "object", properties: { fingerprint: { type: "object" }, confirmed: { type: "boolean", description: "true only if the user explicitly approved sharing this fingerprint" }, retain: { type: "boolean", description: "Let KroosAI keep the fingerprint (default false)" }, project: { type: "string", description: "Project name shown in KroosAI → Projects (e.g. the repo folder name)" } }, required: ["fingerprint", "confirmed"], additionalProperties: false },
44
+ },
45
+ {
46
+ name: "bundle_project",
47
+ description: "Collect a project's source files LOCALLY for a Kroos code review, and return a summary (file count, folders, what was left out, secrets hidden). Respects .gitignore; skips dependencies, builds, lockfiles, binaries, minified files, .env files and keys; hides secrets. Nothing is sent. Show the summary to the user and ask whether to share these files with Kroos.",
48
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "Absolute path to the project root" }, include: { type: "array", items: { type: "string" }, description: "Optional: only these folders or files, relative to the root (e.g. [\"src\", \"package.json\"])" }, project: { type: "string", description: "Project name shown in Kroos → Projects (default: the folder name)" } }, required: ["path"], additionalProperties: false },
49
+ },
50
+ {
51
+ name: "share_project",
52
+ description: "Send a bundle from bundle_project to Kroos and get Kroos's review of the whole project: what it does, how it's built and scales, security, bug and performance risks, and what it means for the business. The project appears in Kroos → Projects; Kroos keeps what it learns, not the code. Only call after the user has seen the bundle summary and said yes. Kroos explains and plans; it never writes code.",
53
+ inputSchema: { type: "object", properties: { bundleId: { type: "string" }, confirmed: { type: "boolean", description: "true only if the user explicitly approved sharing these files" }, question: { type: "string", description: "Optional: what to focus on (e.g. 'Is checkout secure?')" }, conversationId: { type: "string", description: "Optional: continue an earlier Kroos project conversation" } }, required: ["bundleId", "confirmed"], additionalProperties: false },
54
+ },
55
+ {
56
+ name: "review_files",
57
+ description: "Ask Kroos about specific files: they're re-read from disk now (so Kroos sees the current version), secrets hidden, and sent with the question (up to 20 files, 50,000 characters). Use for follow-ups after share_project, passing its conversationId: Kroos keeps its review of the project, not the code, so send the files a question is about. Only call with the user's OK to send these files.",
58
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "Absolute path to the project root" }, files: { type: "array", items: { type: "string" }, description: "File paths relative to the root" }, question: { type: "string" }, conversationId: { type: "string" }, confirmed: { type: "boolean", description: "true only if the user approved sending these files" } }, required: ["path", "files", "question", "confirmed"], additionalProperties: false },
59
+ },
60
+ ];
61
+
62
+ const send = (msg) => process.stdout.write(JSON.stringify(msg) + "\n");
63
+ const result = (id, r) => send({ jsonrpc: "2.0", id, result: r });
64
+ const error = (id, code, message) => send({ jsonrpc: "2.0", id, error: { code, message } });
65
+ const text = (t, structured) => ({ content: [{ type: "text", text: t }], ...(structured ? { structuredContent: structured } : {}) });
66
+
67
+ async function callTool(name, args) {
68
+ if (name === "check_access") {
69
+ const a = await checkAccess({ url: CODE_URL, token: PROJECT_TOKEN });
70
+ return { ...text(a.message, { ok: a.ok, reason: a.reason ?? null, app: a.app ?? null }), ...(a.ok ? {} : { isError: true }) };
71
+ }
72
+ if (name === "fingerprint_repo") {
73
+ const fp = fingerprint(args.path);
74
+ return text(`${toMarkdown(fp)}\n\nAsk the user to review this. Only call get_business_advice after they confirm.`, fp);
75
+ }
76
+ if (name === "get_business_advice") {
77
+ if (args.confirmed !== true) return { ...text("Not sent: the user has not confirmed sharing the fingerprint."), isError: true };
78
+ const fp = args.fingerprint ?? {};
79
+ if (JSON.stringify(fp).length > 50_000) return { ...text("Fingerprint too large; it should be a short summary, not code."), isError: true };
80
+ const project = typeof args.project === "string" ? args.project : undefined;
81
+ const res = PROJECT_TOKEN
82
+ ? await fetch(PROJECT_URL, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${PROJECT_TOKEN}` }, body: JSON.stringify({ fingerprint: fp, project }) })
83
+ : await fetch(ADVISOR_URL, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fingerprint: fp, retain: args.retain === true }) });
84
+ const j = await res.json().catch(() => ({}));
85
+ if (!res.ok) return { ...text(`Advisor error: ${j.error?.message ?? res.status}`), isError: true };
86
+ return text(j.markdown ?? JSON.stringify(j), j);
87
+ }
88
+ if (name === "bundle_project") {
89
+ // The person's plan decides how big a project can be (Kroos tells us at the access check).
90
+ const access = await checkAccess({ url: CODE_URL, token: PROJECT_TOKEN });
91
+ const plan = access.ok && access.limits?.project ? { files: access.limits.project.files, total: access.limits.project.total } : undefined;
92
+ const b = bundle(args.path, { include: Array.isArray(args.include) ? args.include : [], project: typeof args.project === "string" && args.project.trim() ? args.project.trim() : undefined, ...(plan ? { limits: plan } : {}) });
93
+ bundles.set(b.id, b);
94
+ if (bundles.size > 10) bundles.delete(bundles.keys().next().value);
95
+ if (!access.ok) return text(`${summaryMarkdown(b.summary)}\n\nNothing has been sent. Before these files can be shared, the advisor needs access:\n\n${access.message}\n\nShow the user these steps; once they've done them, run bundle_project again.`, { ...b.summary, access: access.reason });
96
+ return text(`${summaryMarkdown(b.summary)}\n\nNothing has been sent. Ask the user whether to share these files with Kroos; only call share_project (bundleId ${b.id}) with confirmed=true after they say yes.`, b.summary);
97
+ }
98
+ if (name === "share_project") {
99
+ if (args.confirmed !== true) return { ...text("Not sent: the user has not confirmed sharing these files."), isError: true };
100
+ const b = bundles.get(args.bundleId);
101
+ if (!b) return { ...text("That bundle isn't here any more: run bundle_project again."), isError: true };
102
+ try {
103
+ const j = await share(b, { url: CODE_URL, token: PROJECT_TOKEN, question: args.question, conversationId: args.conversationId });
104
+ bundles.delete(b.id);
105
+ const report = (j.documents ?? []).find((d) => /code reading report/i.test(d.title ?? ""));
106
+ const reply = (j.reply ?? "").trim() || (report ? "Kroos read the project; its report is below." : "Kroos received the project but didn't return a review this time. Ask for it with ask_kroos in the same conversation (pass this conversationId); it answers from its review of the code.");
107
+ return text(`${reply.replace(" The full report is in the card.", report ? " The full report is below." : "")}${report ? `\n\n---\n${report.markdown}` : ""}\n\n(Shared ${j.files} files in ${j.batches} part${j.batches > 1 ? "s" : ""}. conversationId: ${j.conversationId}; open Kroos → Projects to continue anywhere.)`, { conversationId: j.conversationId, project: j.project, files: j.files, sources: j.sources, allowance: j.allowance });
108
+ } catch (e) { return { ...text(e.message), isError: true }; }
109
+ }
110
+ if (name === "review_files") {
111
+ if (args.confirmed !== true) return { ...text("Not sent: the user has not approved sending these files."), isError: true };
112
+ try {
113
+ const j = await review(args.path, args.files, { url: CODE_URL, token: PROJECT_TOKEN, question: args.question, conversationId: args.conversationId });
114
+ const report = (j.documents ?? []).find((d) => /code reading report/i.test(d.title ?? ""));
115
+ return text(`${((j.reply ?? "").trim() || "Kroos didn't return an answer this time; try again in a moment.").replace(" The full report is in the card.", report ? " The full report is below." : "")}${report ? `\n\n---\n${report.markdown}` : ""}\n\n(conversationId: ${j.conversationId})`, { conversationId: j.conversationId, sources: j.sources, allowance: j.allowance });
116
+ } catch (e) { return { ...text(e.message), isError: true }; }
117
+ }
118
+ throw Object.assign(new Error(`Unknown tool ${name}`), { code: -32602 });
119
+ }
120
+
121
+ createInterface({ input: process.stdin }).on("line", async (line) => {
122
+ let msg;
123
+ try { msg = JSON.parse(line); } catch { return error(null, -32700, "Parse error"); }
124
+ const { id, method, params } = msg;
125
+ try {
126
+ if (method === "initialize") {
127
+ const v = SUPPORTED.includes(params?.protocolVersion) ? params.protocolVersion : SUPPORTED[0];
128
+ return result(id, { protocolVersion: v, capabilities: { tools: {} }, serverInfo: { name: "kroos-code-advisor", version: VERSION }, instructions: "Kroos Code Advisor. check_access: is it connected to the user's Kroos account (if not, show the user the steps it returns; they pair it themselves). fingerprint_repo + get_business_advice: business advice from a summary, never code. bundle_project + share_project: a full Kroos code review of the project, sending code only after the user approves the bundle summary; review_files for follow-ups about specific files. Kroos explains and plans; it never writes code." });
129
+ }
130
+ if (method === "ping") return result(id, {});
131
+ if (method === "tools/list") return result(id, { tools: TOOLS });
132
+ if (method === "tools/call") return result(id, await callTool(params?.name, params?.arguments ?? {}));
133
+ if (id === undefined) return; // notification
134
+ return error(id, -32601, `Method not found: ${method}`);
135
+ } catch (e) {
136
+ return error(id, e.code ?? -32603, e.message);
137
+ }
138
+ });
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@kroos-dev/code-advisor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Kroos Code Advisor for Claude Code and IDEs: business advice from a project summary, and full Kroos code reviews that share code only after you approve it, with secrets hidden on your machine.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/kroosAI/kroos.git",
10
+ "directory": "tools/kroos-fingerprint"
11
+ },
12
+ "homepage": "https://dev.kroos.ai/mcp",
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "bin": {
17
+ "code-advisor": "mcp.mjs",
18
+ "kroos-fingerprint": "cli.mjs"
19
+ },
20
+ "files": [
21
+ "mcp.mjs",
22
+ "cli.mjs",
23
+ "bundle.mjs",
24
+ "fingerprint.mjs",
25
+ "productModel.mjs",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "keywords": [
30
+ "kroos",
31
+ "mcp",
32
+ "claude-code",
33
+ "code-review",
34
+ "model-context-protocol"
35
+ ]
36
+ }
@@ -0,0 +1,45 @@
1
+ // M10 — local product-type model for the Code Advisor (runs on the developer's machine, no network).
2
+ // A tiny multinomial Naive Bayes over identifiers found in the repo (table/model/route/file names),
3
+ // trained from built-in examples. It complements the keyword signals with a probabilistic guess of
4
+ // WHAT is being built. Only the label + confidence go into the fingerprint, never identifiers.
5
+
6
+ const TRAIN = {
7
+ booking: "appointment booking slot availability calendar schedule reservation provider service reminder timeslot clinic doctor patient",
8
+ marketplace: "seller buyer listing vendor payout commission order dispute review escrow storefront connect_account",
9
+ ecommerce: "product cart checkout order inventory sku shipment coupon catalog variant wishlist",
10
+ saas: "workspace tenant organization plan subscription seat invoice billing usage entitlement team member role dashboard",
11
+ fintech: "wallet ledger transaction transfer balance kyc loan repayment account card payout remittance",
12
+ education: "course lesson student enrollment grade teacher classroom quiz assignment curriculum",
13
+ logistics: "shipment driver vehicle route delivery tracking dispatch stop pickup fleet",
14
+ content: "post article author comment category tag feed media subscriber newsletter",
15
+ ai_app: "conversation message prompt completion embedding vector chunk knowledge agent tool model",
16
+ };
17
+
18
+ const tok = (s) => s.toLowerCase().replace(/([a-z])([A-Z])/g, "$1 $2").split(/[^a-z]+/).filter((w) => w.length > 2).map((w) => w.replace(/(ies)$/, "y").replace(/s$/, ""));
19
+
20
+ const model = (() => {
21
+ const counts = {}, totals = {}, vocab = new Set();
22
+ for (const [label, text] of Object.entries(TRAIN)) {
23
+ counts[label] = {}; totals[label] = 0;
24
+ for (const w of tok(text)) { counts[label][w] = (counts[label][w] ?? 0) + 1; totals[label]++; vocab.add(w); }
25
+ }
26
+ return { counts, totals, vocab };
27
+ })();
28
+
29
+ export function classifyProduct(identifiers) {
30
+ const words = identifiers.flatMap(tok).filter((w) => model.vocab.has(w));
31
+ if (words.length < 3) return { label: "unknown", confidence: 0 };
32
+ const V = model.vocab.size, labels = Object.keys(TRAIN);
33
+ const logs = labels.map((l) => words.reduce((s, w) => s + Math.log(((model.counts[l][w] ?? 0) + 1) / (model.totals[l] + V)), Math.log(1 / labels.length)));
34
+ const max = Math.max(...logs), exps = logs.map((x) => Math.exp(x - max)), sum = exps.reduce((a, b) => a + b, 0);
35
+ const i = exps.indexOf(Math.max(...exps));
36
+ return { label: labels[i], confidence: Math.round((exps[i] / sum) * 100) / 100 };
37
+ }
38
+
39
+ /** Pull identifiers (not code) from schema-ish files: table/model/class/route names. */
40
+ export function identifiersFrom(text) {
41
+ const ids = [];
42
+ for (const m of text.matchAll(/\b(?:model|table|class|interface|type|enum|create table(?: if not exists)?)\s+["'`]?([A-Za-z_][A-Za-z0-9_]{2,40})/gi)) ids.push(m[1]);
43
+ for (const m of text.matchAll(/["'`]\/(?:api\/)?([a-z][a-z0-9_-]{2,30})/g)) ids.push(m[1]);
44
+ return ids.slice(0, 200);
45
+ }