@misconfig/cli 1.3.2 → 1.5.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,232 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { controlFor, normalizeServer, packageSpec } from "../engine/index.js";
5
+ import { agentLines } from "../engine/explain.js";
6
+ import { parseJSONC, parseTOML, parseYAML } from "../engine/parse.js";
7
+ import { maskSecrets, isMasked, looksLikeToken } from "../engine/mask.js";
8
+ import { resolveUserPath } from "./discover.js";
9
+ import { LIMITS } from "../engine/paths.js";
10
+
11
+ const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
12
+ const sortKeys = (_key, value) => object(value)
13
+ ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]]))
14
+ : value;
15
+
16
+ // Only the keyed digest of a value is kept. A credential rotation must change
17
+ // that digest even when both values have the same masked representation.
18
+ export function fingerprint(secret, value) {
19
+ return createHmac("sha256", Buffer.from(secret, "hex")).update(JSON.stringify(value, sortKeys)).digest("hex");
20
+ }
21
+
22
+ function name(text) {
23
+ return maskSecrets(String(text)).text.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "�").slice(0, 160);
24
+ }
25
+
26
+ function word(value) {
27
+ return typeof value === "string" && /^[\w.@/-]{1,100}$/.test(value) && !isMasked(maskSecrets(value).text) && !looksLikeToken(value);
28
+ }
29
+
30
+ function program(command) {
31
+ const first = typeof command === "string" ? command.trim().match(/^[\w./\\-]+/)?.[0] : null;
32
+ const base = first?.split(/[\\/]/).at(-1);
33
+ return word(base) ? base : "command";
34
+ }
35
+
36
+ function serverSummary(def) {
37
+ if (!object(def)) return "server definition";
38
+ const { command, args, url } = normalizeServer("", def, null);
39
+ const pkg = command ? packageSpec(command, args) : null;
40
+ if (pkg && word(pkg.name) && (!pkg.version || /^\d+\.\d+\.\d+(?:[-+][\w.]+)?$/.test(pkg.version))) return pkg.name + (pkg.version ? "@" + pkg.version : " (unpinned)");
41
+ // URLs can carry account names, private hostnames and token-like path
42
+ // components. The history only needs to distinguish a remote server.
43
+ if (typeof url === "string") return "remote server";
44
+ return command ? program(command) : "server definition";
45
+ }
46
+
47
+ function hookSummary(hook) {
48
+ const command = typeof hook === "string" ? hook : hook?.command ?? hook?.bash ?? hook?.powershell;
49
+ if (typeof command !== "string") return typeof hook?.type === "string" && word(hook.type) ? hook.type : "hook definition";
50
+ const exe = program(command);
51
+ const args = command.trim().split(/\s+/);
52
+ if (/^(?:npm|pnpm|yarn|bun)$/.test(exe) && args[1] === "run" && word(args[2])) return exe + " run " + args[2];
53
+ const script = args[1]?.split(/[\\/]/).at(-1);
54
+ if (/^(?:node|python3?|bash|sh|pwsh)$/.test(exe) && word(script) && /\.(js|mjs|cjs|py|sh|ps1)$/i.test(script)) return exe + " " + script;
55
+ return exe;
56
+ }
57
+
58
+ const readableModes = new Set(["workspace-write", "read-only", "danger-full-access", "on-request", "on-failure", "never", "untrusted", "default", "plan", "acceptEdits", "bypassPermissions", "auto", "ask", "allow", "deny"]);
59
+ const privateValueContainer = /^(?:env|environment|envs|headers?|http[_-]?headers?)$/i;
60
+ const shellPolicy = /^shell[_-]?environment[_-]?policy$/i;
61
+ export const PRIVATE_SETTING_SUMMARY = "private setting";
62
+
63
+ function privateValueTrail(trail) {
64
+ const parents = trail.slice(0, -1);
65
+ if (parents.some((part) => privateValueContainer.test(part))) return true;
66
+ return parents.some((part, index) => shellPolicy.test(part) && /^(?:set|env|environment)$/i.test(parents[index + 1] ?? ""));
67
+ }
68
+
69
+ // Kept separate for migration of histories written by the early 1.4 preview.
70
+ export function privateValueLabel(label) {
71
+ const parts = String(label).split(" / ");
72
+ return privateValueTrail(parts);
73
+ }
74
+
75
+ function settingSummary(value, key, privateValue) {
76
+ if (privateValue) return PRIVATE_SETTING_SUMMARY;
77
+ if (/token|secret|passw|credential|api.?key|auth.?key/i.test(key)) return "credential setting";
78
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
79
+ if (readableModes.has(value)) return value;
80
+ if (/^(model|provider|version|logLevel)$/i.test(key) && word(value)) return value;
81
+ if (Array.isArray(value)) return value.length + (value.length === 1 ? " entry" : " entries");
82
+ return value === null ? "unset" : "configured value";
83
+ }
84
+
85
+ // File contents live only during discovery. The ledger receives names, short
86
+ // descriptions and hashes, never argument lists, hook bodies or env values.
87
+ export function computerSnapshot(secret, { home = homedir(), env = process.env } = {}) {
88
+ const items = {};
89
+ const fileRevisions = new Map();
90
+ const verified = new Set();
91
+ const uncertain = new Set();
92
+ const riskSources = new Map();
93
+ const hash = (v) => fingerprint(secret, v);
94
+ function collect(file, raw, flags = {}, original = raw) {
95
+ if (flags.sensitive || flags.listed) return;
96
+ const kind = controlFor(file)?.kind ?? flags.role;
97
+ if (!kind) return;
98
+ if (raw === null || flags.partial || flags.tooLarge || flags.invalid || raw.length > LIMITS.maxFileBytes) {
99
+ uncertain.add(file);
100
+ return;
101
+ }
102
+ const entries = {};
103
+ function add(trail, label, value, summary, fields, subject) {
104
+ const key = hash([file, trail]);
105
+ const parts = fields && Object.fromEntries(Object.entries(fields).map(([k,v]) => [k, hash(v)]));
106
+ entries[key] = { file, label: name(label), summary, hash: hash(value), ...(parts ? { parts } : {}), ...(subject ? { subject } : {}) };
107
+ }
108
+ function server(trail, id, def) {
109
+ const fields = {};
110
+ if (object(def)) for (const [k,v] of Object.entries(def)) {
111
+ const group = /^(env|environment|envs)$/.test(k) ? "environment" : /header/i.test(k) ? "headers" : /^(args|command|cmd)$/.test(k) ? "launch" : /^(url|httpUrl|serverUrl)$/.test(k) ? "address" : "settings";
112
+ (fields[group] ??= []).push([k,v]);
113
+ }
114
+ for (const list of Object.values(fields)) list.sort(([a],[b]) => a < b ? -1 : a > b ? 1 : 0);
115
+ const scope = trail[0] === "projects" ? " in " + name(trail[1]) : "";
116
+ add([...trail, id], "MCP " + name(id) + scope, def, serverSummary(def), fields, hash(["server", id]));
117
+ }
118
+ function hooks(trail, event, nodes) {
119
+ const list = Array.isArray(nodes) ? nodes : [nodes];
120
+ let ordinal = 0;
121
+ for (const node of list) {
122
+ const nested = object(node) && Array.isArray(node.hooks);
123
+ const group = nested ? Object.fromEntries(Object.entries(node).filter(([k]) => k !== "hooks")) : null;
124
+ for (const hook of nested ? node.hooks : [node]) {
125
+ ordinal++;
126
+ add([...trail, event, ordinal], "Hook " + event + " #" + ordinal, [group, hook], hookSummary(hook), { matcher: group, action: hook });
127
+ }
128
+ }
129
+ }
130
+ function visit(value, trail = []) {
131
+ const key = trail.at(-1) ?? "";
132
+ if (trail.length === 1 && kind === "Editor settings" && !/^(mcp$|mcp\.|chat\.|github\.copilot|cursor\.|windsurf\.|codeium\.|claudeCode\.)/i.test(key)) return;
133
+ if (trail.length === 1 && /\/\.cline\/data\/globalState\.json$/i.test(file) && !["yoloModeToggled", "autoApprovalSettings"].includes(key)) return;
134
+ const servers = /^(mcpServers|mcp_servers|context_servers|amp\.mcpServers)$/.test(key)
135
+ || (key === "mcp" && /opencode\.jsonc?$/i.test(file))
136
+ || (key === "servers" && (trail.at(-2) === "mcp" || /mcp\.json$/i.test(file)))
137
+ || (key === "extensions" && /goose\/config\.ya?ml$/i.test(file))
138
+ || (!trail.length && flags.role === "mcp-servers" && !value?.mcpServers);
139
+ if (servers && object(value)) {
140
+ for (const [id, def] of Object.entries(value)) server(trail, id, def);
141
+ } else if (servers && Array.isArray(value)) {
142
+ value.forEach((def, i) => server(trail, typeof def?.name === "string" ? def.name : String(i + 1), def));
143
+ } else if (trail.at(-2) === "permissions" && /^(allow|ask|deny)$/.test(key) && Array.isArray(value) && value.every((v) => typeof v === "string")) {
144
+ for (const rule of new Set(value)) {
145
+ const tool = rule.match(/^([\w.*-]+)(?:\((.*)\))?$/);
146
+ const what = tool && word(tool[1]) ? tool[1] + (tool[2] === "*" ? "(*)" : tool[2] ? " (" + program(tool[2]) + ")" : "") : "tool rule";
147
+ add([...trail, rule], "Permission " + key, rule, what);
148
+ }
149
+ } else if (key === "hooks" && object(value)) {
150
+ for (const [event, nodes] of Object.entries(value)) hooks(trail, event, nodes);
151
+ } else if (key === "hooks" && Array.isArray(value)) {
152
+ hooks(trail, "configured", value);
153
+ } else if (object(value) && trail.length < 32) {
154
+ for (const [k, v] of Object.entries(value)) visit(v, [...trail, k]);
155
+ } else if (!(trail[0] === "projects" && key === "allowedTools" && !value?.length)) {
156
+ add(trail, trail.map(name).join(" / ") || kind, value, settingSummary(value, key, privateValueTrail(trail)));
157
+ }
158
+ }
159
+ try {
160
+ const parser = /\.(jsonc?|kiro\.hook)$/i.test(file) ? parseJSONC : /\.toml$/i.test(file) ? parseTOML : /\.ya?ml$/i.test(file) ? parseYAML : null;
161
+ if (parser) {
162
+ const config = parser(raw);
163
+ const unparsed = object(config) && !Object.keys(config).length && parser !== parseJSONC && raw.split(/\r?\n/).some((l) => l.trim() && !l.trim().startsWith("#") && l.trim() !== "{}");
164
+ if (config === undefined || config === null || typeof config !== "object" || unparsed) {
165
+ uncertain.add(file);
166
+ return;
167
+ }
168
+ visit(config);
169
+ } else if (kind === "Shell profile") {
170
+ const lines = agentLines({ lines: raw.split(/\r?\n/) }).map((l) => l.text.trim());
171
+ if (lines.length) add([], kind, lines, lines.length + " agent-related line(s)");
172
+ } else {
173
+ const text = raw.replace(/\r\n/g, "\n");
174
+ const lines = text === "" ? 0 : text.replace(/\n$/, "").split("\n").length;
175
+ add([], kind, text, lines + (lines === 1 ? " line" : " lines"));
176
+ }
177
+ Object.assign(items, entries);
178
+ verified.add(file);
179
+ if (typeof original === "string" && original.length <= LIMITS.maxFileBytes) fileRevisions.set(file, hash(original.replace(/\r\n/g, "\n")));
180
+ } catch (err) {
181
+ if (!(err instanceof RangeError)) throw err;
182
+ uncertain.add(file);
183
+ }
184
+ }
185
+ function inventory(input, installed) {
186
+ // Use the same versions the scanner found. Native installers commonly
187
+ // name the last path component after the version being replaced.
188
+ for (const agent of installed.agents) {
189
+ if (agent.via === "project") continue;
190
+ const leaf = agent.path.split("/").at(-1);
191
+ const file = [agent.version, "app-" + agent.version].includes(leaf) ? agent.path.slice(0, -(leaf.length + 1)) : agent.path;
192
+ const key = hash(["install", file, agent.tool, agent.via]);
193
+ items[key] = { file, label: agent.tool + " (" + agent.via + ")", summary: agent.version, hash: hash(agent.version) };
194
+ verified.add(file);
195
+ }
196
+ for (const editor of installed.editors) {
197
+ verified.add(editor.dir);
198
+ const versions = new Map();
199
+ for (const agent of editor.agents) {
200
+ if (!versions.has(agent.id)) versions.set(agent.id, new Set());
201
+ versions.get(agent.id).add(agent.version || "unknown version");
202
+ }
203
+ for (const [id, found] of versions) {
204
+ const list = [...found].sort();
205
+ items[hash(["extension", editor.dir, id])] = { file: editor.dir, label: editor.editor + " extension " + id, summary: list.join(", "), hash: hash(list), inventoryDirectory: true };
206
+ }
207
+ }
208
+ for (const inst of input.installs) if (inst.via !== "project") riskSources.set(inst.path, hash([inst.package, inst.version]));
209
+ for (const editor of input.extensions) {
210
+ const items = editor.items.map((v) => [v.id, v.version, v.source]);
211
+ items.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
212
+ riskSources.set(editor.dir, hash(items));
213
+ }
214
+ for (const file of input.traces) riskSources.set(file, hash(["present", file]));
215
+ }
216
+ // Discovery can skip an unreadable file or directory. Only a confirmed
217
+ // missing file is a removal; a file still on disk needs another check.
218
+ async function checkMissing(prior) {
219
+ const files = new Map(Object.values(prior).map((item) => [item.file, item]));
220
+ await Promise.all([...files].filter(([f]) => !verified.has(f) && !uncertain.has(f)).map(async ([file, item]) => {
221
+ try {
222
+ const abs = resolveUserPath(file, { home, env });
223
+ await stat(abs);
224
+ if (item.inventoryDirectory && !(await readdir(abs)).length) return;
225
+ uncertain.add(file);
226
+ } catch (err) {
227
+ if (err.code !== "ENOENT" && err.code !== "ENOTDIR") uncertain.add(file);
228
+ }
229
+ }));
230
+ }
231
+ return { items, verified, uncertain, riskSources, fileRevisions, collect, inventory, checkMissing };
232
+ }
package/lib/demo.js ADDED
@@ -0,0 +1,32 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ // Each run owns a new sample home. Nothing in the fixture is executed, and
6
+ // the caller uses the normal scanner, review transactions and report writers.
7
+ export async function withDemo(run) {
8
+ const home = await mkdtemp(path.join(tmpdir(), "misconfig-demo-"));
9
+ const file = path.join(home, ".claude.json"), session = path.join(home, "sample-codex.jsonl");
10
+ const config = (version) => JSON.stringify({
11
+ mcpServers: {
12
+ calendar: { command: "npx", args: ["-y", "@example/calendar@" + version] },
13
+ mail: { command: "npx", args: ["-y", "@example/mail"] },
14
+ },
15
+ });
16
+ try {
17
+ await writeFile(file, config("1.2.3") + "\n", { mode: 0o600 });
18
+ return await run({
19
+ discovery: { dir: home, home, env: {}, sampleFiles: ["~/.claude.json"] },
20
+ store: path.join(home, ".misconfig", "computer-v1"),
21
+ session,
22
+ bump: async () => {
23
+ await writeFile(file, config("1.2.4") + "\n");
24
+ const diff = "@@ -1 +1 @@\n-" + config("1.2.3") + "\n+" + config("1.2.4") + "\n";
25
+ const payload = { type: "patch_apply_end", call_id: "demo", success: true, status: "completed", changes: { [file]: { type: "update", unified_diff: diff, move_path: null } } };
26
+ await writeFile(session, JSON.stringify({ timestamp: new Date().toISOString(), type: "event_msg", payload }) + "\n", { mode: 0o600 });
27
+ },
28
+ });
29
+ } finally {
30
+ await rm(home, { recursive: true, force: true });
31
+ }
32
+ }
package/lib/discover.js CHANGED
@@ -16,8 +16,17 @@ import { TRACES, AGENT_PACKAGES, KNOWN_PACKAGES, VERSION_RE } from "../engine/kn
16
16
  export const PLATFORM = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "mac" : "linux";
