@misconfig/cli 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1152 @@
1
+ // What each file that controls an agent actually tells it to do, in plain
2
+ // words. This runs on the user's computer. Share links carry rule names,
3
+ // never these details; only an --open report, encrypted on the computer,
4
+ // carries them.
5
+
6
+ import { describeMasks, maskSecrets } from "./mask.js";
7
+ import { findDangerFlag, trimWord, programName } from "./flags.js";
8
+ import { parseCodexRules, parseYAML } from "./parse.js";
9
+
10
+ const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
11
+ const strs = (x) => (Array.isArray(x) ? x.filter((s) => typeof s === "string" && s.trim()) : []);
12
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
13
+ // Drops invisible tag characters, zero-width and direction marks, and control
14
+ // codes, so a summary shows only what can be seen.
15
+ const clean = (s) => describeMasks(String(s)).replace(/[\u{E0000}-\u{E007F}\u200b-\u200d\u2060\ufeff\u202a-\u202e\u2066-\u2069\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu, "");
16
+ // Shortens text at a word boundary, so a summary never ends mid-word.
17
+ const clip = (s, n = 90) => {
18
+ const t = clean(s).replace(/\s+/g, " ").trim();
19
+ if (t.length <= n) return t;
20
+ const cut = t.slice(0, n - 1);
21
+ const space = cut.lastIndexOf(" ");
22
+ return `${(space > n * 0.5 ? cut.slice(0, space) : cut).replace(/[\s,;:.(\-]+$/, "")}…`;
23
+ };
24
+
25
+ // Paths as people recognize them: the home folder as ~, forward slashes, and
26
+ // long paths shortened in the middle so the folder or file name stays visible.
27
+ const HOME_PREFIX = /^(?:[a-z]:\/users\/[^/]+|\/users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/i;
28
+ function shortPath(p, n = 60) {
29
+ // Doubled separators, as in a Windows path written C:\\Users\\..., count once.
30
+ const t = clean(p).trim().replace(/\\/g, "/").replace(/(?!^)\/{2,}/g, "/").replace(HOME_PREFIX, "~");
31
+ if (t.length <= n) return t;
32
+ const parts = t.split("/");
33
+ const last = parts.pop();
34
+ const short = `${parts.slice(0, 2).join("/")}/…/${last}`;
35
+ return short.length <= n ? short : `…/${last.length > n - 2 ? `${last.slice(0, n - 3)}…` : last}`;
36
+ }
37
+ const looksLikePath = (s) => /^(?:[a-z]:[\\/]|\/|~[\\/]|\.{1,2}[\\/])/i.test(String(s));
38
+ const commandText = (command, args, n = 80) =>
39
+ clip([command, ...args].filter(Boolean).map((part) => (looksLikePath(part) ? shortPath(part, 50) : part)).join(" "), n);
40
+ const period = (s) => (/[.!?…”"]$/.test(s) ? s : `${s}.`);
41
+ const list = (items, max = 4) => {
42
+ const shown = items.slice(0, max);
43
+ const rest = items.length - shown.length;
44
+ if (rest > 0) return `${shown.join(", ")} and ${rest} more`;
45
+ return shown.length < 2 ? shown.join("") : `${shown.slice(0, -1).join(", ")} and ${shown[shown.length - 1]}`;
46
+ };
47
+ const sentence = (s) => (s ? s.replace(/^./, (c) => c.toUpperCase()).replace(/([^.!?…”"])$/, "$1.") : s);
48
+
49
+ // Unicode tag characters, which no font draws, as runs of { index, length,
50
+ // decoded }. The flags of England, Scotland and Wales are written with a few
51
+ // tag letters after a black flag emoji, so a run like that is a flag, not
52
+ // hidden text.
53
+ const FLAG_TAGS = /^[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,7}\u{E007F}$/u;
54
+ export function hiddenTags(text) {
55
+ const out = [];
56
+ for (const m of text.matchAll(/[\u{E0000}-\u{E007F}]+/gu)) {
57
+ if (text.codePointAt(m.index - 2) === 0x1f3f4 && FLAG_TAGS.test(m[0])) continue;
58
+ const chars = [...m[0]];
59
+ const decoded = chars.map((ch) => String.fromCharCode(ch.codePointAt(0) - 0xe0000)).join("").replace(/[^\x20-\x7e]/g, "");
60
+ out.push({ index: m.index, length: chars.length, decoded });
61
+ }
62
+ return out;
63
+ }
64
+
65
+ // Where zero-width characters are in a text, leaving out the ones that are
66
+ // part of the writing: a byte order mark at the start of the text or of a
67
+ // line, the joiner inside an emoji sequence such as the technologist emoji,
68
+ // and the joiners and breaks that scripts such as Persian, Hindi and Thai
69
+ // use between letters. Two or more in a row always count, since nothing
70
+ // written needs that.
71
+ const PICTOGRAPH = /[\p{Extended_Pictographic}\p{Emoji_Modifier}\ufe0f]/u;
72
+ const LETTER = /[\p{L}\p{M}]/u;
73
+ const LATIN = /[\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/u;
74
+ const otherScript = (ch) => LETTER.test(ch) && !LATIN.test(ch);
75
+ const charBefore = (text, i) => (i > 0 ? String.fromCodePoint(text.codePointAt(i >= 2 && /[\udc00-\udfff]/.test(text[i - 1]) ? i - 2 : i - 1)) : "");
76
+ const charAfter = (text, i) => (i < text.length ? String.fromCodePoint(text.codePointAt(i)) : "");
77
+ export function hiddenZeroWidth(text) {
78
+ const out = [];
79
+ for (const m of text.matchAll(/[\u0000\u200b-\u200d\u2060\u180e\ufeff]+/g)) {
80
+ let { index } = m;
81
+ let run = m[0];
82
+ if (run[0] === "\ufeff" && (index === 0 || text[index - 1] === "\n")) {
83
+ index++;
84
+ run = run.slice(1);
85
+ if (!run) continue;
86
+ }
87
+ if (run.length === 1) {
88
+ const before = charBefore(text, index);
89
+ const after = charAfter(text, index + 1);
90
+ if (run === "\u200d" && PICTOGRAPH.test(before) && PICTOGRAPH.test(after)) continue;
91
+ if ("\u200b\u200c\u200d\u180e".includes(run) && (otherScript(before) || otherScript(after))) continue;
92
+ }
93
+ for (let i = 0; i < run.length; i++) out.push(index + i);
94
+ if (out.length >= 100_000) break;
95
+ }
96
+ return out;
97
+ }
98
+
99
+ // HTML comments as { index, inner }, found with indexOf: a file full of
100
+ // unclosed "<!--" can't slow anything down.
101
+ export function htmlComments(text, max = 200) {
102
+ const out = [];
103
+ for (let from = 0; out.length < max; ) {
104
+ const start = text.indexOf("<!--", from);
105
+ if (start < 0) break;
106
+ const end = text.indexOf("-->", start + 4);
107
+ if (end < 0) break;
108
+ out.push({ index: start, inner: text.slice(start + 4, end) });
109
+ from = end + 3;
110
+ }
111
+ return out;
112
+ }
113
+
114
+ // Fenced code blocks as [start, end) offsets. A file of thousands of fences
115
+ // is still read in one pass.
116
+ export function fencedRanges(text) {
117
+ const ranges = [];
118
+ let open = -1;
119
+ let marker = "";
120
+ for (let start = 0; start < text.length; ) {
121
+ const nl = text.indexOf("\n", start);
122
+ const end = nl < 0 ? text.length : nl;
123
+ const m = /^ {0,3}(`{3,}|~{3,})/.exec(text.slice(start, Math.min(end, start + 16)));
124
+ if (m && open < 0) {
125
+ open = start;
126
+ marker = m[1][0];
127
+ } else if (m && m[1][0] === marker) {
128
+ ranges.push([open, end]);
129
+ open = -1;
130
+ }
131
+ start = end + 1;
132
+ }
133
+ if (open >= 0) ranges.push([open, text.length]);
134
+ return ranges;
135
+ }
136
+
137
+ // A function that finds the code block an offset is in, if any, by binary
138
+ // search, so many lookups in a file of many blocks stay fast.
139
+ export function fenceAt(text) {
140
+ const fences = fencedRanges(text);
141
+ return (i) => {
142
+ let lo = 0;
143
+ let hi = fences.length - 1;
144
+ while (lo <= hi) {
145
+ const mid = (lo + hi) >> 1;
146
+ if (i < fences[mid][0]) hi = mid - 1;
147
+ else if (i >= fences[mid][1]) lo = mid + 1;
148
+ else return fences[mid];
149
+ }
150
+ return null;
151
+ };
152
+ }
153
+
154
+ // HTML comments that are hidden when the Markdown is displayed. Inside a
155
+ // code block or a `code span` a comment shows as written, so it isn't.
156
+ export function hiddenComments(text, max = 200) {
157
+ const fence = fenceAt(text);
158
+ const inFence = (i) => fence(i) !== null;
159
+ return htmlComments(text, max * 5).filter((c) => !inFence(c.index) && !inCodeSpan(text, c.index)).slice(0, max);
160
+ }
161
+
162
+ const withoutComments = (line) => {
163
+ let out = "";
164
+ let from = 0;
165
+ for (const c of hiddenComments(line)) {
166
+ out += line.slice(from, c.index);
167
+ from = c.index + c.inner.length + 7;
168
+ }
169
+ return out + line.slice(from);
170
+ };
171
+
172
+ // Where a file's settings apply.
173
+ export function scopeOf(file) {
174
+ const p = file.path;
175
+ if (/(^|\/)managed-settings\.json$/i.test(p)) return "admin";
176
+ if (file.loose) return "loose";
177
+ if (/^(~|\/|[A-Za-z]:)/.test(p)) return "computer";
178
+ return "project";
179
+ }
180
+
181
+ export const SCOPES = {
182
+ admin: "Set by an administrator, for everyone on this computer",
183
+ computer: "On this computer, for every project",
184
+ project: "In this project",
185
+ loose: "Loose files where agents have been started",
186
+ };
187
+
188
+ // { scope, summary, details } for one file. `json` is the parsed settings
189
+ // file (or null); `servers` are its MCP servers, already normalized.
190
+ export function explainFile(file, { json = null, servers = [] } = {}) {
191
+ const scope = scopeOf(file);
192
+ if (file.listed && file.kind === "Plugin code") return { scope, summary: `Code ${file.tools?.[0] ?? "the agent"} loads when it starts. misconfig lists it by name and doesn't open it.`, details: [] };
193
+ if (!file.content) return { scope, summary: file.tooLarge ? "Too large to read." : "Not read.", details: [] };
194
+ const p = file.path;
195
+ let out;
196
+ if (/(^|\/)(\.claude\/settings(\.local)?\.json|managed-settings(\.d\/[^/]+)?\.json)$/i.test(p)) out = claudeSettings(json, scope === "project");
197
+ else if (/(^|\/)\.claude\/plugins\/installed_plugins\.json$/i.test(p)) out = claudePlugins(json);
198
+ else if (/(^|\/)\.claude\/plugins\/known_marketplaces\.json$/i.test(p)) out = claudeMarketplaces(json);
199
+ else if (/(^|\/)\.claude\/plugins\/.+\/hooks\/hooks\.json$/i.test(p)) out = { parts: [], details: claudeHooks(json?.hooks) };
200
+ else if (/(^|\/)\.claude\.json$/i.test(p)) out = claudeUserConfig(json);
201
+ else if (/(^|\/)\.codex\/([^/]+\.)?config\.toml$/i.test(p)) out = codexConfig(json);
202
+ else if (/(^|\/)codex\/requirements\.toml$/i.test(p)) out = codexRequirements(json);
203
+ else if (/(^|\/)(\.gemini|gemini-cli|GeminiCli)\/(system-)?settings\.json$/i.test(p)) out = geminiSettings(json);
204
+ else if (/(^|\/)\.gemini\/trustedFolders\.json$/i.test(p)) out = trustedFolders(geminiTrusted(json));
205
+ else if (/(^|\/)\.copilot\/config\.json$/i.test(p)) out = trustedFolders(strs(json?.trusted_folders ?? json?.trustedFolders));
206
+ else if (/(^|\/)(\.github\/hooks\/[^/]+|\.cursor\/hooks|\.codex\/hooks|\.windsurf\/hooks|\.codeium\/windsurf\/hooks|\.devin\/hooks\.v1|\.grok\/hooks\/[^/]+)\.json$/i.test(p)) out = jsonHooks(json);
207
+ else if (/(^|\/)\.kiro\/hooks\/[^/]+\.(json|kiro\.hook)$/i.test(p)) out = jsonHooks(json);
208
+ else if (/(^|\/)(\.kiro\/agents|\.amazonq\/cli-agents|\.aws\/amazonq\/cli-agents)\/[^/]+\.json$/i.test(p)) out = agentConfig(json);
209
+ else if (/(^|\/)\.cursor\/environment\.json$/i.test(p)) out = cursorEnvironment(json);
210
+ else if (/(^|\/)\.vscode\/tasks\.json$/i.test(p)) out = vsCodeTasks(json);
211
+ else if (/(^|\/)\.gemini\/commands\/.+\.toml$/i.test(p)) out = geminiCommand(p, json);
212
+ else if (/(^|\/)\.codex\/rules\/[^/]+\.rules$/i.test(p)) out = codexRules(file);
213
+ else if (/(^|\/)\.cursor\/(cli-config|cli)\.json$/i.test(p)) out = cursorCli(json);
214
+ else if (/(^|\/)\.cursor\/sandbox\.json$/i.test(p)) out = cursorSandbox(json);
215
+ else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(p)) out = editorSettings(json);
216
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) out = openCode(json);
217
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) out = zedSettings(json);
218
+ else if (/(^|\/)\.cline\/data\/globalState\.json$/i.test(p)) out = clineState(json);
219
+ else if (/(^|\/)\.grok\/config\.toml$/i.test(p)) out = grokConfig(json);
220
+ else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) out = ampSettings(json);
221
+ else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) out = gooseConfig(file);
222
+ else if (/(^|\/)\.continue\/config\.ya?ml$/i.test(p)) out = continueConfig(file);
223
+ else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(p)) out = aiderConfig(file);
224
+ else if (file.kind === "Shell profile") out = shellProfile(file);
225
+ else if (file.kind === "Hook script") out = hookScript(file);
226
+ else if (/\.(jsonc?|toml)$/i.test(p)) out = { parts: [], details: [] };
227
+ else out = instructions(file);
228
+
229
+ // MCP servers, wherever they're defined.
230
+ if (servers.length) {
231
+ const on = servers.filter((s) => !s.disabled);
232
+ out.parts.push(on.length === servers.length ? `${plural(servers.length, "MCP server")}: ${list(servers.map((s) => s.name), 3)}` : `${plural(on.length, "MCP server")} on, ${servers.length - on.length} off`);
233
+ for (const s of servers) out.details.push(serverText(s));
234
+ }
235
+ const summary = out.summary ?? (out.parts.length ? out.parts.map(sentence).join(" ") : "Nothing that changes how an agent behaves.");
236
+ return { scope, summary, details: out.details };
237
+ }
238
+
239
+ function serverText(s) {
240
+ let what;
241
+ if (s.url) {
242
+ let host = "";
243
+ try {
244
+ host = new URL(s.url).host;
245
+ } catch {
246
+ host = clip(s.url, 40);
247
+ }
248
+ what = `connects to ${host}`;
249
+ } else what = `runs ${commandText(s.command, s.args)}`;
250
+ const auto = s.alwaysAllow === true ? "; its tools run without asking" : strs(s.alwaysAllow).length ? `; runs ${list(strs(s.alwaysAllow), 3)} without asking` : "";
251
+ const keys = Object.keys(s.env ?? {});
252
+ const env = keys.length > 3 ? `; sets ${keys.length} environment variables` : keys.length ? `; sets ${list(keys, 3)}` : "";
253
+ return period(`MCP server “${s.name}”${s.disabled ? " (turned off)" : ""}: ${what}${auto}${env}`);
254
+ }
255
+
256
+ // --- Claude Code -------------------------------------------------------------
257
+
258
+ const CLAUDE_MODES = {
259
+ default: ["Asks before acting", "Asks the first time each tool is used."],
260
+ manual: ["Asks before acting", "Asks the first time each tool is used."],
261
+ acceptEdits: ["Edits files without asking", "Accepts file edits and common file commands in the project without asking, and asks before other commands."],
262
+ plan: ["Plan mode", "Starts in plan mode: it reads and explores but changes nothing until you approve a plan."],
263
+ auto: ["Auto mode", "Auto mode: runs without routine prompts while a classifier checks that each action matches what you asked for."],
264
+ dontAsk: ["Refuses anything not allowed", "Never prompts: anything that isn't already allowed is refused."],
265
+ bypassPermissions: ["Never asks", "Skips permission prompts for everything except a few protected actions."],
266
+ };
267
+
268
+ // Claude Code hook events, in plain words.
269
+ export const HOOK_EVENTS = {
270
+ SessionStart: "When a session starts",
271
+ Setup: "During setup",
272
+ UserPromptSubmit: "When you send a prompt",
273
+ UserPromptExpansion: "When a prompt is expanded",
274
+ PreToolUse: "Before each tool runs",
275
+ PermissionRequest: "When Claude asks for permission",
276
+ PermissionDenied: "When a permission is denied",
277
+ PostToolUse: "After each tool runs",
278
+ PostToolUseFailure: "After a tool fails",
279
+ PostToolBatch: "After a batch of tools runs",
280
+ Notification: "When Claude sends a notification",
281
+ MessageDisplay: "When a message is shown",
282
+ SubagentStart: "When a subagent starts",
283
+ SubagentStop: "When a subagent finishes",
284
+ TaskCreated: "When a task is created",
285
+ TaskCompleted: "When a task is completed",
286
+ Stop: "When Claude finishes a reply",
287
+ StopFailure: "When a reply ends with an error",
288
+ TeammateIdle: "When a teammate goes idle",
289
+ InstructionsLoaded: "When instruction files are loaded",
290
+ ConfigChange: "When settings change",
291
+ CwdChanged: "When the working folder changes",
292
+ DirectoryAdded: "When a folder is added",
293
+ FileChanged: "When a file changes",
294
+ WorktreeCreate: "When a worktree is created",
295
+ WorktreeRemove: "When a worktree is removed",
296
+ PreCompact: "Before the conversation is compacted",
297
+ PostCompact: "After the conversation is compacted",
298
+ PreModelSwitch: "Before the model changes",
299
+ PostModelSwitch: "After the model changes",
300
+ Elicitation: "When an MCP server asks for input",
301
+ ElicitationResult: "When you answer an MCP server",
302
+ SessionEnd: "When a session ends",
303
+ };
304
+
305
+ // Settings that make Claude Code run a command, and what each command is for.
306
+ const CLAUDE_COMMANDS = {
307
+ apiKeyHelper: "to get its API key",
308
+ awsAuthRefresh: "to refresh AWS credentials",
309
+ awsCredentialExport: "to get AWS credentials",
310
+ gcpAuthRefresh: "to refresh Google Cloud credentials",
311
+ otelHeadersHelper: "to get telemetry headers",
312
+ statusLine: "to draw the status line",
313
+ subagentStatusLine: "to draw subagent status",
314
+ fileSuggestion: "to suggest files",
315
+ processWrapper: "to start its background processes",
316
+ policyHelper: "to work out managed settings",
317
+ sshHostCommands: "to find SSH hosts",
318
+ };
319
+
320
+ const commandsOf = (value, depth = 0) =>
321
+ typeof value === "string"
322
+ ? [value]
323
+ : Array.isArray(value) && depth < 4
324
+ ? value.flatMap((v) => commandsOf(v, depth + 1))
325
+ : isObj(value)
326
+ ? [value.command, value.path].filter((c) => typeof c === "string")
327
+ : [];
328
+
329
+ function hookText(event, matcher, h) {
330
+ const when = `${HOOK_EVENTS[event] ?? event}${matcher}`;
331
+ if (typeof h?.command === "string") return `${when}: runs ${clip(h.command, 80)}.`;
332
+ if (h?.type === "http" && typeof h.url === "string") {
333
+ let host = h.url;
334
+ try {
335
+ host = new URL(h.url).host;
336
+ } catch {}
337
+ return `${when}: sends the event to ${clip(host, 50)}.`;
338
+ }
339
+ if (h?.type === "mcp_tool") return `${when}: calls an MCP tool${typeof h.server === "string" ? ` on “${clip(h.server, 30)}”` : ""}.`;
340
+ if (h?.type === "prompt") return `${when}: asks a model to check it.`;
341
+ if (h?.type === "agent") return `${when}: starts a subagent to check it.`;
342
+ return null;
343
+ }
344
+
345
+ // `shared` is a project's own settings file, where Claude Code ignores the
346
+ // auto and bypassPermissions modes.
347
+ function claudeSettings(json, shared) {
348
+ const parts = [];
349
+ const details = [];
350
+ if (!isObj(json)) return { parts, details, summary: "Couldn't read the settings in this file." };
351
+ const p = isObj(json.permissions) ? json.permissions : {};
352
+ const mode = CLAUDE_MODES[p.defaultMode];
353
+ if (mode && shared && (p.defaultMode === "auto" || p.defaultMode === "bypassPermissions")) {
354
+ parts.push(`asks for ${p.defaultMode} mode`);
355
+ details.push(`Asks for ${p.defaultMode} mode. Claude Code ignores that in a project's own settings and starts in the default mode, but versions before 2.1.257 honor bypassPermissions.`);
356
+ } else if (mode) {
357
+ parts.push(mode[0]);
358
+ details.push(mode[1]);
359
+ } else if (typeof p.defaultMode === "string") {
360
+ parts.push(`permission mode: ${clip(p.defaultMode, 30)}`);
361
+ details.push(`Permission mode: ${clip(p.defaultMode, 30)}.`);
362
+ }
363
+ const allow = strs(p.allow);
364
+ const ask = strs(p.ask);
365
+ const deny = strs(p.deny);
366
+ if (allow.length) {
367
+ parts.push(`allows ${plural(allow.length, "action")} without asking`);
368
+ details.push(`Allowed without asking: ${list(allow.map((r) => clip(r, 60)), 8)}.`);
369
+ }
370
+ if (ask.length) details.push(`Always asks first: ${list(ask.map((r) => clip(r, 60)), 6)}.`);
371
+ if (deny.length) {
372
+ parts.push(`blocks ${plural(deny.length, "action")}`);
373
+ details.push(`Blocked: ${list(deny.map((r) => clip(r, 60)), 8)}.`);
374
+ }
375
+ const dirs = strs(p.additionalDirectories);
376
+ if (dirs.length) details.push(`Can also work in: ${list(dirs.map((d) => clip(d, 60)), 4)}.`);
377
+
378
+ const hooks = claudeHooks(json.hooks);
379
+ if (hooks.length) parts.push(hooks.length === 1 ? "has a hook" : `has ${hooks.length} hooks`);
380
+ details.push(...hooks);
381
+ if (json.disableAllHooks === true) details.push("Turns off all hooks.");
382
+ if (isObj(json.env) && Object.keys(json.env).length) {
383
+ const keys = Object.keys(json.env);
384
+ parts.push(`sets ${plural(keys.length, "environment variable")}`);
385
+ details.push(`Sets ${list(keys, 6)} for the agent.`);
386
+ }
387
+ if (typeof json.model === "string") {
388
+ parts.push(`uses the ${json.model} model`);
389
+ details.push(`Uses the ${json.model} model.`);
390
+ }
391
+ if (json.enableAllProjectMcpServers === true) {
392
+ parts.push("turns on every project MCP server");
393
+ details.push("Turns on every MCP server a project's .mcp.json lists, without asking.");
394
+ }
395
+ const enabled = strs(json.enabledMcpjsonServers);
396
+ if (enabled.length) details.push(`Turns on these project MCP servers: ${list(enabled, 5)}.`);
397
+ for (const [key, purpose] of Object.entries(CLAUDE_COMMANDS)) {
398
+ for (const command of commandsOf(json[key])) details.push(`Runs ${clip(command, 60)} ${purpose}.`);
399
+ }
400
+ if (isObj(json.sandbox) && typeof json.sandbox.enabled === "boolean") details.push(json.sandbox.enabled ? "Runs commands in a sandbox." : "Turns the command sandbox off.");
401
+ const plugins = isObj(json.enabledPlugins) ? Object.keys(json.enabledPlugins).filter((k) => json.enabledPlugins[k]) : [];
402
+ if (plugins.length) {
403
+ parts.push(`turns on ${plural(plugins.length, "plugin")}`);
404
+ details.push(`Turns on ${plural(plugins.length, "plugin")}: ${list(plugins.map((k) => clip(k, 40)), 5)}.`);
405
+ }
406
+ if (isObj(json.extraKnownMarketplaces) && Object.keys(json.extraKnownMarketplaces).length) {
407
+ details.push(`Adds plugin marketplaces: ${list(Object.keys(json.extraKnownMarketplaces).map((k) => clip(k, 40)), 4)}.`);
408
+ }
409
+ if (typeof json.outputStyle === "string") details.push(`Uses the “${json.outputStyle}” output style.`);
410
+ return { parts, details };
411
+ }
412
+
413
+ // One line per hook, in the order they appear.
414
+ function claudeHooks(hooks) {
415
+ const out = [];
416
+ if (!isObj(hooks)) return out;
417
+ for (const [event, entries] of Object.entries(hooks)) {
418
+ for (const entry of Array.isArray(entries) ? entries : []) {
419
+ const matcher = typeof entry?.matcher === "string" && entry.matcher && entry.matcher !== "*" ? ` (${clip(entry.matcher, 30)})` : "";
420
+ for (const h of Array.isArray(entry?.hooks) ? entry.hooks : [entry]) {
421
+ const text = hookText(event, matcher, h);
422
+ if (text) out.push(text);
423
+ }
424
+ }
425
+ }
426
+ return out;
427
+ }
428
+
429
+ // ~/.claude.json, already reduced to MCP servers and the folders Claude Code
430
+ // has been started in. MCP servers are added by the caller.
431
+ function claudeUserConfig(json) {
432
+ const parts = [];
433
+ const details = [];
434
+ if (!isObj(json) || !isObj(json.projects)) return { parts, details };
435
+ const folders = Object.keys(json.projects);
436
+ const risky = folders.filter((d) => /^~$|\/(Downloads|Desktop)$/i.test(d) || /^([A-Za-z]:)?\/?$/.test(d));
437
+ const named = risky.map((d) => (d === "~" ? "your home folder" : /Downloads$/i.test(d) ? "Downloads" : /Desktop$/i.test(d) ? "Desktop" : d));
438
+ parts.push(`started in ${plural(folders.length, "folder")}${named.length ? `, including ${list(named, 3)}` : ""}`);
439
+ const shown = folders.map((d) => (d === "~" ? "~ (your home folder)" : d));
440
+ details.push(`Has been started in ${plural(folders.length, "folder")}: ${list(shown, 6)}.`);
441
+ const approvals = folders.filter((d) => strs(json.projects[d]?.allowedTools).length);
442
+ if (approvals.length) details.push(`Remembers commands you approved in ${plural(approvals.length, "folder")}: ${list(approvals, 4)}.`);
443
+ return { parts, details };
444
+ }
445
+
446
+ // --- Codex -------------------------------------------------------------------
447
+
448
+ const CODEX_SANDBOX = {
449
+ "read-only": ["Read-only sandbox", "Sandbox: can read files but not change them."],
450
+ "workspace-write": ["Sandboxed to the project", "Sandbox: can change files only in the project folder."],
451
+ "danger-full-access": ["No sandbox", "No sandbox: commands can change any file and use the network."],
452
+ };
453
+ const CODEX_APPROVAL = {
454
+ untrusted: ["asks before most commands", "Asks before running anything outside a short list of safe commands. Newer versions of Codex don't accept this value."],
455
+ "on-failure": ["asks only when a command fails", "Runs commands in the sandbox and asks only when one fails. Codex has deprecated this value."],
456
+ "on-request": ["asks when it decides to", "Asks only when it decides a command needs your approval."],
457
+ never: ["never asks", "Never asks for approval."],
458
+ };
459
+
460
+ function codexConfig(toml) {
461
+ const parts = [];
462
+ const details = [];
463
+ if (!isObj(toml)) return { parts, details, summary: "Couldn't read the settings in this file." };
464
+ const sandbox = CODEX_SANDBOX[toml.sandbox_mode];
465
+ if (sandbox) {
466
+ parts.push(sandbox[0]);
467
+ details.push(sandbox[1]);
468
+ }
469
+ const approval = CODEX_APPROVAL[toml.approval_policy];
470
+ if (approval) {
471
+ parts.push(approval[0]);
472
+ details.push(approval[1]);
473
+ }
474
+ if (isObj(toml.approval_policy)) {
475
+ parts.push("approvals set per kind of action");
476
+ details.push(`Approvals are set per kind of action: ${list(Object.keys(toml.approval_policy), 5)}.`);
477
+ }
478
+ if (typeof toml.approvals_reviewer === "string") details.push(`Approval requests are reviewed by: ${clip(toml.approvals_reviewer, 30)}.`);
479
+ if (toml.sandbox_workspace_write?.network_access === true) details.push("Lets sandboxed commands use the network.");
480
+ if (typeof toml.model === "string") details.push(`Uses the ${toml.model} model.`);
481
+ if (isObj(toml.projects)) {
482
+ const trusted = Object.entries(toml.projects).filter(([, s]) => s?.trust_level === "trusted").map(([d]) => shortPath(d, 50));
483
+ const risky = (d) => d === "~" || /^~\/(downloads|desktop)$/i.test(d) || /^[a-z]:\/?$/i.test(d) || d === "/";
484
+ const home = trusted.includes("~");
485
+ if (trusted.length) {
486
+ parts.push(`trusts ${plural(trusted.length, "folder")}${home ? ", including your home folder" : ""}`);
487
+ const ordered = [...trusted.filter(risky), ...trusted.filter((d) => !risky(d))].map((d) => (d === "~" ? "~ (your home folder)" : d));
488
+ details.push(`Trusts ${list(ordered, 4)}.`);
489
+ }
490
+ }
491
+ if (isObj(toml.profiles) && Object.keys(toml.profiles).length) details.push(`Has ${plural(Object.keys(toml.profiles).length, "profile")}: ${list(Object.keys(toml.profiles), 4)}.`);
492
+ const notify = strs(toml.notify);
493
+ if (notify.length) details.push(`Runs ${commandText(notify[0], notify.slice(1), 60)} to send notifications.`);
494
+ const hooks = hookLines(toml.hooks);
495
+ parts.push(...hookParts(hooks));
496
+ details.push(...hooks);
497
+ namedFiles(parts, details, toml.project_doc_fallback_filenames);
498
+ let helpers = 0;
499
+ for (const [name, provider] of Object.entries(isObj(toml.model_providers) ? toml.model_providers : {}).slice(0, 10)) {
500
+ if (typeof provider?.auth?.command !== "string") continue;
501
+ helpers++;
502
+ details.push(`Runs ${commandText(provider.auth.command, strs(provider.auth.args), 60)} to get a key for the “${clip(name, 30)}” model provider.`);
503
+ }
504
+ for (const [name, server] of Object.entries(isObj(toml.mcp_servers) ? toml.mcp_servers : {}).slice(0, 20)) {
505
+ const helper = server?.http_headers_helper;
506
+ if (typeof helper !== "string" && !strs(helper).length) continue;
507
+ helpers++;
508
+ details.push(`Runs ${clip(Array.isArray(helper) ? strs(helper).join(" ") : helper, 60)} to make the request headers for MCP server “${clip(name, 30)}”.`);
509
+ }
510
+ if (helpers) parts.push(`runs ${plural(helpers, "command")} for keys or headers`);
511
+ const set = isObj(toml.shell_environment_policy?.set) ? Object.keys(toml.shell_environment_policy.set) : [];
512
+ if (set.length) {
513
+ parts.push(`sets ${plural(set.length, "environment variable")}`);
514
+ details.push(`Sets ${plural(set.length, "environment variable")} for the commands it runs: ${list(set.map((k) => clip(k, 30)), 5)}.`);
515
+ }
516
+ return { parts, details };
517
+ }
518
+
519
+ // --- Gemini, editors, OpenCode, Zed, Aider -----------------------------------
520
+
521
+ function geminiSettings(json) {
522
+ const parts = [];
523
+ const details = [];
524
+ if (!isObj(json)) return { parts, details };
525
+ const mode = [json.general?.defaultApprovalMode, json.defaultApprovalMode, json.approvalMode, json.general?.approvalMode, json.tools?.approvalMode].find((v) => typeof v === "string") ?? "";
526
+ // Gemini CLI turns YOLO mode on only from the command line, so a setting
527
+ // that asks for it changes nothing.
528
+ if (json.yolo === true || /^yolo$/i.test(mode)) {
529
+ parts.push("Asks for YOLO mode, which Gemini CLI ignores in settings");
530
+ details.push("Asks for YOLO mode. Current Gemini CLI turns YOLO on only with --yolo or --approval-mode=yolo, so this setting changes nothing.");
531
+ } else if (/^auto_edit$/i.test(mode)) {
532
+ parts.push("Edits files without asking");
533
+ details.push("Approval mode auto_edit: edits files without asking, and asks before other tools.");
534
+ } else if (/^plan$/i.test(mode)) {
535
+ parts.push("Plan mode");
536
+ details.push("Starts in plan mode: it reads and explores but changes nothing.");
537
+ }
538
+ if (json.autoAccept === true || json.tools?.autoAccept === true) {
539
+ parts.push("Accepts some tool calls without asking");
540
+ details.push("Accepts tool calls it considers safe without asking.");
541
+ }
542
+ const sandbox = json.sandbox ?? json.tools?.sandbox;
543
+ if (sandbox !== undefined) details.push(sandbox ? `Runs tools in a sandbox${typeof sandbox === "string" ? ` (${sandbox})` : ""}.` : "Sandbox turned off.");
544
+ const allowed = strs(json.coreTools ?? json.tools?.core ?? json.tools?.allowed);
545
+ if (allowed.length) details.push(`Tools it may use: ${list(allowed, 6)}.`);
546
+ const excluded = strs(json.excludeTools ?? json.tools?.exclude);
547
+ if (excluded.length) details.push(`Tools it may not use: ${list(excluded, 6)}.`);
548
+ namedFiles(parts, details, json.context?.fileName ?? json.contextFileName, ["GEMINI.md"]);
549
+ const discover = [json.tools?.discoveryCommand, json.toolDiscoveryCommand].find((c) => typeof c === "string" && c.trim());
550
+ if (discover) {
551
+ parts.push("runs its own command to find tools");
552
+ details.push(`Runs ${clip(discover, 60)} to find more tools.`);
553
+ }
554
+ const call = [json.tools?.callCommand, json.toolCallCommand].find((c) => typeof c === "string" && c.trim());
555
+ if (call) details.push(`Runs ${clip(call, 60)} to use them.`);
556
+ const hooks = hookLines(json.hooks);
557
+ parts.push(...hookParts(hooks));
558
+ details.push(...hooks);
559
+ return { parts, details };
560
+ }
561
+
562
+ function editorSettings(json) {
563
+ const parts = [];
564
+ const details = [];
565
+ if (!isObj(json)) return { parts, details };
566
+ if (json["chat.tools.autoApprove"] === true || json["chat.tools.global.autoApprove"] === true || json["chat.permissions.default"] === "autoApprove") {
567
+ parts.push("Runs agent tools without asking");
568
+ details.push("Agent mode runs tools and terminal commands without asking.");
569
+ }
570
+ if (json["github.copilot.chat.claudeAgent.allowDangerouslySkipPermissions"] === true) {
571
+ parts.push("lets the Claude agent skip every permission prompt");
572
+ details.push("The Claude agent in Copilot Chat can skip every permission prompt.");
573
+ }
574
+ if (json["chat.tools.terminal.ignoreDefaultAutoApproveRules"] === true) details.push("Ignores VS Code's built-in rules for terminal commands.");
575
+ const edits = json["chat.tools.edits.autoApprove"];
576
+ if (isObj(edits)) {
577
+ const on = Object.keys(edits).filter((k) => edits[k] === true);
578
+ if (on.length) details.push(`Edits that don't need approval: ${list(on.map((k) => clip(k, 40)), 5)}.`);
579
+ }
580
+ const terminal = json["chat.tools.terminal.autoApprove"] ?? json["github.copilot.chat.agent.terminal.allowList"];
581
+ if (isObj(terminal)) {
582
+ const on = Object.entries(terminal).filter(([, v]) => v === true || (isObj(v) && v.approve === true)).map(([k]) => k);
583
+ const off = Object.entries(terminal).filter(([, v]) => v === false || (isObj(v) && v.approve === false)).map(([k]) => k);
584
+ if (on.length) {
585
+ parts.push(`${plural(on.length, "terminal command")} approved automatically`);
586
+ details.push(`Terminal commands that run without asking: ${list(on.map((k) => clip(k, 40)), 6)}.`);
587
+ }
588
+ if (off.length) details.push(`Terminal commands that always ask: ${list(off.map((k) => clip(k, 40)), 6)}.`);
589
+ }
590
+ const agentKeys = Object.keys(json).filter((k) => /^(chat\.|github\.copilot|cursor\.|windsurf\.|codeium\.)/i.test(k));
591
+ if (agentKeys.length && !parts.length) details.push(`Changes ${plural(agentKeys.length, "agent setting")}: ${list(agentKeys, 5)}.`);
592
+ if (!agentKeys.length && !isObj(json.mcp)) return { parts, details, summary: "No agent settings changed." };
593
+ return { parts, details };
594
+ }
595
+
596
+ function openCode(json) {
597
+ const parts = [];
598
+ const details = [];
599
+ if (!isObj(json)) return { parts, details };
600
+ const perm = isObj(json.permission) ? json.permission : {};
601
+ for (const tool of ["edit", "bash", "webfetch"]) {
602
+ const v = perm[tool];
603
+ if (typeof v === "string") details.push(`${tool === "webfetch" ? "Web requests" : tool === "bash" ? "Shell commands" : "File edits"}: ${v === "allow" ? "run without asking" : v === "ask" ? "asks first" : v === "deny" ? "blocked" : v}.`);
604
+ }
605
+ if (perm.bash === "allow" || (isObj(perm.bash) && perm.bash["*"] === "allow")) parts.push("Runs shell commands without asking");
606
+ if (json.share === "auto") {
607
+ parts.push("shares every session automatically");
608
+ details.push("Shares every session to a public link automatically.");
609
+ } else if (typeof json.share === "string") details.push(`Session sharing: ${json.share}.`);
610
+ if (typeof json.model === "string") details.push(`Uses the ${json.model} model.`);
611
+ if (isObj(json.agent) && Object.keys(json.agent).length) details.push(`Defines ${plural(Object.keys(json.agent).length, "agent")}: ${list(Object.keys(json.agent), 4)}.`);
612
+ namedFiles(parts, details, json.instructions);
613
+ return { parts, details };
614
+ }
615
+
616
+ function zedSettings(json) {
617
+ const parts = [];
618
+ const details = [];
619
+ if (!isObj(json)) return { parts, details };
620
+ if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true || json.agent?.tool_permissions?.default === "allow") {
621
+ parts.push("Runs agent tools without asking");
622
+ details.push("The agent runs tool actions without asking.");
623
+ } else if (typeof json.agent?.tool_permissions?.default === "string") {
624
+ details.push(`Tool permissions default to “${clip(json.agent.tool_permissions.default, 20)}”.`);
625
+ }
626
+ if (json.session?.trust_all_worktrees === true) {
627
+ parts.push("trusts every project");
628
+ details.push("Trusts every project you open, so each one's own settings apply.");
629
+ }
630
+ const model = json.agent?.default_model?.model ?? json.assistant?.default_model?.model;
631
+ if (typeof model === "string") details.push(`Uses the ${model} model.`);
632
+ if (!parts.length && !details.length && !isObj(json.context_servers)) return { parts, details, summary: "No agent settings changed." };
633
+ return { parts, details };
634
+ }
635
+
636
+ function aiderConfig(file) {
637
+ const parts = [];
638
+ const details = [];
639
+ for (const line of file.lines ?? []) {
640
+ const colon = line.indexOf(":");
641
+ if (colon < 0) continue;
642
+ const key = line.slice(0, colon).trim();
643
+ const value = line.slice(colon + 1).trim();
644
+ if (!/^[a-z0-9-]+$/i.test(key) || !value) continue;
645
+ if (key === "yes-always" && /^true$/i.test(value)) {
646
+ parts.push("Confirms everything without asking");
647
+ details.push("Answers yes to every confirmation, including running commands.");
648
+ } else if (key === "model") details.push(`Uses the ${clip(value, 40)} model.`);
649
+ else if (key === "auto-commits") details.push(`Commits changes automatically: ${value}.`);
650
+ }
651
+ // The read list, as one value, a [list] or items under the key.
652
+ const read = [];
653
+ let inRead = false;
654
+ for (const line of file.lines ?? []) {
655
+ const top = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line);
656
+ if (top) {
657
+ inRead = top[1] === "read";
658
+ if (inRead && top[2].trim()) read.push(...top[2].replace(/^\[|\]$/g, "").split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")));
659
+ continue;
660
+ }
661
+ const item = inRead && /^\s+-\s+(.+)$/.exec(line);
662
+ if (item) read.push(item[1].trim().replace(/^["']|["']$/g, ""));
663
+ }
664
+ namedFiles(parts, details, read.filter(Boolean));
665
+ return { parts, details };
666
+ }
667
+
668
+ // --- Trusted folders, hooks and other agents' settings -----------------------
669
+
670
+ const RISKY_FOLDER = /^(~|\/|[a-z]:[\\/]?|(~|\/users\/[^/]+|\/home\/[^/]+|[a-z]:\/users\/[^/]+)(\/(downloads|desktop))?)$/i;
671
+
672
+ function trustedFolders(folders) {
673
+ const parts = [];
674
+ const details = [];
675
+ const shown = folders.map((d) => shortPath(d, 50));
676
+ if (!shown.length) return { parts, details, summary: "Trusts no folders." };
677
+ const risky = (d) => RISKY_FOLDER.test(d);
678
+ const home = shown.some((d) => d === "~");
679
+ parts.push(`trusts ${plural(shown.length, "folder")}${home ? ", including your home folder" : ""}`);
680
+ const ordered = [...shown.filter(risky), ...shown.filter((d) => !risky(d))].map((d) => (d === "~" ? "~ (your home folder)" : d));
681
+ details.push(`Trusts ${list(ordered, 5)}.`);
682
+ return { parts, details };
683
+ }
684
+
685
+ // Gemini CLI trusts a folder itself (TRUST_FOLDER) or the folder it's in (TRUST_PARENT).
686
+ function geminiTrusted(json) {
687
+ if (!isObj(json)) return [];
688
+ const parent = (d) => trimWord(d, "", "/\\").replace(/[\\/][^\\/]*$/, "") || "/";
689
+ return Object.entries(json).flatMap(([d, v]) => (v === "TRUST_FOLDER" ? [d] : v === "TRUST_PARENT" ? [parent(d)] : []));
690
+ }
691
+
692
+ // Every hook in a hooks setting, in any agent's format: event names mapped
693
+ // to lists of hooks, groups of hooks under a matcher, or a list of hooks
694
+ // that each name what sets them off. One line per hook, such as
695
+ // "PreToolUse: runs ./check.sh."
696
+ function hookLines(value, event = "", depth = 0, out = []) {
697
+ if (depth > 6 || out.length >= 50) return out;
698
+ if (Array.isArray(value)) {
699
+ for (const v of value.slice(0, 50)) hookLines(v, event, depth + 1, out);
700
+ return out;
701
+ }
702
+ if (!isObj(value)) return out;
703
+ const on = event || [value.trigger, value.when?.type, value.event].find((v) => typeof v === "string" && v.trim()) || "";
704
+ const command = [value.command, value.bash, value.powershell, value.action?.command, value.then?.command].find((c) => (typeof c === "string" && c.trim()) || strs(c).length);
705
+ const prompt = [value.prompt, value.action?.prompt, value.then?.prompt].find((c) => typeof c === "string" && c.trim());
706
+ const what = command !== undefined ? `runs ${clip(Array.isArray(command) ? strs(command).join(" ") : command, 80)}` : prompt ? `asks the agent “${clip(prompt, 80)}”` : null;
707
+ if (what) {
708
+ out.push(on ? `${clip(on, 40)}: ${what}.` : sentence(what));
709
+ return out;
710
+ }
711
+ for (const [k, v] of Object.entries(value)) if (k !== "matcher" && k !== "when") hookLines(v, depth === 0 && !event ? k : on, depth + 1, out);
712
+ return out;
713
+ }
714
+ const hookParts = (lines) => (lines.length ? [lines.length === 1 ? "has a hook" : `has ${lines.length} hooks`] : []);
715
+
716
+ function jsonHooks(json) {
717
+ const details = hookLines(isObj(json) && json.hooks !== undefined ? json.hooks : json);
718
+ return { parts: hookParts(details), details };
719
+ }
720
+
721
+ // Kiro and Amazon Q agent files: hooks, and tools the agent uses without
722
+ // asking. Their MCP servers are listed with the others.
723
+ function agentConfig(json) {
724
+ if (!isObj(json)) return { parts: [], details: [], summary: "Couldn't read the settings in this file." };
725
+ const details = hookLines(json.hooks);
726
+ const parts = hookParts(details);
727
+ const allowed = strs(json.allowedTools);
728
+ if (allowed.length) {
729
+ parts.push(`uses ${plural(allowed.length, "tool")} without asking`);
730
+ details.push(`Tools it uses without asking: ${list(allowed.map((t) => clip(t, 40)), 6)}.`);
731
+ }
732
+ if (typeof json.name === "string" && json.name.trim()) details.unshift(`Agent “${clip(json.name, 40)}”.`);
733
+ return { parts, details };
734
+ }
735
+
736
+ // What a Cursor background agent runs on the machine it works on.
737
+ function cursorEnvironment(json) {
738
+ if (!isObj(json)) return { parts: [], details: [], summary: "Couldn't read the settings in this file." };
739
+ const details = [];
740
+ if (typeof json.install === "string" && json.install.trim()) details.push(`Runs ${clip(json.install, 80)} to set up the machine.`);
741
+ if (typeof json.start === "string" && json.start.trim()) details.push(`Runs ${clip(json.start, 80)} each time an agent starts.`);
742
+ for (const t of (Array.isArray(json.terminals) ? json.terminals : []).filter((t) => isObj(t) && typeof t.command === "string").slice(0, 5)) {
743
+ details.push(`Opens a terminal${typeof t.name === "string" && t.name.trim() ? ` named “${clip(t.name, 30)}”` : ""} that runs ${clip(t.command, 60)}.`);
744
+ }
745
+ return { parts: details.length ? [`runs ${plural(details.length, "command")} for background agents`] : [], details };
746
+ }
747
+
748
+ // A Gemini CLI custom command: its name, what it asks the agent, and the
749
+ // shell commands it runs with !{...} before the prompt is sent.
750
+ function geminiCommand(path, toml) {
751
+ if (!isObj(toml)) return { parts: [], details: [], summary: "Couldn't read the settings in this file." };
752
+ const name = `/${path.replace(/^.*?\.gemini\/commands\//i, "").replace(/\.toml$/i, "").split("/").join(":")}`;
753
+ const prompt = typeof toml.prompt === "string" ? toml.prompt : "";
754
+ const shell = [...prompt.matchAll(/!\{([^}]{1,200})\}/g)].map((m) => m[1].trim());
755
+ const parts = [`command ${clip(name, 40)}`];
756
+ if (shell.length) parts.push(`runs ${plural(shell.length, "shell command")} when used`);
757
+ const details = [];
758
+ if (typeof toml.description === "string" && toml.description.trim()) details.push(`Described as: “${clip(toml.description, 80)}”`);
759
+ if (prompt.trim()) details.push(`Says: “${clip(prompt.trim().split("\n")[0], 80)}”`);
760
+ for (const c of shell.slice(0, 5)) details.push(`Runs ${clip(c, 60)} first.`);
761
+ return { parts, details };
762
+ }
763
+
764
+ // Files a setting names as instructions, beyond the agent's usual ones.
765
+ function namedFiles(parts, details, names, usual = []) {
766
+ const given = (typeof names === "string" ? [names] : Array.isArray(names) ? names : []).filter((n) => typeof n === "string" && n.trim()).map((n) => clip(n.trim(), 60));
767
+ if (!given.some((n) => !usual.includes(n))) return;
768
+ parts.push(`reads instructions from ${list(given.filter((n) => !usual.includes(n)), 3)}`);
769
+ details.push(`Reads its instructions from ${list(given, 6)}.`);
770
+ }
771
+
772
+ // VS Code tasks: what each runs, and which run as soon as the folder opens.
773
+ function vsCodeTasks(json) {
774
+ const tasks = (Array.isArray(json?.tasks) ? json.tasks : []).filter(isObj);
775
+ if (!tasks.length) return { parts: [], details: [] };
776
+ const text = (t) => clip([t.command, ...strs(t.args)].filter((w) => typeof w === "string").join(" ").trim(), 70);
777
+ const onOpen = tasks.filter((t) => t.runOptions?.runOn === "folderOpen");
778
+ const parts = [plural(tasks.length, "task")];
779
+ if (onOpen.length) parts.push(`${onOpen.length === 1 ? "1 runs" : `${onOpen.length} run`} when the folder opens`);
780
+ const details = tasks.slice(0, 20).map((t) => {
781
+ const name = typeof t.label === "string" && t.label.trim() ? `Task “${clip(t.label, 40)}”` : "A task";
782
+ const command = text(t);
783
+ return `${name}${command ? ` runs ${command}` : ""}${t.runOptions?.runOn === "folderOpen" ? ", as soon as the folder opens" : ""}.`;
784
+ });
785
+ return { parts, details };
786
+ }
787
+
788
+ // Codex command rules: which commands run without asking, which ask first
789
+ // and which are blocked.
790
+ const DECISIONS = { allow: (w) => `Lets ${w} run without asking`, prompt: (w) => `Asks before ${w}`, forbidden: (w) => `Blocks ${w}` };
791
+ function codexRules(file) {
792
+ const rules = parseCodexRules(file.content).filter((r) => r.pattern?.length && DECISIONS[r.decision]);
793
+ if (!rules.length) return { parts: [], details: [], summary: "No command rules this check can read." };
794
+ // Programs by name, so C:\Windows\...\powershell.exe -Command reads as
795
+ // powershell -Command.
796
+ const word = (w, i) => (i === 0 ? programName(w) : w);
797
+ const words = (r) => clip(r.pattern.slice(0, 5).map((w, i) => (Array.isArray(w) ? w.map((x) => word(x, i)).join(" or ") : w == null ? "…" : word(w, i))).join(" "), 60);
798
+ // The summary names each pattern by its program and first word.
799
+ const start = (r) => clip(r.pattern.slice(0, 2).map((w, i) => (Array.isArray(w) ? w.map((x) => word(x, i)).join(" or ") : w == null ? "…" : word(w, i))).join(" "), 40);
800
+ const parts = [];
801
+ for (const [decision, verb] of [["allow", "lets"], ["prompt", "asks before"], ["forbidden", "blocks"]]) {
802
+ const matching = rules.filter((r) => r.decision === decision);
803
+ if (!matching.length) continue;
804
+ const starts = [...new Set(matching.map(start))];
805
+ const what = matching.length === 1 ? starts[0] : `${plural(matching.length, "command")} starting with ${list(starts, 3)}`;
806
+ parts.push(decision === "allow" ? `${verb} ${what} run without asking` : `${verb} ${what}`);
807
+ }
808
+ const details = rules.slice(0, 30).map((r) => `${DECISIONS[r.decision](words(r))}${r.justification.trim() ? `: “${clip(r.justification, 60)}”` : ""}.`);
809
+ return { parts, details };
810
+ }
811
+
812
+ function cursorCli(json) {
813
+ const parts = [];
814
+ const details = [];
815
+ const allow = strs(json?.permissions?.allow);
816
+ const deny = strs(json?.permissions?.deny);
817
+ if (allow.length) {
818
+ parts.push(`allows ${plural(allow.length, "action")} without asking`);
819
+ details.push(`Allowed without asking: ${list(allow.map((r) => clip(r, 60)), 8)}.`);
820
+ }
821
+ if (deny.length) {
822
+ parts.push(`blocks ${plural(deny.length, "action")}`);
823
+ details.push(`Blocked: ${list(deny.map((r) => clip(r, 60)), 8)}.`);
824
+ }
825
+ return { parts, details };
826
+ }
827
+
828
+ function cursorSandbox(json) {
829
+ if (json?.type === "insecure_none") return { parts: ["No sandbox"], details: ["No sandbox: agent commands can change any file and use the network."] };
830
+ const details = [];
831
+ if (typeof json?.type === "string") details.push(`Sandbox type: ${clip(json.type, 30)}.`);
832
+ if (typeof json?.networkPolicy?.default === "string") details.push(`Network access by default: ${clip(json.networkPolicy.default, 20)}.`);
833
+ return { parts: [], details };
834
+ }
835
+
836
+ function claudePlugins(json) {
837
+ const names = isObj(json?.plugins) ? Object.keys(json.plugins) : [];
838
+ if (!names.length) return { parts: [], details: [], summary: "No plugins installed." };
839
+ return { parts: [`${plural(names.length, "plugin")} installed`], details: [`Installed plugins: ${list(names.map((n) => clip(n, 50)), 8)}.`] };
840
+ }
841
+
842
+ // Where a plugin marketplace's plugins come from, by its source type: a
843
+ // GitHub repository, a git or web address, or a folder.
844
+ function marketplaceKind(m) {
845
+ const src = isObj(m?.source) ? m.source : {};
846
+ const repo = typeof src.repo === "string" ? src.repo : "";
847
+ const url = typeof src.url === "string" ? src.url : "";
848
+ const kind = typeof src.source === "string" ? src.source : repo && !url ? "github" : url && !repo ? "git" : "";
849
+ return { kind, repo, url, path: typeof src.path === "string" ? src.path : "" };
850
+ }
851
+ export function marketplaceSource(m) {
852
+ const { kind, repo, url, path } = marketplaceKind(m);
853
+ return kind === "github" ? repo : kind === "git" || kind === "url" ? url : path || repo || url;
854
+ }
855
+ // True for a marketplace in Anthropic's own GitHub organization, named
856
+ // exactly: the address its source type uses, with no more path after the
857
+ // repository.
858
+ const ANTHROPIC_REPO = /^anthropics\/(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/i;
859
+ const ANTHROPIC_URL = /^(?:https:\/\/github\.com\/|git@github\.com:)anthropics\/(?!\.\.?(?:\.git)?\/?$)[A-Za-z0-9._-]{1,100}\/?$/i;
860
+ export function anthropicMarketplace(m) {
861
+ const { kind, repo, url } = marketplaceKind(m);
862
+ if (kind === "github") return ANTHROPIC_REPO.test(repo);
863
+ if (kind === "git" || kind === "url") return ANTHROPIC_URL.test(url);
864
+ return false;
865
+ }
866
+
867
+ // Where Claude Code can install plugins from, and who runs each place.
868
+ function claudeMarketplaces(json) {
869
+ const entries = isObj(json) ? Object.entries(json).filter(([, m]) => isObj(m)) : [];
870
+ if (!entries.length) return { parts: [], details: [], summary: "No plugin marketplaces added." };
871
+ const others = entries.filter(([, m]) => !anthropicMarketplace(m)).length;
872
+ const who = !others ? "all run by Anthropic" : others < entries.length ? `${others} not run by Anthropic` : entries.length === 1 ? "not run by Anthropic" : "none run by Anthropic";
873
+ return {
874
+ parts: [`${plural(entries.length, "plugin marketplace")}, ${who}`],
875
+ details: entries.slice(0, 50).map(([name, m]) => `Marketplace ${clip(name, 50)}: ${clip(marketplaceSource(m), 100) || "no source given"}${anthropicMarketplace(m) ? ", run by Anthropic" : ""}.`),
876
+ };
877
+ }
878
+
879
+ function codexRequirements(toml) {
880
+ const details = [];
881
+ if (!isObj(toml)) return { parts: [], details };
882
+ for (const [key, value] of Object.entries(toml)) {
883
+ const text = (v) => (typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : "");
884
+ if (Array.isArray(value)) details.push(`${key}: ${list(value.map(text).filter(Boolean).map((v) => clip(v, 30)), 6)}.`);
885
+ else if (text(value)) details.push(`${key}: ${clip(text(value), 40)}.`);
886
+ }
887
+ return { parts: details.length ? ["Limits what Codex settings may allow"] : [], details };
888
+ }
889
+
890
+ function clineState(json) {
891
+ const parts = [];
892
+ const details = [];
893
+ if (!isObj(json)) return { parts, details };
894
+ if (json.yoloModeToggled === true) {
895
+ parts.push("YOLO mode: approves everything");
896
+ details.push("YOLO mode is on: every action runs without asking.");
897
+ }
898
+ const auto = json.autoApprovalSettings;
899
+ if (isObj(auto) && auto.enabled !== false && isObj(auto.actions)) {
900
+ const on = Object.keys(auto.actions).filter((k) => auto.actions[k] === true);
901
+ if (on.length) {
902
+ if (!parts.length) parts.push(`auto-approves ${plural(on.length, "kind")} of action`);
903
+ details.push(`Approved without asking: ${list(on, 6)}.`);
904
+ }
905
+ }
906
+ return { parts, details };
907
+ }
908
+
909
+ function grokConfig(toml) {
910
+ const parts = [];
911
+ const details = [];
912
+ if (!isObj(toml)) return { parts, details, summary: "Couldn't read the settings in this file." };
913
+ const mode = toml.ui?.permission_mode ?? toml.permission_mode;
914
+ if (mode === "always-approve" || mode === "yolo") {
915
+ parts.push("Never asks");
916
+ details.push(`Permission mode “${mode}”: runs commands and edits without asking.`);
917
+ } else if (typeof mode === "string") details.push(`Permission mode: ${clip(mode, 30)}.`);
918
+ if (isObj(toml.sandbox)) details.push(`Sandbox settings: ${list(Object.keys(toml.sandbox), 5)}.`);
919
+ const status = toml.ui?.status_line?.command;
920
+ if (typeof status === "string" && status.trim()) {
921
+ parts.push("runs a command for its status line");
922
+ details.push(`Runs ${clip(status, 60)} to draw the status line.`);
923
+ }
924
+ return { parts, details };
925
+ }
926
+
927
+ function ampSettings(json) {
928
+ const parts = [];
929
+ const details = [];
930
+ if (!isObj(json)) return { parts, details };
931
+ if (json["amp.dangerouslyAllowAll"] === true) {
932
+ parts.push("Runs every tool without asking");
933
+ details.push("Runs every tool, including commands, without asking.");
934
+ }
935
+ const keys = Object.keys(json).filter((k) => k.startsWith("amp.") && k !== "amp.mcpServers" && k !== "amp.dangerouslyAllowAll");
936
+ if (keys.length) details.push(`Changes ${plural(keys.length, "setting")}: ${list(keys, 5)}.`);
937
+ return { parts, details };
938
+ }
939
+
940
+ // YAML, read line by line for the few keys that matter.
941
+ function gooseConfig(file) {
942
+ const parts = [];
943
+ const details = [];
944
+ const lines = file.lines ?? [];
945
+ const mode = lines.map((l) => l.match(/^GOOSE_MODE\s*:\s*["']?([\w-]+)/)?.[1]).find(Boolean);
946
+ if (mode === "auto") {
947
+ parts.push("Runs tools without asking");
948
+ details.push("Mode auto: runs tools and commands without asking.");
949
+ } else if (mode) details.push(`Mode: ${mode}.`);
950
+ const start = lines.findIndex((l) => /^extensions\s*:/.test(l));
951
+ if (start >= 0) {
952
+ const names = [];
953
+ for (const l of lines.slice(start + 1)) {
954
+ if (/^\S/.test(l)) break;
955
+ const m = l.match(/^ {2}([\w.-]+)\s*:\s*$/);
956
+ if (m) names.push(m[1]);
957
+ }
958
+ if (names.length) {
959
+ parts.push(`${plural(names.length, "extension")}: ${list(names, 3)}`);
960
+ details.push(`Extensions: ${list(names, 8)}.`);
961
+ }
962
+ }
963
+ return { parts, details };
964
+ }
965
+
966
+ function continueConfig(file) {
967
+ const parts = [];
968
+ const details = [];
969
+ for (const line of file.lines ?? []) {
970
+ const m = line.match(/^\s*(?:-\s*)?destination\s*:\s*["']?([^\s"'#]+)/i);
971
+ if (!m) continue;
972
+ let where = m[1];
973
+ try {
974
+ where = /^https?:/i.test(m[1]) ? new URL(m[1]).host : shortPath(m[1].replace(/^file:\/\//i, ""), 50);
975
+ } catch {}
976
+ details.push(`Sends session data to ${clip(where, 50)}.`);
977
+ }
978
+ if (details.length) parts.push(`sends session data to ${plural(details.length, "place")}`);
979
+ return { parts, details };
980
+ }
981
+
982
+ // --- Shell profiles and hook scripts -----------------------------------------
983
+
984
+ const AGENT_COMMANDS = /\b(claude|codex|gemini|qwen|opencode|cursor-agent|aider|amp|copilot|grok|kiro|q chat)\b/i;
985
+ const AGENT_ENV = /\b(ANTHROPIC|CLAUDE|OPENAI|CODEX|GEMINI|GOOGLE_GENAI|XAI|GROK|OPENROUTER|MISTRAL|DEEPSEEK)_[A-Z0-9_]+/;
986
+
987
+ // Lines in a shell profile that change how an agent starts or runs.
988
+ export function agentLines(file) {
989
+ const out = [];
990
+ for (const [i, line] of (file.lines ?? []).entries()) {
991
+ if (/^\s*#/.test(line) || !line.trim()) continue;
992
+ if (AGENT_COMMANDS.test(line) || AGENT_ENV.test(line)) out.push({ line: i + 1, text: line });
993
+ }
994
+ return out;
995
+ }
996
+
997
+ function shellProfile(file) {
998
+ const parts = [];
999
+ const details = [];
1000
+ const lines = agentLines(file);
1001
+ for (const { line, text } of lines) {
1002
+ const flag = findDangerFlag(text);
1003
+ const agent = text.match(AGENT_COMMANDS)?.[1];
1004
+ const env = text.match(AGENT_ENV)?.[0];
1005
+ if (flag && agent) {
1006
+ parts.push(`starts ${agent} with ${flag.flag}`);
1007
+ details.push(`Line ${line}: every time you run ${agent}, it adds ${flag.flag}.`);
1008
+ } else if (env) details.push(`Line ${line}: sets ${env} for every program you run.`);
1009
+ else details.push(`Line ${line}: ${clip(text, 80)}`);
1010
+ }
1011
+ if (!lines.length) return { parts, details, summary: "Nothing agent-related." };
1012
+ if (!parts.length) parts.push(`${plural(lines.length, "line")} about agents`);
1013
+ return { parts, details };
1014
+ }
1015
+
1016
+ function hookScript(file) {
1017
+ const commands = (file.lines ?? []).filter((l) => l.trim() && !/^\s*(#|\/\/|rem\b)/i.test(l));
1018
+ return {
1019
+ parts: [`hook script, ${plural(commands.length, "command line")}`],
1020
+ details: commands.slice(0, 6).map((l) => `Runs: ${clip(l, 80)}`),
1021
+ };
1022
+ }
1023
+
1024
+ // --- Instruction files -------------------------------------------------------
1025
+
1026
+ // Files where "@path" pulls another file in: Claude Code's CLAUDE.md files
1027
+ // and rules, and Gemini CLI's GEMINI.md. Elsewhere an @ is only text, such as
1028
+ // a package or model name.
1029
+ export const CAN_IMPORT = /(?:^|\/)(?:claude(?:\.local)?|gemini)\.md$|(?:^|\/)\.claude\/rules\//i;
1030
+ const RX_IMPORT = /(?:^|\s)@([~.\w/-][^\s]*\.[A-Za-z][\w-]{0,9})(?=$|[\s),;:.!?])/g;
1031
+
1032
+ // Whether an offset sits inside a `code span` on its line.
1033
+ export function inCodeSpan(text, index) {
1034
+ let ticks = 0;
1035
+ for (let j = text.lastIndexOf("\n", index - 1) + 1; j < index; j++) if (text.charCodeAt(j) === 96) ticks++;
1036
+ return ticks % 2 === 1;
1037
+ }
1038
+
1039
+ const DIRECTIVE =
1040
+ /^(?:always|never|don['’]?t|do not|must|should|use|run|prefer|avoid|make sure|ensure|keep|write|follow|add|remove|only|ignore|install|call|send|read|check|before|after|when|if|you|please|import|create|update|delete|commit|push|test|format|name|put|store|respond|reply|answer|ask|tell|do)\b/i;
1041
+
1042
+ // The front matter of a skill, agent or rule file, read as YAML so that
1043
+ // quoted, folded and multi-line values come out the way they were written.
1044
+ // Values are kept as one line of text; a block YAML can't read falls back to
1045
+ // plain key: value lines.
1046
+ function frontmatter(text) {
1047
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
1048
+ if (!m) return {};
1049
+ const block = m[1].slice(0, 20_000);
1050
+ const out = {};
1051
+ let yaml = null;
1052
+ try {
1053
+ yaml = parseYAML(block);
1054
+ } catch {
1055
+ yaml = null;
1056
+ }
1057
+ if (isObj(yaml)) {
1058
+ for (const [key, value] of Object.entries(yaml)) {
1059
+ if (!/^[A-Za-z][\w-]*$/.test(key)) continue;
1060
+ const text = ["string", "number", "boolean"].includes(typeof value) ? String(value) : Array.isArray(value) ? value.filter((v) => typeof v === "string").join(", ") : null;
1061
+ if (text !== null) out[key.toLowerCase()] = text.replace(/\s+/g, " ").trim();
1062
+ }
1063
+ return out;
1064
+ }
1065
+ for (const line of block.split(/\r?\n/)) {
1066
+ const kv = line.match(/^([A-Za-z][\w-]*)\s*:\s*(.*)$/);
1067
+ if (kv) out[kv[1].toLowerCase()] = kv[2].trim().replace(/^["']|["']$/g, "");
1068
+ }
1069
+ return out;
1070
+ }
1071
+
1072
+ function instructions(file) {
1073
+ const text = file.content.slice(0, 200_000);
1074
+ const fm = frontmatter(text);
1075
+ const body = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
1076
+ const lines = body.split(/\r?\n/);
1077
+ const nonEmpty = lines.filter((l) => l.trim()).length;
1078
+ // Headings and imports outside code blocks: a "# comment" in a shell
1079
+ // example isn't a section, and an @ in code imports nothing.
1080
+ const headings = [];
1081
+ const imports = [];
1082
+ let code = false;
1083
+ for (const line of lines) {
1084
+ if (/^\s*(```|~~~)/.test(line)) code = !code;
1085
+ else if (code) continue;
1086
+ else if (/^#{1,3}\s+\S/.test(line)) headings.push(clip(line.replace(/^#+\s*/, ""), 40));
1087
+ else if (CAN_IMPORT.test(file.path)) {
1088
+ const visible = line.slice(0, 2000).replace(/`[^`]*`/g, " ");
1089
+ for (const m of visible.matchAll(RX_IMPORT)) imports.push(`@${m[1]}`);
1090
+ }
1091
+ }
1092
+ // What it says, in the order it says it.
1093
+ const said = [];
1094
+ let fence = false;
1095
+ for (const raw of lines) {
1096
+ if (/^\s*(```|~~~)/.test(raw)) fence = !fence;
1097
+ // Code, headings and table rows aren't sentences the file says.
1098
+ if (fence || /^\s*(?:#|```|~~~|<!--|-->|-{3,}|\|)/.test(raw)) continue;
1099
+ // Lines are cut before links are tidied, so a line of thousands of
1100
+ // brackets can't slow it down. Only the start of a line is ever shown.
1101
+ const l = withoutComments(clean(raw.slice(0, 1000)))
1102
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "")
1103
+ .replace(/\*\*/g, "")
1104
+ .replace(/!?\[([^\]\n]{1,200})\]\([^)\s]{0,300}\)/g, "$1")
1105
+ .trim();
1106
+ if (l.length >= 4 && !/^@\S+$/.test(l)) said.push(l);
1107
+ if (said.length >= 40) break;
1108
+ }
1109
+ const directives = said.filter((l) => DIRECTIVE.test(l));
1110
+ const example = directives[0] ?? said[0];
1111
+
1112
+ // What it says that people can't see: invisible characters and comments.
1113
+ const hidden = [];
1114
+ for (const run of hiddenTags(text)) {
1115
+ const decoded = run.decoded.trim();
1116
+ if (decoded) hidden.push(`Hidden text you can't see when it's displayed: “${clip(maskSecrets(decoded).text, 100)}”`);
1117
+ if (hidden.length >= 4) break;
1118
+ }
1119
+ for (const c of hiddenComments(text)) {
1120
+ const inner = c.inner.trim();
1121
+ if (inner.length >= 8 && !/^(prettier-|eslint-|markdownlint|toc|end|start|region|endregion)/i.test(inner)) hidden.push(`Hidden in a comment: “${clip(inner, 100)}”`);
1122
+ if (hidden.length >= 4) break;
1123
+ }
1124
+
1125
+ const p = file.path;
1126
+ const name = fm.name ?? p.split("/").slice(-2, -1)[0];
1127
+ const parts = [];
1128
+ const details = [];
1129
+ const skill = /(^|\/)skills\/(?:[^/]+\/)+SKILL\.md$/i.test(p);
1130
+ if (skill || /(^|\/)\.claude\/(?:.+\/)?(agents|commands)\/[^/]+\.md$/i.test(p)) {
1131
+ const kind = skill ? "Skill" : /\/agents\/[^/]+$/i.test(p) ? "Subagent" : "Command";
1132
+ const label = kind === "Command" ? `/${p.split("/").pop().replace(/\.md$/i, "")}` : `“${name}”`;
1133
+ parts.push(`${kind} ${label}${fm.description ? `: ${clip(fm.description, 70)}` : ""}`);
1134
+ const tools = fm["allowed-tools"] ?? fm.tools;
1135
+ if (tools) details.push(`Can use: ${clip(tools, 80)}.`);
1136
+ if (fm.model) details.push(`Uses the ${fm.model} model.`);
1137
+ } else {
1138
+ const what = file.kind === "Memory" ? "saved memory" : "instructions";
1139
+ parts.push(`${plural(nonEmpty, "line")} of ${what}${example ? `, such as “${clip(example, 60)}”` : ""}`);
1140
+ }
1141
+ if (hidden.length) parts.push("also contains text that's hidden when you read it");
1142
+ if (fm.alwaysapply === "true") details.push("Applies to every request.");
1143
+ else if (fm.globs || fm.applyto) details.push(`Applies to files matching ${clip(fm.globs || fm.applyto, 60)}.`);
1144
+ else if (fm.description && !/skills|agents|commands/i.test(p)) details.push(`Applies when relevant to: ${clip(fm.description, 70)}.`);
1145
+ if (headings.length) details.push(period(`Sections: ${list(headings, 6)}`));
1146
+ if (imports.length) details.push(`Pulls in ${list([...new Set(imports)].map((i) => clip(i, 50)), 4)}.`);
1147
+ details.push(...hidden);
1148
+ for (const d of said.slice(0, 8)) details.push(`Says: “${clip(d, 90)}”`);
1149
+ // Only the first 40 lines are collected, so past that the count is a floor.
1150
+ if (said.length > 8) details.push(`And ${said.length >= 40 ? "at least " : ""}${plural(said.length - 8, "more line")}.`);
1151
+ return { parts, details };
1152
+ }