@point-seven-studio/jq-groundcrew 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,604 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/groundcrew-cli.ts
4
+ import { existsSync as existsSync2, writeFileSync } from "fs";
5
+ import { createServer } from "http";
6
+ import path2 from "path";
7
+
8
+ // src/groundcrew-core.ts
9
+ var DOCS = "https://code.claude.com/docs/en";
10
+ var MEMORY_LINE_TARGET = 200;
11
+ var MEMORY_LINE_FAIL = 400;
12
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
13
+ var all = (files, pick) => files.flatMap(pick);
14
+ function deniesSecrets(rule) {
15
+ return /^Read\(/.test(rule) && /\.env|secret|credential|\.pem|\.key\b|id_rsa/i.test(rule);
16
+ }
17
+ function allowsEveryCommand(rule) {
18
+ return /^Bash(\(\s*(\*|:\*|\*\*)?\s*\))?$/.test(rule.trim());
19
+ }
20
+ function memoryChecks(facts) {
21
+ const source = `${DOCS}/memory.md`;
22
+ if (!facts.memory.length) {
23
+ return [
24
+ {
25
+ id: "memory-exists",
26
+ group: "setup",
27
+ title: "Project instructions",
28
+ status: "warn",
29
+ detail: "No CLAUDE.md or AGENTS.md was found for this project.",
30
+ fix: "Run /init to create one, then cut it down to the lines that prevent a mistake.",
31
+ source
32
+ }
33
+ ];
34
+ }
35
+ const checks = facts.memory.map((file) => {
36
+ const status = file.lines > MEMORY_LINE_FAIL ? "fail" : file.lines > MEMORY_LINE_TARGET ? "warn" : "pass";
37
+ return {
38
+ id: `memory-length:${file.label}`,
39
+ group: "setup",
40
+ title: `${file.label} length`,
41
+ status,
42
+ detail: status === "pass" ? `${plural(file.lines, "line")}, under the ${MEMORY_LINE_TARGET}-line target.` : `${plural(file.lines, "line")}. The docs say to target under ${MEMORY_LINE_TARGET} lines per file, because a longer file uses more context and is followed less well. Every session loads all of it.`,
43
+ fix: status === "pass" ? "" : `For each line, ask whether removing it would cause a mistake. Move what only some tasks need into a skill or into ${facts.ruleFiles ? "the existing" : "a"} .claude/rules/ file, and turn a rule that must happen every time into a hook.`,
44
+ source
45
+ };
46
+ });
47
+ const index = facts.autoMemoryIndex;
48
+ if (index) {
49
+ const over = index.lines > 200 || index.bytes > 25e3;
50
+ checks.push({
51
+ id: "auto-memory-index",
52
+ group: "setup",
53
+ title: "Auto memory index",
54
+ status: over ? "warn" : "pass",
55
+ detail: over ? `MEMORY.md is ${plural(index.lines, "line")} and ${Math.round(index.bytes / 1e3)} KB. Only the first 200 lines or 25 KB are loaded, so the rest is never read.` : `MEMORY.md is ${plural(index.lines, "line")}, inside what is loaded.`,
56
+ fix: over ? "Shorten the index, or merge entries, so the ones that matter are in the part that loads." : "",
57
+ source
58
+ });
59
+ }
60
+ return checks;
61
+ }
62
+ function automationChecks(facts) {
63
+ const events = [...new Set(all(facts.settings, (f) => f.hookEvents))].sort();
64
+ const allow = all(facts.settings, (f) => f.allow);
65
+ const skills = facts.skills.project + facts.skills.user;
66
+ const checks = [
67
+ {
68
+ id: "hooks",
69
+ group: "setup",
70
+ title: "Hooks",
71
+ status: events.length ? "pass" : "warn",
72
+ detail: events.length ? `Hooks run on: ${events.join(", ")}.` : "No hook is configured, so nothing runs automatically.",
73
+ fix: events.length ? "" : "Our suggestion: a rule that must happen every time, such as formatting or a lint run after an edit, belongs in a hook. A line in CLAUDE.md is advice that can be skipped.",
74
+ source: `${DOCS}/hooks.md`
75
+ },
76
+ {
77
+ id: "allow-rules",
78
+ group: "setup",
79
+ title: "Pre-approved commands",
80
+ status: allow.length ? "pass" : "warn",
81
+ detail: allow.length ? `${plural(allow.length, "allow rule")} across ${plural(facts.settings.filter((f) => f.allow.length).length, "settings file")}.` : "No allow rule is set, so every command asks for approval.",
82
+ fix: allow.length ? "" : "Use /permissions to allow the commands you trust, such as your test and lint commands.",
83
+ source: `${DOCS}/permissions.md`
84
+ },
85
+ {
86
+ id: "skills",
87
+ group: "setup",
88
+ title: "Skills",
89
+ status: "info",
90
+ detail: skills ? `${plural(facts.skills.project, "project skill")} and ${plural(facts.skills.user, "user skill")}.` : "No skill is defined. A skill holds knowledge that only some tasks need, so it stays out of every other session.",
91
+ fix: "",
92
+ source: `${DOCS}/skills.md`
93
+ }
94
+ ];
95
+ if (facts.legacyCommands) {
96
+ checks.push({
97
+ id: "legacy-commands",
98
+ group: "setup",
99
+ title: "Custom commands",
100
+ status: "info",
101
+ detail: `${plural(facts.legacyCommands, "file")} in .claude/commands/. They still work. The docs merge commands into skills and prefer a skill for new work.`,
102
+ fix: "",
103
+ source: `${DOCS}/skills.md`
104
+ });
105
+ }
106
+ checks.push({
107
+ id: "subagents-and-mcp",
108
+ group: "setup",
109
+ title: "Subagents and connected tools",
110
+ status: "info",
111
+ detail: `${plural(facts.subagents.project + facts.subagents.user, "subagent")}. ${plural(facts.mcpServers.project, "project MCP server")} and ${plural(facts.mcpServers.user, "user MCP server")}.`,
112
+ fix: "",
113
+ source: `${DOCS}/mcp.md`
114
+ });
115
+ return checks;
116
+ }
117
+ function guardrailChecks(facts) {
118
+ const files = facts.settings;
119
+ const deny = all(files, (f) => f.deny);
120
+ const secretRules = deny.filter(deniesSecrets);
121
+ const broad = all(files, (f) => f.allow.filter(allowsEveryCommand).map((rule) => `${rule} in ${f.label}`));
122
+ const modes = files.filter((f) => f.defaultMode).map((f) => ({ mode: f.defaultMode, label: f.label }));
123
+ const bypass = modes.find((m) => m.mode === "bypassPermissions");
124
+ const loose = modes.find((m) => m.mode === "dontAsk" || m.mode === "auto");
125
+ const sandboxOn = files.some((f) => f.sandboxEnabled === true);
126
+ const windows = facts.platform === "win32";
127
+ const reach = files.reduce((sum, f) => sum + f.additionalDirectories, 0);
128
+ const retention = files.map((f) => f.cleanupPeriodDays).find((d) => d !== null) ?? null;
129
+ const checks = [
130
+ {
131
+ id: "deny-secrets",
132
+ group: "guardrails",
133
+ title: "Secrets are off limits",
134
+ status: secretRules.length ? "pass" : facts.secretFiles.length ? "fail" : "warn",
135
+ detail: secretRules.length ? `${plural(secretRules.length, "deny rule")} cover secret files: ${secretRules.join(", ")}.` : facts.secretFiles.length ? `No deny rule covers secret files, and this project has ${facts.secretFiles.join(", ")}. The agent can read ${facts.secretFiles.length === 1 ? "it" : "them"}.` : "No deny rule covers secret files. None was found in the project, so nothing is exposed today.",
136
+ fix: secretRules.length ? "" : `Add deny rules to .claude/settings.json: ${facts.secretFiles.length ? facts.secretFiles.map((file) => `"Read(./${file})"`).join(", ") : '"Read(./.env)" and "Read(./secrets/**)", for example'}. A deny rule is checked before any allow rule.`,
137
+ source: `${DOCS}/permissions.md`
138
+ },
139
+ {
140
+ id: "broad-allow",
141
+ group: "guardrails",
142
+ title: "No blanket approval of shell commands",
143
+ status: broad.length ? "fail" : "pass",
144
+ detail: broad.length ? `These rules approve every shell command: ${broad.join("; ")}.` : "No allow rule approves every shell command.",
145
+ fix: broad.length ? "Replace the blanket rule with rules for the commands you trust." : "",
146
+ source: `${DOCS}/permissions.md`
147
+ },
148
+ {
149
+ id: "default-mode",
150
+ group: "guardrails",
151
+ title: "Permission mode",
152
+ status: bypass ? "fail" : loose ? "warn" : "pass",
153
+ detail: bypass ? `${bypass.label} sets the default mode to bypassPermissions, so nothing asks for approval.` : loose ? `${loose.label} sets the default mode to ${loose.mode}, which approves actions without asking.` : modes.length ? `Default mode: ${modes.map((m) => `${m.mode} (${m.label})`).join(", ")}.` : "No default mode is set, so the standard mode applies and actions ask for approval.",
154
+ fix: bypass ? "Use this mode only inside a container or a virtual machine that holds nothing you care about." : loose ? "Check that this is what you intend on a machine with real credentials." : "",
155
+ source: `${DOCS}/permissions.md`
156
+ },
157
+ {
158
+ id: "sandbox",
159
+ group: "guardrails",
160
+ title: "Sandbox",
161
+ status: sandboxOn ? "pass" : windows ? "info" : "warn",
162
+ detail: sandboxOn ? "The sandbox is enabled, so commands run inside OS-level limits." : windows ? "The sandbox is off. It is not supported on native Windows." : "The sandbox is off, which is the default. Commands run with your full access to files and the network.",
163
+ fix: sandboxOn || windows ? "" : 'Turn it on with /sandbox, or set "sandbox": { "enabled": true } in settings.',
164
+ source: `${DOCS}/sandboxing.md`
165
+ },
166
+ {
167
+ id: "reach",
168
+ group: "guardrails",
169
+ title: "Reach outside the project",
170
+ status: "info",
171
+ detail: reach ? `${reach} additional ${reach === 1 ? "directory" : "directories"} outside the project can be reached.` : "No additional directory is granted, so the agent works inside the project.",
172
+ fix: "",
173
+ source: `${DOCS}/permissions.md`
174
+ },
175
+ {
176
+ id: "retention",
177
+ group: "guardrails",
178
+ title: "Session records",
179
+ status: "info",
180
+ detail: `Session transcripts are kept for ${retention ?? 30} days${retention === null ? ", the default" : ""}. They are the record of what the agent did.`,
181
+ fix: "",
182
+ source: `${DOCS}/sessions.md`
183
+ }
184
+ ];
185
+ if (files.some((f) => f.scope === "managed")) {
186
+ checks.push({
187
+ id: "managed",
188
+ group: "guardrails",
189
+ title: "Managed settings",
190
+ status: "info",
191
+ detail: "A managed settings file is present. Its rules come first and a project cannot override them.",
192
+ fix: "",
193
+ source: `${DOCS}/managed-settings.md`
194
+ });
195
+ }
196
+ return checks;
197
+ }
198
+ function looksLikeACheck(command) {
199
+ return /\b(test|tests|jest|vitest|pytest|mocha|lint|eslint|ruff|tsc|typecheck|type-check|mypy|pyright|check|build|cargo (test|check|clippy)|go (test|vet))\b/i.test(command);
200
+ }
201
+ function verificationChecks(facts) {
202
+ const files = facts.settings;
203
+ const allowed = all(files, (f) => f.allow.filter((rule) => /^Bash\(/.test(rule) && looksLikeACheck(rule)));
204
+ const hooked = all(files, (f) => f.hookCommands.filter((h) => looksLikeACheck(h.command)));
205
+ const stopEvents = [...new Set(all(files, (f) => f.hookEvents.filter((event) => event === "Stop" || event === "SubagentStop")))].sort();
206
+ const unscoped = facts.subagentFiles.filter((agent) => !agent.limitsTools).map((agent) => agent.name);
207
+ const checks = [
208
+ {
209
+ id: "verify-command",
210
+ group: "verification",
211
+ title: "The agent can run your checks",
212
+ status: allowed.length || hooked.length ? "pass" : "warn",
213
+ detail: allowed.length || hooked.length ? `${plural(allowed.length, "allow rule")} and ${plural(hooked.length, "hook")} name a test, lint, type-check or build command.` : 'No allow rule and no hook names a test, lint, type-check or build command. Without a check it can run, the agent only has "looks done" to go on.',
214
+ fix: allowed.length || hooked.length ? "" : "Our suggestion: pre-approve the commands that check a change, so the agent can run them without asking each time.",
215
+ source: `${DOCS}/permissions.md`
216
+ },
217
+ {
218
+ id: "stop-check",
219
+ group: "verification",
220
+ title: "Something checks the work before the agent stops",
221
+ status: stopEvents.length ? "pass" : "warn",
222
+ detail: stopEvents.length ? `A hook runs on ${stopEvents.join(" and ")}. A Stop hook can send the agent back to keep working.` : "No hook runs when the agent finishes. The agent decides on its own that it is done, and you find out whether it was.",
223
+ fix: stopEvents.length ? "" : "Our suggestion: a Stop hook that runs a fast check and exits with code 2 when it fails. The docs say that sends Claude back to keep working, and they cap consecutive continuations at eight, so it cannot loop forever.",
224
+ source: `${DOCS}/hooks.md`
225
+ }
226
+ ];
227
+ if (facts.subagentFiles.length) {
228
+ checks.push({
229
+ id: "subagent-scope",
230
+ group: "verification",
231
+ title: "Each subagent is limited to the tools its job needs",
232
+ status: unscoped.length ? "warn" : "pass",
233
+ detail: unscoped.length ? `${plural(unscoped.length, "subagent")} set no tools line: ${unscoped.join(", ")}. The docs say a subagent then "inherits every tool available to subagents".` : `All ${plural(facts.subagentFiles.length, "subagent")} limit their tools.`,
234
+ fix: unscoped.length ? "Add a tools line to the frontmatter that lists only what the subagent needs, or a disallowedTools line that removes what it must not use." : "",
235
+ source: `${DOCS}/sub-agents.md`
236
+ });
237
+ } else {
238
+ checks.push({
239
+ id: "subagent-scope",
240
+ group: "verification",
241
+ title: "Subagents",
242
+ status: "info",
243
+ detail: "No subagent is defined. A subagent with a narrow job, such as a reviewer that sees only the diff, checks work in a fresh context.",
244
+ fix: "",
245
+ source: `${DOCS}/sub-agents.md`
246
+ });
247
+ }
248
+ return checks;
249
+ }
250
+ function promptFor(check, facts) {
251
+ if (check.status !== "fail" && check.status !== "warn") return "";
252
+ const [id, label] = check.id.split(":");
253
+ switch (id) {
254
+ case "memory-exists":
255
+ return "/init";
256
+ case "memory-length": {
257
+ const file = facts.memory.find((m) => m.label === label);
258
+ return `${label} is ${file?.lines ?? "many"} lines. The Claude Code docs say to target under ${MEMORY_LINE_TARGET} lines per file, because a longer file uses more context and is followed less well. Read it and give me a plan before you edit anything. For each section, say one of: keep; delete, because the code or the README already says it; move to a skill, because only some tasks need it; move to a file under .claude/rules/; or turn into a hook, because it must happen every time. Give the line count the file would have after the plan. Change nothing until I approve it.`;
259
+ }
260
+ case "auto-memory-index":
261
+ return "The auto memory index MEMORY.md is longer than what loads (the first 200 lines or 25 KB). Read it and propose which entries to merge, shorten or remove so that the ones that matter load. Show me the new index before you save it.";
262
+ case "hooks":
263
+ return 'This project has no Claude Code hooks. Look at how it formats, lints and tests code. Propose at most two hooks for .claude/settings.json that run after an edit (the PostToolUse event, with the matcher "Edit|Write"), for example the formatter on the changed file. For each one, show me the JSON, the command it runs and how long that command takes. Do not change the settings file until I approve.';
264
+ case "allow-rules":
265
+ return "/permissions";
266
+ case "deny-secrets": {
267
+ const rules = facts.secretFiles.length ? facts.secretFiles.map((file) => `Read(./${file})`).join(", ") : "Read(./.env), Read(./secrets/**)";
268
+ return `Add deny rules to the permissions.deny array in .claude/settings.json so that Claude Code cannot read secret files: ${rules}. Keep every rule that is already in the file. Show me the diff before you save it, and tell me how to confirm afterwards that a read of one of these files is refused.`;
269
+ }
270
+ case "broad-allow":
271
+ return "My Claude Code settings hold an allow rule that approves every shell command. Find it in the settings files, then list the shell commands this project really needs, such as its test, lint and build commands. Propose scoped allow rules for those to replace the blanket rule. Show me the diff before you save it.";
272
+ case "sandbox":
273
+ return "/sandbox";
274
+ case "verify-command":
275
+ return "/permissions";
276
+ case "stop-check":
277
+ return "Nothing checks your work before you stop. Look at how this project tests and lints, and find the fastest check that catches a broken change, such as the type check. Propose a Stop hook for .claude/settings.json that runs it and exits with code 2 when it fails, so that you are sent back to keep working. Show me the JSON, the command and how long the command takes. Do not change the settings file until I approve.";
278
+ case "subagent-scope":
279
+ return "Some of my subagents inherit every tool. For each subagent file under .claude/agents/, read what it is for and propose a tools line in its frontmatter that lists only the tools that job needs. Show me the proposed line for each file before you edit any of them.";
280
+ default:
281
+ return "";
282
+ }
283
+ }
284
+ function runChecks(facts) {
285
+ const checks = [...memoryChecks(facts), ...automationChecks(facts), ...guardrailChecks(facts), ...verificationChecks(facts)];
286
+ return checks.map((check) => ({ ...check, prompt: promptFor(check, facts) }));
287
+ }
288
+ function summarize(checks) {
289
+ const count = (status) => checks.filter((c) => c.status === status).length;
290
+ const [pass, warn, fail, info] = [count("pass"), count("warn"), count("fail"), count("info")];
291
+ const judged = pass + warn + fail;
292
+ return { pass, warn, fail, info, score: judged ? Math.round(pass / judged * 100) : 0 };
293
+ }
294
+ var FAIL_ON_LEVELS = ["fail", "warn"];
295
+ function failing(checks, level) {
296
+ return checks.filter((c) => c.status === "fail" || level === "warn" && c.status === "warn");
297
+ }
298
+
299
+ // src/groundcrew-gather.ts
300
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
301
+ import os from "os";
302
+ import path from "path";
303
+ var SECRET_NAMES = /^(\.env(\..+)?|secrets?(\..+)?|credentials(\..+)?|.*\.pem|id_rsa)$/i;
304
+ var NOT_SECRET = /\.(example|sample|template)$/i;
305
+ var SECRET_DEPTH = 3;
306
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "vendor", "coverage"]);
307
+ var home = () => os.homedir();
308
+ var configDir = () => process.env.CLAUDE_CONFIG_DIR || path.join(home(), ".claude");
309
+ var tilde = (file) => file.startsWith(home()) ? `~${file.slice(home().length)}` : file;
310
+ function canRead(project) {
311
+ try {
312
+ readdirSync(project);
313
+ return true;
314
+ } catch {
315
+ return false;
316
+ }
317
+ }
318
+ function readJson(file) {
319
+ try {
320
+ return JSON.parse(readFileSync(file, "utf-8"));
321
+ } catch {
322
+ return null;
323
+ }
324
+ }
325
+ function countFiles(dir, test) {
326
+ if (!existsSync(dir)) return 0;
327
+ let total = 0;
328
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
329
+ if (entry.isDirectory()) total += countFiles(path.join(dir, entry.name), test);
330
+ else if (test(entry.name)) total += 1;
331
+ }
332
+ return total;
333
+ }
334
+ function findSecretFiles(root, relative, depth) {
335
+ const dir = path.join(root, relative);
336
+ if (depth > SECRET_DEPTH || !existsSync(dir)) return [];
337
+ const found = [];
338
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
339
+ const here = relative ? `${relative}/${entry.name}` : entry.name;
340
+ if (entry.isDirectory()) {
341
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) found.push(...findSecretFiles(root, here, depth + 1));
342
+ } else if (SECRET_NAMES.test(entry.name) && !NOT_SECRET.test(entry.name)) {
343
+ found.push(here);
344
+ }
345
+ }
346
+ return found;
347
+ }
348
+ function hookCommands(hooks) {
349
+ const found = [];
350
+ for (const [event, groups] of Object.entries(hooks)) {
351
+ for (const group of Array.isArray(groups) ? groups : []) {
352
+ for (const handler of Array.isArray(group?.hooks) ? group.hooks : []) {
353
+ if (typeof handler?.command === "string") found.push({ event, command: handler.command });
354
+ }
355
+ }
356
+ }
357
+ return found;
358
+ }
359
+ function subagentFiles(dir) {
360
+ if (!existsSync(dir)) return [];
361
+ const found = [];
362
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
363
+ const file = path.join(dir, entry.name);
364
+ if (entry.isDirectory()) found.push(...subagentFiles(file));
365
+ else if (entry.name.endsWith(".md")) {
366
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(readFileSync(file, "utf-8"))?.[1] ?? "";
367
+ found.push({ name: entry.name.replace(/\.md$/, ""), limitsTools: /^(tools|disallowedTools)\s*:/m.test(frontmatter) });
368
+ }
369
+ }
370
+ return found;
371
+ }
372
+ var isMarkdown = (name) => name.endsWith(".md");
373
+ var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
374
+ function gather(project) {
375
+ const filesRead = [];
376
+ const label = (file) => file.startsWith(project + path.sep) ? file.slice(project.length + 1) : tilde(file);
377
+ const memoryFile = (file) => {
378
+ if (!existsSync(file) || !statSync(file).isFile()) return null;
379
+ const text = readFileSync(file, "utf-8");
380
+ filesRead.push(label(file));
381
+ return { label: label(file), lines: text.split("\n").length - (text.endsWith("\n") ? 1 : 0), bytes: Buffer.byteLength(text) };
382
+ };
383
+ const memory = [
384
+ path.join(project, "CLAUDE.md"),
385
+ path.join(project, ".claude", "CLAUDE.md"),
386
+ path.join(project, "CLAUDE.local.md"),
387
+ path.join(project, "AGENTS.md"),
388
+ path.join(configDir(), "CLAUDE.md")
389
+ ].map(memoryFile).filter((file) => file !== null);
390
+ const settingsFile = (scope, file) => {
391
+ const json = readJson(file);
392
+ if (!json) return null;
393
+ filesRead.push(label(file));
394
+ const permissions = json.permissions || {};
395
+ const hooks = json.hooks && typeof json.hooks === "object" ? json.hooks : {};
396
+ return {
397
+ scope,
398
+ label: label(file),
399
+ allow: strings(permissions.allow),
400
+ ask: strings(permissions.ask),
401
+ deny: strings(permissions.deny),
402
+ defaultMode: typeof permissions.defaultMode === "string" ? permissions.defaultMode : null,
403
+ additionalDirectories: strings(permissions.additionalDirectories).length,
404
+ hookEvents: Object.keys(hooks).filter((event) => Array.isArray(hooks[event]) && hooks[event].length > 0),
405
+ hookCommands: hookCommands(hooks),
406
+ sandboxEnabled: typeof json.sandbox?.enabled === "boolean" ? json.sandbox.enabled : null,
407
+ cleanupPeriodDays: typeof json.cleanupPeriodDays === "number" ? json.cleanupPeriodDays : null
408
+ };
409
+ };
410
+ const managed = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? "C:\\Program Files\\ClaudeCode\\managed-settings.json" : "/etc/claude-code/managed-settings.json";
411
+ const settings = [
412
+ settingsFile("managed", managed),
413
+ settingsFile("local", path.join(project, ".claude", "settings.local.json")),
414
+ settingsFile("project", path.join(project, ".claude", "settings.json")),
415
+ settingsFile("user", path.join(configDir(), "settings.json"))
416
+ ].filter((file) => file !== null);
417
+ const projectMcp = readJson(path.join(project, ".mcp.json"));
418
+ const userConfig = readJson(path.join(home(), ".claude.json"));
419
+ const userServers = Object.keys(userConfig?.mcpServers || {}).length + Object.keys(userConfig?.projects?.[project]?.mcpServers || {}).length;
420
+ if (projectMcp) filesRead.push(".mcp.json");
421
+ if (userConfig) filesRead.push("~/.claude.json (MCP server names only)");
422
+ const encoded = project.replace(/[^a-zA-Z0-9]/g, "-");
423
+ return {
424
+ filesRead,
425
+ facts: {
426
+ platform: process.platform,
427
+ memory,
428
+ ruleFiles: countFiles(path.join(project, ".claude", "rules"), isMarkdown) + countFiles(path.join(configDir(), "rules"), isMarkdown),
429
+ autoMemoryIndex: memoryFile(path.join(configDir(), "projects", encoded, "memory", "MEMORY.md")),
430
+ settings,
431
+ skills: {
432
+ project: countFiles(path.join(project, ".claude", "skills"), (name) => name === "SKILL.md"),
433
+ user: countFiles(path.join(configDir(), "skills"), (name) => name === "SKILL.md")
434
+ },
435
+ subagents: {
436
+ project: countFiles(path.join(project, ".claude", "agents"), isMarkdown),
437
+ user: countFiles(path.join(configDir(), "agents"), isMarkdown)
438
+ },
439
+ subagentFiles: [...subagentFiles(path.join(project, ".claude", "agents")), ...subagentFiles(path.join(configDir(), "agents"))],
440
+ legacyCommands: countFiles(path.join(project, ".claude", "commands"), isMarkdown),
441
+ mcpServers: { project: Object.keys(projectMcp?.mcpServers || {}).length, user: userServers },
442
+ secretFiles: findSecretFiles(project, "", 0).sort()
443
+ }
444
+ };
445
+ }
446
+
447
+ // src/groundcrew-page.ts
448
+ var esc = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
449
+ var STATUS = {
450
+ fail: { icon: "\u2715", word: "Fix" },
451
+ warn: { icon: "!", word: "Look" },
452
+ pass: { icon: "\u2713", word: "Good" },
453
+ info: { icon: "i", word: "Fact" }
454
+ };
455
+ var GROUP_TITLE = { setup: "Setup", guardrails: "Guardrails", verification: "Verification" };
456
+ var GROUPS = [
457
+ { key: "setup", intro: "What loads into every session, and what runs without being asked." },
458
+ { key: "guardrails", intro: "What the agent may reach, and what stops it." },
459
+ { key: "verification", intro: "Who checks the work when the agent says it is done." }
460
+ ];
461
+ var ORDER = ["fail", "warn", "pass", "info"];
462
+ var needsFix = (check) => check.status === "fail" || check.status === "warn";
463
+ var anchor = (check) => `check-${check.id.replace(/[^a-zA-Z0-9]+/g, "-")}`;
464
+ var CSS = `
465
+ :root{--bg:#faf9f6;--card:#fff;--fg:#1c1b19;--mut:#5f5c55;--line:#dddad1;--well:#f1efe9;--fail:#d03b3b;--warn:#fab219;--pass:#0ca30c;--info:#8f8e86}
466
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512}}
467
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
468
+ main{max-width:860px;margin:0 auto;padding:28px 16px 60px}h1{font-size:26px;margin:0}h2{font-size:19px;margin:36px 0 2px}
469
+ p{margin:6px 0}.mut{color:var(--mut)}code,pre{font:13px/1.5 ui-monospace,Menlo,monospace}a{color:inherit}[id]{scroll-margin-top:14px}
470
+ .score{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0 0}.tile{flex:1;min-width:120px;background:var(--card);border:1px solid var(--line);
471
+ border-radius:10px;padding:10px 14px}.tile b{display:block;font-size:26px;line-height:1.15}.tile span{font-size:12.5px;color:var(--mut)}
472
+ .bar{display:flex;gap:2px;height:8px;margin:14px 0 0}.bar i{display:block;border-radius:999px}
473
+ .todo{margin:14px 0 0;padding:0;list-style:none}.todo li{display:flex;gap:8px;align-items:center;padding:3px 0;font-size:14.5px}
474
+ .check{background:var(--card);border:1px solid var(--line);border-left-width:5px;border-radius:10px;padding:12px 14px;margin:10px 0 0}
475
+ .check h3{font-size:15.5px;margin:0;display:flex;align-items:center;gap:8px}.check p{font-size:14px}
476
+ .dot{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;font-size:11px;font-weight:700;
477
+ color:#fff;flex:none}.word{font-size:11.5px;font-weight:600;color:var(--mut);border:1px solid var(--line);border-radius:999px;padding:0 8px;margin-left:auto}
478
+ .fix{border-top:1px solid var(--line);margin-top:8px;padding-top:8px}.src{font-size:12.5px}
479
+ .prompt{margin-top:10px;border:1px solid var(--line);border-radius:8px;background:var(--well)}
480
+ .prompt header{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid var(--line);font-size:12.5px;color:var(--mut)}
481
+ .prompt pre{margin:0;padding:10px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--fg)}
482
+ .prompt button{margin-left:auto;font:600 12.5px system-ui,sans-serif;color:var(--fg);background:var(--card);border:1px solid var(--line);border-radius:6px;
483
+ padding:3px 12px;cursor:pointer}.prompt button:hover{border-color:var(--mut)}.prompt button:focus-visible{outline:2px solid var(--fg);outline-offset:2px}
484
+ .rows{margin:10px 0 0;padding:0;list-style:none;background:var(--card);border:1px solid var(--line);border-radius:10px}
485
+ .rows li{display:grid;grid-template-columns:18px minmax(120px,220px) 1fr;gap:4px 10px;align-items:start;padding:8px 12px;font-size:14px}
486
+ .rows li+li{border-top:1px solid var(--line)}.rows .dot{margin-top:2px}.rows b{font-weight:600}.rows .src{grid-column:3}
487
+ @media (max-width:600px){.rows li{grid-template-columns:18px 1fr}.rows span.d,.rows .src{grid-column:2}}
488
+ footer{margin-top:40px;border-top:1px solid var(--line);padding-top:12px;font-size:13px;color:var(--mut)}footer li{margin:2px 0}
489
+ ${ORDER.map((s) => `.s-${s}{border-left-color:var(--${s})}.s-${s} .dot,.s-${s}.dot,.bar .b-${s}{background:var(--${s})}`).join("")}
490
+ .s-warn .dot,.s-warn.dot{color:#0b0b0b}`;
491
+ var COPY_SCRIPT = `document.addEventListener('click',function(e){var b=e.target.closest('button[data-copy]');if(!b)return;
492
+ var t=document.getElementById(b.getAttribute('data-copy')).textContent;
493
+ function done(){b.textContent='Copied';setTimeout(function(){b.textContent='Copy'},1600)}
494
+ function old(){var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}
495
+ if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(done,old)}else{old()}});`;
496
+ var dot = (status) => `<span class="dot s-${status}" aria-hidden="true">${STATUS[status].icon}</span>`;
497
+ var sourceLink = (check) => `<a href="${esc(check.source)}" target="_blank" rel="noopener noreferrer">${esc(check.source.replace(/^https:\/\/code\.claude\.com\/docs\/en\//, "docs: ").replace(/\.md$/, ""))}</a>`;
498
+ function fixCard(check) {
499
+ const status = STATUS[check.status];
500
+ const id = anchor(check);
501
+ const isCommand = check.prompt.startsWith("/");
502
+ const prompt = check.prompt ? `<div class="prompt"><header>${isCommand ? "Type this command in Claude Code" : "Paste this into Claude Code"}<button type="button" data-copy="${id}-prompt">Copy</button></header><pre id="${id}-prompt">${esc(check.prompt)}</pre></div>` : "";
503
+ return `<section class="check s-${check.status}" id="${id}"><h3>${dot(check.status)}${esc(check.title)}<span class="word">${status.word}</span></h3><p>${esc(check.detail)}</p>${check.fix ? `<p class="fix"><b>What to change:</b> ${esc(check.fix)}</p>` : ""}${prompt}<p class="src mut">Rests on ${sourceLink(check)}</p></section>`;
504
+ }
505
+ var row = (check) => `<li>${dot(check.status)}<b>${esc(check.title)}<span class="mut"> \xB7 ${STATUS[check.status].word}</span></b><span class="d">${esc(check.detail)}</span><span class="src mut">${sourceLink(check)}</span></li>`;
506
+ function renderPage(report2) {
507
+ const { summary } = report2;
508
+ const judged = summary.pass + summary.warn + summary.fail;
509
+ const bar = ["fail", "warn", "pass"].filter((s) => summary[s] > 0).map((s) => `<i class="b-${s}" style="flex:${summary[s]}"></i>`).join("");
510
+ const sorted = [...report2.checks].sort((a, b) => ORDER.indexOf(a.status) - ORDER.indexOf(b.status));
511
+ const fixes = sorted.filter(needsFix);
512
+ const todo = fixes.length ? `<h2>Do these first</h2><ul class="todo">${fixes.map((c) => `<li>${dot(c.status)}<a href="#${anchor(c)}">${esc(c.title)}</a><span class="mut">${GROUP_TITLE[c.group]}</span></li>`).join("")}</ul>` : '<h2>Nothing to fix</h2><p class="mut">Every check that can fail passes.</p>';
513
+ const groups = GROUPS.map((group) => {
514
+ const mine = sorted.filter((c) => c.group === group.key);
515
+ const rest = mine.filter((c) => !needsFix(c));
516
+ return `<h2>${GROUP_TITLE[group.key]}</h2><p class="mut">${group.intro}</p>${mine.filter(needsFix).map(fixCard).join("")}` + (rest.length ? `<ul class="rows">${rest.map(row).join("")}</ul>` : "");
517
+ }).join("");
518
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JQ Groundcrew: ${esc(report2.project)}</title><style>${CSS}</style></head><body><main><h1>JQ Groundcrew</h1><p class="mut">The setup check for Claude Code. How it is set up for <code>${esc(report2.project)}</code>. Read ${esc(report2.generatedAt)}. Refresh to read again.</p><div class="score"><div class="tile"><b>${summary.fail}</b><span>to fix</span></div><div class="tile"><b>${summary.warn}</b><span>to look at</span></div><div class="tile"><b>${summary.pass}</b><span>good</span></div><div class="tile"><b>${summary.score}%</b><span>of ${judged} checks pass</span></div></div><div class="bar" role="img" aria-label="${summary.fail} to fix, ${summary.warn} to look at, ${summary.pass} good">${bar}</div>` + todo + groups + `<footer><p>This page was made on your machine from the files below, and it loads nothing, so nothing left the machine. Its one script copies a prompt to your clipboard when you press Copy. It read settings and counted files. It did not read the contents of any secret file, and it read no session transcript.</p><p>A suggested prompt asks Claude Code to show its plan or its diff first. Read that before you approve it.</p><ul>${report2.filesRead.map((file) => `<li><code>${esc(file)}</code></li>`).join("")}</ul><p>Each check names the page of Anthropic\u2019s Claude Code documentation it rests on. The documentation was checked on 2026-11-14 and can change.</p></footer></main><script>${COPY_SCRIPT}</script></body></html>
519
+ `;
520
+ }
521
+
522
+ // src/groundcrew-cli.ts
523
+ var DEFAULT_PORT = 4317;
524
+ function report(project) {
525
+ const { facts, filesRead } = gather(project);
526
+ const checks = runChecks(facts);
527
+ return { project: tilde(project), generatedAt: (/* @__PURE__ */ new Date()).toLocaleString("en-US"), filesRead, checks, summary: summarize(checks) };
528
+ }
529
+ function parseArgs(args, defaultProject) {
530
+ const valueAfter = (flag) => {
531
+ const at = args.indexOf(flag);
532
+ return at === -1 ? null : { at, value: args[at + 1] };
533
+ };
534
+ const html = valueAfter("--html");
535
+ const port = valueAfter("--port");
536
+ const failOn = valueAfter("--fail-on");
537
+ if (html && (!html.value || html.value.startsWith("--"))) throw new Error("--html needs a file name");
538
+ const portNumber = port ? Number(port.value) : DEFAULT_PORT;
539
+ if (!Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) throw new Error("--port needs a number from 1 to 65535");
540
+ if (failOn && !FAIL_ON_LEVELS.includes(failOn.value)) throw new Error("--fail-on needs fail or warn");
541
+ if (failOn && !html && !args.includes("--json")) throw new Error("--fail-on works with --json or --html, not with the page server");
542
+ const taken = new Set([html?.at, port?.at, failOn?.at].filter((at) => at !== void 0).map((at) => at + 1));
543
+ const dir = args.find((arg, i) => !arg.startsWith("--") && !taken.has(i));
544
+ const project = path2.resolve(dir || defaultProject);
545
+ if (!existsSync2(project) || !canRead(project)) throw new Error(`cannot read the folder: ${project}`);
546
+ return { project, flags: new Set(args.filter((arg) => arg.startsWith("--"))), html: html?.value ?? null, port: portNumber, failOn: failOn?.value ?? null };
547
+ }
548
+ function exitCodeFor(checks, failOn) {
549
+ if (!failOn) return 0;
550
+ const counted = failing(checks, failOn);
551
+ for (const check of counted) console.error(`groundcrew: ${check.status}: ${check.title}`);
552
+ return counted.length ? 1 : 0;
553
+ }
554
+ function runLocal(parsed) {
555
+ const { project } = parsed;
556
+ if (parsed.flags.has("--json")) {
557
+ const result = report(project);
558
+ console.log(JSON.stringify(result, null, 2));
559
+ return exitCodeFor(result.checks, parsed.failOn);
560
+ }
561
+ if (parsed.html) {
562
+ const result = report(project);
563
+ writeFileSync(parsed.html, renderPage(result));
564
+ console.log(`wrote ${parsed.html}`);
565
+ return exitCodeFor(result.checks, parsed.failOn);
566
+ }
567
+ createServer((request, response) => {
568
+ if (request.url !== "/") {
569
+ response.writeHead(404).end("not found");
570
+ return;
571
+ }
572
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(renderPage(report(project)));
573
+ }).listen(parsed.port, "127.0.0.1", () => console.log(`JQ Groundcrew for ${tilde(project)}: http://127.0.0.1:${parsed.port} (Ctrl+C to stop)`));
574
+ return 0;
575
+ }
576
+
577
+ // src/main.ts
578
+ var VERSION = true ? "0.1.2" : "dev";
579
+ var HELP = `JQ Groundcrew ${VERSION}: the setup check for Claude Code.
580
+
581
+ It reads how Claude Code is set up for a project and shows what to fix, with a prompt to copy
582
+ for each fix. It runs on your machine and sends nothing anywhere.
583
+
584
+ jq-groundcrew [folder] open a page at http://127.0.0.1:${DEFAULT_PORT}
585
+ jq-groundcrew [folder] --html FILE write the page to a file
586
+ jq-groundcrew [folder] --json print the report
587
+ jq-groundcrew --port NUMBER serve on another port
588
+ jq-groundcrew --json --fail-on fail exit 1 if a check fails, for CI
589
+ (--fail-on warn also counts a warning)
590
+
591
+ The folder defaults to the one you are in. It reads settings files, counts lines in CLAUDE.md
592
+ files, and lists the names of skills, subagents, MCP servers and files that usually hold
593
+ secrets. It never opens a secrets file and never reads a session transcript.
594
+
595
+ Unofficial. Not affiliated with or endorsed by Anthropic.`;
596
+ try {
597
+ const args = process.argv.slice(2);
598
+ if (args.includes("--help") || args.includes("-h")) console.log(HELP);
599
+ else if (args.includes("--version") || args.includes("-v")) console.log(VERSION);
600
+ else process.exitCode = runLocal(parseArgs(args, process.cwd()));
601
+ } catch (error) {
602
+ console.error(error.message || error);
603
+ process.exit(1);
604
+ }