17
17
  const LOOSE_NAMES = /\.(md|mdc|txt)$/i;
18
18
 
19
+ export function displayUserPath(abs, home) {
20
+ if (home) {
21
+ const rel = path.relative(home, abs);
22
+ if (!rel) return "~";
23
+ if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
24
+ }
25
+ return abs.split(path.sep).join("/");
26
+ }
27
+
19
28
  // `limits` is for tests; the command always uses LIMITS from the engine.
20
- export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS } = {}) {
29
+ export async function discover({ dir = process.cwd(), includeUser = true, home = homeDir(), env = process.env, limits = LIMITS, onComputerFile, sampleFiles } = {}) {
21
30
  const projectDir = path.resolve(dir);
22
31
  const info = await fs.stat(projectDir).catch(() => null);
23
32
  if (!info?.isDirectory()) throw new Error(`There's no folder at ${projectDir}.`);
@@ -25,19 +34,14 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
25
34
  const files = [];
26
35
  const seen = new Set();
27
36
  const lineMaps = {};
37
+ let collectingComputer = false;
28
38
  let masked = 0;
29
39
 
30
- const tilde = (abs) => {
31
- if (home) {
32
- const rel = path.relative(home, abs);
33
- if (!rel) return "~";
34
- if (!rel.startsWith("..") && !path.isAbsolute(rel)) return "~/" + rel.split(path.sep).join("/");
35
- }
36
- return abs.split(path.sep).join("/");
37
- };
38
- const add = (enginePath, raw, size, extra = {}) => {
40
+ const tilde = (abs) => displayUserPath(abs, home);
41
+ const add = (enginePath, raw, size, extra = {}, original = raw) => {
39
42
  if (seen.has(enginePath)) return;
40
43
  seen.add(enginePath);
44
+ if (collectingComputer && onComputerFile) onComputerFile(enginePath, raw, extra, original);
41
45
  if (raw === null) return files.push({ path: enginePath, size, ...extra });
42
46
  const m = maskSecrets(raw);
43
47
  masked += m.count;
@@ -212,20 +216,20 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
212
216
  // --- The home folder and app settings ------------------------------------
213
217
  // Each file keeps its usual name (~/.claude/settings.json) even when an
214
218
  // environment variable moved it, so the checks still recognize it.
219
+ collectingComputer = withUser;
215
220
  if (withUser) {
216
221
  const userFiles = [];
217
- for (const entry of LOCATIONS) {
218
- for (const p of userPaths(entry, PLATFORM)) {
219
- for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
220
- const enginePath = name ?? tilde(abs);
221
- if (!p.endsWith("/")) {
222
- userFiles.push({ abs, enginePath });
223
- continue;
224
- }
225
- // In a folder, only the files agents read.
226
- const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
227
- for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
222
+ // The demo supplies only its own fixture paths and skips host inventories.
223
+ for (const p of sampleFiles ?? LOCATIONS.flatMap((entry) => userPaths(entry, PLATFORM))) {
224
+ for (const { abs, name } of await expand(resolveUserPath(p, { home, env }), p.startsWith("~") ? p : null)) {
225
+ const enginePath = name ?? tilde(abs);
226
+ if (!p.endsWith("/")) {
227
+ userFiles.push({ abs, enginePath });
228
+ continue;
228
229
  }
230
+ // In a folder, only the files agents read.
231
+ const nameOf = (f) => enginePath.replace(/\/?$/, "/") + path.relative(abs, f).split(path.sep).join("/");
232
+ for (const f of await listFiles(abs, 4, (f) => ["content", "listed"].includes(classifyPath(nameOf(f))), (d) => insideSkill(nameOf(d)))) userFiles.push({ abs: f, enginePath: nameOf(f) });
229
233
  }
230
234
  }
231
235
  // With CLAUDE_CONFIG_DIR set, ~/.claude.json may live in that folder.
@@ -238,9 +242,12 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
238
242
  if (/(^|[\\/])\.claude\.json$/.test(abs)) {
239
243
  const stat = await fs.stat(abs).catch(() => null);
240
244
  const raw = stat?.isFile() ? await readText(abs) : null;
241
- if (raw === null) continue;
245
+ if (raw === null) {
246
+ if (stat?.isFile()) add(enginePath, null, stat.size, { invalid: true });
247
+ continue;
248
+ }
242
249
  const reduced = reduceClaudeJson(raw, tilde);
243
- add(enginePath, reduced.text, stat.size);
250
+ add(enginePath, reduced.text, stat.size, reduced.invalid ? { invalid: true } : {}, raw);
244
251
  if (reduced.lineMap) lineMaps[enginePath] = reduced.lineMap;
245
252
  continue;
246
253
  }
@@ -273,8 +280,9 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
273
280
  // If an agent has run in, or trusts, Downloads or the home folder, check
274
281
  // the loose instruction files there too. Only the settings on this
275
282
  // computer say where agents have run; a project's own copies don't count.
283
+ collectingComputer = false;
276
284
  const risky = new Set();
277
- for (const f of withUser ? files : []) {
285
+ for (const f of withUser && !sampleFiles ? files : []) {
278
286
  if (!f.content || !/^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
279
287
  for (const d of agentFolders(f.path, f.content)) if (riskyPlace(d)) risky.add(d.startsWith("~") ? d : tilde(path.resolve(d)));
280
288
  }
@@ -296,7 +304,7 @@ export async function discover({ dir = process.cwd(), includeUser = true, home =
296
304
  const locked = scanningHome ? [] : await lockedPackages(projectDir);
297
305
  let extensions = [];
298
306
  let traces = [];
299
- if (withUser) {
307
+ if (withUser && !sampleFiles) {
300
308
  installs.push(...(await agentInstalls({ home, env, tilde })));
301
309
  extensions = await editorExtensions({ home, env, tilde });
302
310
  traces = await traceFiles({ home, env });
@@ -608,14 +616,14 @@ export function resolveUserPath(p, { home, env }) {
608
616
  // has been started in and their tool approvals. lineMap[i] is the line in
609
617
  // the real file that reduced line i + 1 came from, so findings point at
610
618
  // lines people can open.
611
- function reduceClaudeJson(raw, tilde) {
619
+ export function reduceClaudeJson(raw, tilde) {
612
620
  let json;
613
621
  try {
614
622
  json = JSON.parse(raw);
615
623
  } catch {
616
- return { text: "{}", lineMap: null };
624
+ return { text: "{}", lineMap: null, invalid: true };
617
625
  }
618
- if (!json || typeof json !== "object") return { text: "{}", lineMap: null };
626
+ if (!json || typeof json !== "object" || Array.isArray(json)) return { text: "{}", lineMap: null, invalid: true };
619
627
  const keys = new Map(); // reduced key, as JSON, -> key in the real file, as JSON
620
628
  const out = {};
621
629
  for (const [k, v] of Object.entries(json)) {
@@ -0,0 +1,122 @@
1
+ import { lstat, open, opendir } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { LIMITS } from "../engine/paths.js";
5
+ import { computerSnapshot, fingerprint } from "./computer-snapshot.js";
6
+ import { displayUserPath, reduceClaudeJson, resolveUserPath } from "./discover.js";
7
+ import { visitEdits } from "./edit-records.js";
8
+ import { addEditorEvidence, linkEditors } from "./review-history.js";
9
+
10
+ const WEEK = 7 * 86400000;
11
+ const TAIL = 4 * 1024 * 1024;
12
+ const BUDGET = 32 * 1024 * 1024;
13
+ const pathKey = (s) => process.platform === "win32" ? s.toLowerCase() : s;
14
+
15
+ async function recentSessions(home, env, since, report) {
16
+ const roots = [path.join(env.CLAUDE_CONFIG_DIR || path.join(home, ".claude"), "projects"),
17
+ ...["sessions", "archived_sessions"].map((dir) => path.join(env.CODEX_HOME || path.join(home, ".codex"), dir))];
18
+ const queue = roots.slice(), found = [];
19
+ let entries = 0;
20
+ for (let i = 0; i < queue.length; i++) {
21
+ try {
22
+ if (!(await lstat(queue[i])).isDirectory()) continue;
23
+ const dir = await opendir(queue[i]);
24
+ for await (const entry of dir) {
25
+ if (++entries > 8192) { report.limited = true; break; }
26
+ const file = path.join(queue[i], entry.name);
27
+ if (entry.isDirectory()) queue.push(file);
28
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
29
+ const info = await lstat(file);
30
+ if (info.mtimeMs >= since) found.push({ file, time: info.mtimeMs });
31
+ }
32
+ } catch (e) { if (e.code !== "ENOENT") report.limited = true; }
33
+ if (entries > 8192) break;
34
+ }
35
+ return found.sort((a,b) => b.time - a.time).map((x) => x.file);
36
+ }
37
+
38
+ async function readTail(file, room, report) {
39
+ if (!(await lstat(file)).isFile()) { report.limited = true; return; }
40
+ const fd = await open(file, "r");
41
+ try {
42
+ const stat = await fd.stat();
43
+ if (!stat.isFile()) { report.limited = true; return; }
44
+ const size = Math.min(room, TAIL, stat.size);
45
+ const data = Buffer.alloc(size);
46
+ let length = 0;
47
+ while (length < size) {
48
+ const { bytesRead } = await fd.read(data, length, size - length, stat.size - size + length);
49
+ if (!bytesRead) break;
50
+ length += bytesRead;
51
+ }
52
+ if (length < size) report.limited = true;
53
+ let text = data.toString("utf8", 0, length);
54
+ if (size < stat.size) {
55
+ report.limited = true;
56
+ const newline = text.indexOf("\n");
57
+ text = newline < 0 ? "" : text.slice(newline + 1);
58
+ }
59
+ return { length, text };
60
+ } finally { await fd.close(); }
61
+ }
62
+
63
+ function itemsFor(key, file, raw, home) {
64
+ if (raw === null) return {};
65
+ if (typeof raw !== "string" || Buffer.byteLength(raw) > LIMITS.maxFileBytes) return;
66
+ if (file === "~/.claude.json") {
67
+ const reduced = reduceClaudeJson(raw, (p) => displayUserPath(p, home));
68
+ if (reduced.invalid) return;
69
+ raw = reduced.text;
70
+ }
71
+ const snapshot = computerSnapshot(key);
72
+ snapshot.collect(file, raw);
73
+ if (snapshot.verified.has(file)) return snapshot.items;
74
+ }
75
+
76
+ export async function attributeEdits(state, review, currentFiles, { sessions = [], home = homedir(), env = process.env } = {}) {
77
+ const report = { filesRead: 0, matchedEdits: 0, limited: false };
78
+ const since = sessions.length ? 0 : Date.now() - WEEK;
79
+ const targets = new Map();
80
+ for (const event of state.history.events) {
81
+ if (event.action !== "observed" || !event.transition || event.at < since) continue;
82
+ const abs = pathKey(resolveUserPath(event.file, { home, env }));
83
+ if (!targets.has(abs)) targets.set(abs, { file: event.file, events: [] });
84
+ targets.get(abs).events.push(event);
85
+ }
86
+ if (!targets.size) return report;
87
+ const matched = new Set();
88
+ function visit(target, at, name, reconstruct) {
89
+ const eligible = target.events.filter((e) => e.since <= at && at <= e.at);
90
+ if (!eligible.length || at < since) return;
91
+ const pair = reconstruct(currentFiles.get(target.file));
92
+ if (!pair) return;
93
+ // A hunk alone cannot prove which occurrence it changed after files
94
+ // have moved around. Bind reconstructed text to both scan snapshots.
95
+ const digests = pair[2] ? pair.slice(0, 2).map((s) => s === null ? null : fingerprint(state.key, s.replace(/\r\n/g, "\n"))) : null;
96
+ const before = itemsFor(state.key, target.file, pair[0], home);
97
+ const after = itemsFor(state.key, target.file, pair[1], home);
98
+ if (!before || !after) return;
99
+ for (const e of eligible) {
100
+ if (digests && (digests[0] !== e.priorFile || digests[1] !== e.nextFile)) continue;
101
+ const a = before[e.subject]?.hash ?? null, b = after[e.subject]?.hash ?? null;
102
+ if (a === b || e.transition !== "c-" + fingerprint(state.key, [e.subject, a, b]).slice(0, 20)) continue;
103
+ addEditorEvidence(state.history, e, { name, basis: "tool-record", at });
104
+ matched.add(e.id);
105
+ }
106
+ }
107
+ const files = sessions.length ? [...new Set(sessions)] : await recentSessions(home, env, since, report);
108
+ let remaining = BUDGET;
109
+ if (files.length > 48) report.limited = true;
110
+ for (const file of files.slice(0, 48)) {
111
+ if (!remaining) { report.limited = true; break; }
112
+ let part;
113
+ try { part = await readTail(file, remaining, report); } catch { report.limited = true; }
114
+ if (!part) continue;
115
+ remaining -= part.length;
116
+ report.filesRead++;
117
+ visitEdits(part.text, (abs) => abs && targets.get(pathKey(abs)), visit);
118
+ }
119
+ report.matchedEdits = matched.size;
120
+ linkEditors(state.history, [...review.changes, ...review.pending]);
121
+ return report;
122
+ }
@@ -0,0 +1,125 @@
1
+ import path from "node:path";
2
+ import { LIMITS } from "../engine/paths.js";
3
+
4
+ function absolute(file, cwd) {
5
+ if (typeof file !== "string" || !file || file.includes("\0")) return null;
6
+ if (path.isAbsolute(file)) return path.normalize(file);
7
+ return typeof cwd === "string" && path.isAbsolute(cwd) ? path.resolve(cwd, file) : null;
8
+ }
9
+
10
+ // Reverse only numbered, exact unified-diff hunks. A context or line-count
11
+ // mismatch means the current file cannot establish the earlier setting.
12
+ export function beforePatch(after, diff) {
13
+ if (typeof after !== "string" || typeof diff !== "string") return;
14
+ if (diff.length > LIMITS.maxFileBytes * 3) return;
15
+ const current = after.replace(/\r\n/g, "\n").match(/[^\n]*\n|[^\n]+$/g) ?? [];
16
+ const patch = diff.replace(/\r\n/g, "\n").split("\n");
17
+ if (patch.at(-1) === "") patch.pop();
18
+ let i = 0, cursor = 0, hunks = 0;
19
+ const original = [];
20
+ if (patch[0]?.startsWith("--- ") && patch[1]?.startsWith("+++ ")) i = 2;
21
+ while (i < patch.length) {
22
+ const h = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@.*$/.exec(patch[i++]);
23
+ if (!h) return;
24
+ const oldCount = Number(h[2] ?? 1), newCount = Number(h[4] ?? 1);
25
+ const start = Number(h[3]) - (newCount ? 1 : 0);
26
+ if (start < cursor || start > current.length || original.length + start - cursor !== Number(h[1]) - (oldCount ? 1 : 0)) return;
27
+ while (cursor < start) original.push(current[cursor++]);
28
+ let oldLines = 0, newLines = 0;
29
+ while (i < patch.length && !patch[i].startsWith("@@ ")) {
30
+ const line = patch[i++], op = line[0];
31
+ if (![" ", "+", "-"].includes(op)) return;
32
+ let value = line.slice(1) + "\n";
33
+ if (patch[i] === "\") { value = line.slice(1); i++; }
34
+ if (op !== "-") { if (current[cursor++] !== value) return; newLines++; }
35
+ if (op !== "+") { original.push(value); oldLines++; }
36
+ }
37
+ if (oldLines !== oldCount || newLines !== newCount) return;
38
+ hunks++;
39
+ }
40
+ if (hunks) return original.join("") + current.slice(cursor).join("");
41
+ }
42
+
43
+ function replaceLiteral(text, oldValue, newValue, all) {
44
+ if (typeof text !== "string" || typeof oldValue !== "string" || !oldValue || typeof newValue !== "string") return;
45
+ if ([text, oldValue, newValue].some((s) => s.length > LIMITS.maxFileBytes)) return;
46
+ const at = text.indexOf(oldValue);
47
+ if (at < 0 || (!all && text.indexOf(oldValue, at + 1) !== -1)) return;
48
+ if (!all) return text.slice(0, at) + newValue + text.slice(at + oldValue.length);
49
+ const fragments = text.split(oldValue);
50
+ if (text.length + (fragments.length - 1) * (newValue.length - oldValue.length) > LIMITS.maxFileBytes) return;
51
+ return fragments.join(newValue);
52
+ }
53
+
54
+ function claudeEdit(call, result, current) {
55
+ const { input, name } = call;
56
+ if (result.userModified === true || result.success === false || result.is_error || result.error) return;
57
+ if (name === "Write") {
58
+ if (typeof input.content !== "string" || (result.content !== undefined && result.content !== input.content)) return;
59
+ if (typeof result.originalFile === "string") return [result.originalFile, input.content];
60
+ if (result.type === "create" && result.originalFile == null) return [null, input.content];
61
+ } else {
62
+ const { old_string: oldValue, new_string: newValue, replace_all: all } = input;
63
+ if (typeof oldValue !== "string" || typeof newValue !== "string" || oldValue === newValue) return;
64
+ if ((result.oldString !== undefined && result.oldString !== oldValue) || (result.newString !== undefined && result.newString !== newValue)) return;
65
+ if (typeof result.originalFile === "string") {
66
+ const after = replaceLiteral(result.originalFile, oldValue, newValue, all);
67
+ if (after !== undefined) return [result.originalFile, after];
68
+ } else if (result.success === true && !all) {
69
+ const before = replaceLiteral(current, newValue, oldValue, false);
70
+ if (before !== undefined) return [before, current, true];
71
+ }
72
+ }
73
+ }
74
+
75
+ // Only completed file-tool records qualify. Conversations, shell commands,
76
+ // pending patches and user-modified tool calls cannot establish an editor.
77
+ export function visitEdits(text, targetFor, visit) {
78
+ const calls = new Map();
79
+ let cwd;
80
+ for (const line of text.split("\n")) {
81
+ if (!line.includes("tool_use") && !line.includes("tool_result") && !line.includes("patch_apply_end") && !line.includes("item_completed") && !line.includes("session_meta") && !line.includes("turn_context")) continue;
82
+ let r;
83
+ try { r = JSON.parse(line); } catch { continue; }
84
+ if (!r || typeof r !== "object") continue;
85
+ const p = r.payload;
86
+ if ((r.type === "session_meta" || r.type === "turn_context") && typeof p?.cwd === "string") { cwd = p.cwd; continue; }
87
+ if (r.type === "assistant" && r.message?.role === "assistant" && Array.isArray(r.message.content)) {
88
+ for (const call of r.message.content) {
89
+ if (call?.type !== "tool_use" || !["Edit", "Write"].includes(call.name) || typeof call.id !== "string") continue;
90
+ const target = targetFor(absolute(call.input?.file_path, r.cwd));
91
+ if (target) calls.set(call.id, { ...call, target, session: r.sessionId });
92
+ }
93
+ continue;
94
+ }
95
+ const at = typeof r.timestamp === "string" ? Date.parse(r.timestamp) : NaN;
96
+ if (!Number.isFinite(at)) continue;
97
+ if (r.type === "user" && r.message?.role === "user" && Array.isArray(r.message.content) && r.toolUseResult) {
98
+ const replies = r.message.content.filter((c) => c?.type === "tool_result");
99
+ if (replies.length !== 1) continue;
100
+ const reply = replies[0], call = calls.get(reply.tool_use_id);
101
+ calls.delete(reply.tool_use_id);
102
+ if (!call || call.session !== r.sessionId || reply.is_error === true || typeof r.toolUseResult !== "object") continue;
103
+ const target = targetFor(absolute(r.toolUseResult.filePath, r.cwd));
104
+ if (target !== call.target) continue;
105
+ visit(target, at, "Claude Code", (current) => claudeEdit(call, r.toolUseResult, current));
106
+ }
107
+ if (r.type !== "event_msg" || !p) continue;
108
+ let changes;
109
+ if (p.type === "patch_apply_end" && p.success === true && (p.status === undefined || p.status === "completed")) changes = p.changes;
110
+ if (p.type === "item_completed" && p.item?.type === "FileChange" && p.item.status === "completed") changes = p.item.changes;
111
+ if (!changes || typeof changes !== "object" || Array.isArray(changes)) continue;
112
+ for (const [name, change] of Object.entries(changes)) {
113
+ const target = targetFor(absolute(name, cwd));
114
+ if (!target || !change || change.move_path) continue;
115
+ visit(target, at, "Codex", (current) => {
116
+ if (change.type === "add" && typeof change.content === "string") return [null, change.content, true];
117
+ if (change.type === "delete" && typeof change.content === "string") return [change.content, null, true];
118
+ if (change.type === "update") {
119
+ const before = beforePatch(current, change.unified_diff);
120
+ if (before !== undefined) return [before, current, true];
121
+ }
122
+ });
123
+ }
124
+ }
125
+ }