mason-context 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -237,6 +237,19 @@ Add the printed block to `.claude/settings.json` — the *committed* project set
237
237
 
238
238
  For faster fires than `npx` resolution allows, install the package (`npm i -D mason-context`) and point the command at `node_modules/.bin/mason-hook`.
239
239
 
240
+ ## Diff review (mason-review)
241
+
242
+ A classic agent failure mode is the local edit that misses its coupled update — the serializer without the migration, the config without its consumer. The coupling is invisible to static analysis, but it's sitting in git history. `mason-review` diffs the current branch against a base ref and reports two things:
243
+
244
+ ```bash
245
+ npx -p mason-context mason-review --base origin/main
246
+ ```
247
+
248
+ - **Missing co-change partners** — files that changed together with a changed file in ≥60% of its commits (≥4 shared, 1500-commit window) but are absent from this diff. Evidence-based but heuristic-grade: a missing partner is a question to ask the diff, not proof of a bug. These drive exit 1.
249
+ - **Touched decisions** — decision records whose anchor files the diff touches, listed as constraints to verify against. Informational; never affect the exit code.
250
+
251
+ Deterministic, no LLM, one pass over git history (~100ms). Run it locally before pushing, or wire it into CI as an advisory check (`mason-review || true` if you want the signal without the gate).
252
+
240
253
  ## Confluence sync
241
254
 
242
255
  Keep a Confluence wiki in sync with the concept map, in plain product language that PMs and designers can read. Each sync rewrites the snapshot through your assistant into PM-friendly descriptions, pushes one page per feature, and posts a "what changed since last sync" entry to a changelog page. Mason owns these pages and overwrites each one on every sync, so edit the code, not the page — manual edits to a page body are replaced. Re-running a sync with no code change is a no-op: it makes no Confluence edits at all.
package/dist/mason-mcp.js CHANGED
@@ -3947,7 +3947,7 @@ function createMcpServer() {
3947
3947
  const server = new McpServer(
3948
3948
  {
3949
3949
  name: "mason",
3950
- version: "0.8.1"
3950
+ version: "0.9.0"
3951
3951
  },
3952
3952
  {
3953
3953
  instructions: "Mason maintains a persistent feature-to-file concept map of this codebase so you can skip manual exploration. RULE: when given a task, bug, or change request, call `get_context` with the task text first \u2014 one call returns the relevant features, files, tests, blast radius, and freshness. Before answering ANY question about features, architecture, data flows, or where something lives \u2014 and before any grep/glob/file-read exploration for such a question \u2014 call `get_snapshot` first. One call returns the whole map and replaces 5-10 search round-trips; if it has drifted it says so and self-corrects. Likewise call `get_impact` BEFORE editing or refactoring a file (git co-change history + references + related tests \u2014 signals you cannot get from reading the file itself), and `mason_check_drift` to verify the map is fresh in long sessions. When you learn something the code alone can't tell you \u2014 a failed approach, a deprecation, a workaround's reason, a review-settled convention \u2014 record it with `save_decision` so the whole team's assistants inherit it; `get_context` returns matching decisions as constraints. If `get_snapshot` reports no snapshot exists, offer to set Mason up: `mason_init` returns a setup playbook (a Map-Reduce loop of `generate_snapshot_batch` + `save_partial_snapshot`, then `reduce_snapshot` + `save_snapshot`, optionally `mason_set_confluence`, then `mason_complete_init`). `full_analysis`, `analyze_project`, and `get_code_samples` are read-only diagnostics for unmapped projects and never need init. Mason has no CLI; everything happens through these tools."
@@ -0,0 +1,418 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/review/cli.ts
4
+ import path8 from "path";
5
+
6
+ // src/review/review.ts
7
+ import fs5 from "fs/promises";
8
+ import path7 from "path";
9
+ import { execFile as execFile5 } from "child_process";
10
+ import { promisify as promisify5 } from "util";
11
+
12
+ // src/drift/drift.ts
13
+ import fs3 from "fs/promises";
14
+ import path4 from "path";
15
+ import { execFile as execFile3 } from "child_process";
16
+ import { promisify as promisify3 } from "util";
17
+
18
+ // src/snapshot/snapshot.ts
19
+ import fs2 from "fs/promises";
20
+ import path3 from "path";
21
+ import { execFile as execFile2 } from "child_process";
22
+ import { promisify as promisify2 } from "util";
23
+ import fg3 from "fast-glob";
24
+
25
+ // src/mcp/sampler.ts
26
+ import fs from "fs/promises";
27
+ import path from "path";
28
+ import { execFile } from "child_process";
29
+ import { promisify } from "util";
30
+ import fg from "fast-glob";
31
+ var exec = promisify(execFile);
32
+
33
+ // src/test-map.ts
34
+ import path2 from "path";
35
+ import fg2 from "fast-glob";
36
+
37
+ // src/snapshot/snapshot.ts
38
+ var exec2 = promisify2(execFile2);
39
+
40
+ // src/drift/drift.ts
41
+ var exec3 = promisify3(execFile3);
42
+ async function getChangesWithStatus(resolvedRoot, fromHash) {
43
+ if (!fromHash || fromHash === "unknown") return null;
44
+ try {
45
+ const { stdout } = await exec3(
46
+ "git",
47
+ ["diff", "--name-status", "-M", fromHash, "HEAD"],
48
+ { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }
49
+ );
50
+ const changes = [];
51
+ for (const line of stdout.split("\n")) {
52
+ if (!line.trim()) continue;
53
+ const parts = line.split(" ");
54
+ if (parts.some((p) => p.startsWith(".mason/"))) continue;
55
+ const code = parts[0];
56
+ if (code.startsWith("R") && parts.length >= 3) {
57
+ changes.push({
58
+ status: "renamed",
59
+ path: parts[2],
60
+ previousPath: parts[1]
61
+ });
62
+ } else if (code.startsWith("C") && parts.length >= 3) {
63
+ changes.push({ status: "added", path: parts[2] });
64
+ } else if (code === "A" && parts.length >= 2) {
65
+ changes.push({ status: "added", path: parts[1] });
66
+ } else if (code === "D" && parts.length >= 2) {
67
+ changes.push({ status: "deleted", path: parts[1] });
68
+ } else if (parts.length >= 2) {
69
+ changes.push({ status: "modified", path: parts[1] });
70
+ }
71
+ }
72
+ return changes;
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ // src/decisions/decisions.ts
79
+ import fs4 from "fs/promises";
80
+ import path6 from "path";
81
+ import { createHash } from "crypto";
82
+
83
+ // src/context/lexical.ts
84
+ import path5 from "path";
85
+
86
+ // src/decisions/decisions.ts
87
+ function decisionsDir(rootDir) {
88
+ return path6.join(rootDir, ".mason", "decisions");
89
+ }
90
+ async function loadDecisions(rootDir) {
91
+ let entries;
92
+ try {
93
+ entries = await fs4.readdir(decisionsDir(rootDir));
94
+ } catch {
95
+ return [];
96
+ }
97
+ const records = [];
98
+ for (const entry of entries) {
99
+ if (!entry.endsWith(".json")) continue;
100
+ try {
101
+ const raw = await fs4.readFile(
102
+ path6.join(decisionsDir(rootDir), entry),
103
+ "utf-8"
104
+ );
105
+ const parsed = JSON.parse(raw);
106
+ if (parsed.version !== 1 || !parsed.id || !parsed.title || !parsed.body) {
107
+ continue;
108
+ }
109
+ records.push(parsed);
110
+ } catch {
111
+ continue;
112
+ }
113
+ }
114
+ return records.sort((a, b) => a.id.localeCompare(b.id));
115
+ }
116
+
117
+ // src/review/cochange.ts
118
+ import { execFile as execFile4 } from "child_process";
119
+ import { promisify as promisify4 } from "util";
120
+ var exec4 = promisify4(execFile4);
121
+ var HISTORY_COMMITS = 1500;
122
+ var MIN_FILE_COMMITS = 5;
123
+ var MIN_SHARED_COMMITS = 4;
124
+ var MIN_COCHANGE_RATE = 0.6;
125
+ var MAX_COMMIT_FILES = 30;
126
+ async function buildMatrix(resolvedRoot) {
127
+ try {
128
+ const { stdout } = await exec4(
129
+ "git",
130
+ ["log", `-n${HISTORY_COMMITS}`, "--format=%x01", "--name-only", "-M"],
131
+ { cwd: resolvedRoot, maxBuffer: 100 * 1024 * 1024 }
132
+ );
133
+ const commitsByFile = /* @__PURE__ */ new Map();
134
+ const blocks = stdout.split("");
135
+ let index = 0;
136
+ for (const block of blocks) {
137
+ const files = block.split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith(".mason/"));
138
+ if (files.length === 0 || files.length > MAX_COMMIT_FILES) continue;
139
+ for (const file of files) {
140
+ let set = commitsByFile.get(file);
141
+ if (!set) {
142
+ set = /* @__PURE__ */ new Set();
143
+ commitsByFile.set(file, set);
144
+ }
145
+ set.add(index);
146
+ }
147
+ index++;
148
+ }
149
+ return { commitsByFile, totalCommits: index };
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+ async function findMissingPartners(resolvedRoot, changedFiles, existsOnDisk) {
155
+ const matrix = await buildMatrix(resolvedRoot);
156
+ if (!matrix) return null;
157
+ const changedSet = new Set(changedFiles);
158
+ const findings = [];
159
+ for (const changedFile of changedFiles) {
160
+ const fileCommits = matrix.commitsByFile.get(changedFile);
161
+ if (!fileCommits || fileCommits.size < MIN_FILE_COMMITS) continue;
162
+ for (const [partner, partnerCommits] of matrix.commitsByFile) {
163
+ if (partner === changedFile || changedSet.has(partner)) continue;
164
+ let shared = 0;
165
+ for (const c of fileCommits) {
166
+ if (partnerCommits.has(c)) shared++;
167
+ }
168
+ if (shared < MIN_SHARED_COMMITS) continue;
169
+ const rate = shared / fileCommits.size;
170
+ if (rate < MIN_COCHANGE_RATE) continue;
171
+ if (!await existsOnDisk(partner)) continue;
172
+ findings.push({
173
+ changedFile,
174
+ missingPartner: partner,
175
+ sharedCommits: shared,
176
+ fileCommits: fileCommits.size,
177
+ rate: Math.round(rate * 100) / 100
178
+ });
179
+ }
180
+ }
181
+ findings.sort((a, b) => b.rate - a.rate || b.sharedCommits - a.sharedCommits);
182
+ return findings;
183
+ }
184
+
185
+ // src/review/review.ts
186
+ var exec5 = promisify5(execFile5);
187
+ var MAX_ANALYZED_FILES = 50;
188
+ async function resolveMergeBase(resolvedRoot, base) {
189
+ try {
190
+ const { stdout } = await exec5("git", ["merge-base", base, "HEAD"], {
191
+ cwd: resolvedRoot
192
+ });
193
+ return stdout.trim() || null;
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+ async function defaultBase(resolvedRoot) {
199
+ for (const ref of ["origin/HEAD", "origin/main", "origin/master", "main"]) {
200
+ try {
201
+ await exec5("git", ["rev-parse", "--verify", "--quiet", ref], {
202
+ cwd: resolvedRoot
203
+ });
204
+ return ref;
205
+ } catch {
206
+ }
207
+ }
208
+ return null;
209
+ }
210
+ function anchorsTouched(record, changedFiles) {
211
+ return changedFiles.filter(
212
+ (file) => record.files.some((anchor) => {
213
+ const a = anchor.replace(/\/+$/, "");
214
+ return a === file || file.startsWith(`${a}/`);
215
+ })
216
+ );
217
+ }
218
+ async function computeReview(rootDir, base) {
219
+ const resolvedRoot = path7.resolve(rootDir);
220
+ const mergeBase = await resolveMergeBase(resolvedRoot, base);
221
+ if (!mergeBase) return null;
222
+ const changes = await getChangesWithStatus(resolvedRoot, mergeBase);
223
+ if (changes === null) return null;
224
+ const changedFiles = [
225
+ ...new Set(
226
+ changes.filter((c) => c.status !== "deleted").map((c) => c.path)
227
+ )
228
+ ].sort();
229
+ const report = {
230
+ version: 1,
231
+ root: resolvedRoot,
232
+ base,
233
+ mergeBase,
234
+ changedFiles,
235
+ missingPartners: [],
236
+ touchedDecisions: [],
237
+ historyAvailable: true,
238
+ truncated: false
239
+ };
240
+ if (changedFiles.length === 0) return report;
241
+ let analyzed = changedFiles;
242
+ if (changedFiles.length > MAX_ANALYZED_FILES) {
243
+ analyzed = changedFiles.slice(0, MAX_ANALYZED_FILES);
244
+ report.truncated = true;
245
+ }
246
+ const partners = await findMissingPartners(
247
+ resolvedRoot,
248
+ analyzed,
249
+ async (relPath) => {
250
+ try {
251
+ await fs5.access(path7.join(resolvedRoot, relPath));
252
+ return true;
253
+ } catch {
254
+ return false;
255
+ }
256
+ }
257
+ );
258
+ if (partners === null) {
259
+ report.historyAvailable = false;
260
+ } else {
261
+ report.missingPartners = partners;
262
+ }
263
+ const decisions = await loadDecisions(resolvedRoot);
264
+ for (const record of decisions) {
265
+ if (record.status !== "active" || record.files.length === 0) continue;
266
+ const touched = anchorsTouched(record, changedFiles);
267
+ if (touched.length > 0) {
268
+ report.touchedDecisions.push({
269
+ id: record.id,
270
+ title: record.title,
271
+ body: record.body,
272
+ category: record.category,
273
+ anchors: record.files,
274
+ touchedFiles: touched
275
+ });
276
+ }
277
+ }
278
+ return report;
279
+ }
280
+
281
+ // src/review/cli.ts
282
+ var USAGE = `Usage: mason-review [--dir <path>] [--base <ref>] [--json]
283
+
284
+ Reviews the current branch's diff against what git history and the Mason
285
+ decision store know:
286
+ - co-change partners the diff forgot: files that historically change
287
+ together with a changed file (>=60% of its commits, >=4 shared) but are
288
+ absent from this diff
289
+ - recorded decisions whose anchor files the diff touches (informational)
290
+ Deterministic: no LLM call, no network \u2013 safe for CI.
291
+
292
+ Options:
293
+ --dir <path> Project root (default: current directory)
294
+ --base <ref> Base ref to diff against via merge-base (default: origin/HEAD,
295
+ origin/main, origin/master, or main \u2013 first that resolves)
296
+ --json Full report as JSON (additive-only schema)
297
+ --help Show this help
298
+
299
+ Exit codes:
300
+ 0 no missing co-change partners (touched decisions alone do not fail)
301
+ 1 missing co-change partners found
302
+ 2 error (base unresolvable, not a git repository, bad arguments)`;
303
+ function parseArgs(argv) {
304
+ const parsed = {
305
+ dir: process.cwd(),
306
+ base: void 0,
307
+ json: false,
308
+ help: false
309
+ };
310
+ for (let i = 0; i < argv.length; i++) {
311
+ const arg = argv[i];
312
+ if (arg === "--json") {
313
+ parsed.json = true;
314
+ } else if (arg === "--help" || arg === "-h") {
315
+ parsed.help = true;
316
+ } else if (arg === "--dir") {
317
+ const value = argv[++i];
318
+ if (!value) throw new Error("--dir requires a path argument");
319
+ parsed.dir = value;
320
+ } else if (arg === "--base") {
321
+ const value = argv[++i];
322
+ if (!value) throw new Error("--base requires a ref argument");
323
+ parsed.base = value;
324
+ } else if (!arg.startsWith("-") && parsed.dir === process.cwd()) {
325
+ parsed.dir = arg;
326
+ } else {
327
+ throw new Error(`Unknown argument: ${arg}`);
328
+ }
329
+ }
330
+ return parsed;
331
+ }
332
+ function formatReviewSummary(report) {
333
+ const lines = [];
334
+ lines.push(
335
+ `Diff vs ${report.base} (merge-base ${report.mergeBase.slice(0, 7)}): ${report.changedFiles.length} changed file${report.changedFiles.length === 1 ? "" : "s"}.`
336
+ );
337
+ if (report.truncated) {
338
+ lines.push(
339
+ `Large diff \u2013 co-change analysis limited to the first ${50} files.`
340
+ );
341
+ }
342
+ if (!report.historyAvailable) {
343
+ lines.push(
344
+ "Git history unavailable (shallow clone?) \u2013 co-change analysis skipped."
345
+ );
346
+ }
347
+ if (report.missingPartners.length > 0) {
348
+ lines.push("Possible forgotten co-change partners:");
349
+ for (const f of report.missingPartners) {
350
+ lines.push(
351
+ ` [missing-partner] ${f.changedFile} changed without ${f.missingPartner} \u2013 they changed together in ${Math.round(f.rate * 100)}% of ${f.changedFile}'s last ${f.fileCommits} commits (${f.sharedCommits} shared)`
352
+ );
353
+ }
354
+ }
355
+ if (report.touchedDecisions.length > 0) {
356
+ lines.push("Recorded decisions touched by this diff (constraints \u2013 verify the diff respects them):");
357
+ for (const d of report.touchedDecisions) {
358
+ lines.push(
359
+ ` [decision] ${d.title} (${d.category}; via ${d.touchedFiles.join(", ")})`
360
+ );
361
+ }
362
+ }
363
+ lines.push(
364
+ report.missingPartners.length === 0 ? "No missing co-change partners." : `${report.missingPartners.length} possible omission${report.missingPartners.length === 1 ? "" : "s"}.`
365
+ );
366
+ return lines.join("\n");
367
+ }
368
+ async function runReviewCli(argv, io = {
369
+ out: (line) => process.stdout.write(`${line}
370
+ `),
371
+ err: (line) => process.stderr.write(`${line}
372
+ `)
373
+ }) {
374
+ let args;
375
+ try {
376
+ args = parseArgs(argv);
377
+ } catch (error) {
378
+ io.err(error instanceof Error ? error.message : String(error));
379
+ io.err(USAGE);
380
+ return 2;
381
+ }
382
+ if (args.help) {
383
+ io.out(USAGE);
384
+ return 0;
385
+ }
386
+ const rootDir = path8.resolve(args.dir);
387
+ const base = args.base ?? await defaultBase(rootDir);
388
+ if (!base) {
389
+ io.err(
390
+ `Could not find a base ref in ${rootDir} (tried origin/HEAD, origin/main, origin/master, main). Pass one with --base.`
391
+ );
392
+ return 2;
393
+ }
394
+ const report = await computeReview(rootDir, base);
395
+ if (!report) {
396
+ io.err(
397
+ `Could not resolve a merge base between ${base} and HEAD in ${rootDir} \u2013 not a git repository, unknown ref, or unrelated histories.`
398
+ );
399
+ return 2;
400
+ }
401
+ if (args.json) {
402
+ io.out(JSON.stringify(report, null, 2));
403
+ } else {
404
+ io.out(formatReviewSummary(report));
405
+ }
406
+ return report.missingPartners.length > 0 ? 1 : 0;
407
+ }
408
+
409
+ // bin/mason-review.ts
410
+ runReviewCli(process.argv.slice(2)).then(
411
+ (code) => process.exit(code),
412
+ (err) => {
413
+ process.stderr.write(`mason-review error: ${err}
414
+ `);
415
+ process.exit(2);
416
+ }
417
+ );
418
+ //# sourceMappingURL=mason-review.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/review/cli.ts","../src/review/review.ts","../src/drift/drift.ts","../src/snapshot/snapshot.ts","../src/mcp/sampler.ts","../src/test-map.ts","../src/decisions/decisions.ts","../src/context/lexical.ts","../src/review/cochange.ts","../bin/mason-review.ts"],"sourcesContent":["import path from \"node:path\";\nimport { computeReview, defaultBase } from \"./review.js\";\nimport type { ReviewReport } from \"./review.js\";\n\nexport const USAGE = `Usage: mason-review [--dir <path>] [--base <ref>] [--json]\n\nReviews the current branch's diff against what git history and the Mason\ndecision store know:\n - co-change partners the diff forgot: files that historically change\n together with a changed file (>=60% of its commits, >=4 shared) but are\n absent from this diff\n - recorded decisions whose anchor files the diff touches (informational)\nDeterministic: no LLM call, no network – safe for CI.\n\nOptions:\n --dir <path> Project root (default: current directory)\n --base <ref> Base ref to diff against via merge-base (default: origin/HEAD,\n origin/main, origin/master, or main – first that resolves)\n --json Full report as JSON (additive-only schema)\n --help Show this help\n\nExit codes:\n 0 no missing co-change partners (touched decisions alone do not fail)\n 1 missing co-change partners found\n 2 error (base unresolvable, not a git repository, bad arguments)`;\n\nexport interface ReviewCliIo {\n out: (line: string) => void;\n err: (line: string) => void;\n}\n\ninterface ParsedArgs {\n dir: string;\n base: string | undefined;\n json: boolean;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const parsed: ParsedArgs = {\n dir: process.cwd(),\n base: undefined,\n json: false,\n help: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--json\") {\n parsed.json = true;\n } else if (arg === \"--help\" || arg === \"-h\") {\n parsed.help = true;\n } else if (arg === \"--dir\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--dir requires a path argument\");\n parsed.dir = value;\n } else if (arg === \"--base\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--base requires a ref argument\");\n parsed.base = value;\n } else if (!arg.startsWith(\"-\") && parsed.dir === process.cwd()) {\n parsed.dir = arg;\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n return parsed;\n}\n\nexport function formatReviewSummary(report: ReviewReport): string {\n const lines: string[] = [];\n lines.push(\n `Diff vs ${report.base} (merge-base ${report.mergeBase.slice(0, 7)}): ${report.changedFiles.length} changed file${report.changedFiles.length === 1 ? \"\" : \"s\"}.`\n );\n if (report.truncated) {\n lines.push(\n `Large diff – co-change analysis limited to the first ${50} files.`\n );\n }\n if (!report.historyAvailable) {\n lines.push(\n \"Git history unavailable (shallow clone?) – co-change analysis skipped.\"\n );\n }\n\n if (report.missingPartners.length > 0) {\n lines.push(\"Possible forgotten co-change partners:\");\n for (const f of report.missingPartners) {\n lines.push(\n ` [missing-partner] ${f.changedFile} changed without ${f.missingPartner} – they changed together in ${Math.round(f.rate * 100)}% of ${f.changedFile}'s last ${f.fileCommits} commits (${f.sharedCommits} shared)`\n );\n }\n }\n\n if (report.touchedDecisions.length > 0) {\n lines.push(\"Recorded decisions touched by this diff (constraints – verify the diff respects them):\");\n for (const d of report.touchedDecisions) {\n lines.push(\n ` [decision] ${d.title} (${d.category}; via ${d.touchedFiles.join(\", \")})`\n );\n }\n }\n\n lines.push(\n report.missingPartners.length === 0\n ? \"No missing co-change partners.\"\n : `${report.missingPartners.length} possible omission${report.missingPartners.length === 1 ? \"\" : \"s\"}.`\n );\n return lines.join(\"\\n\");\n}\n\nexport async function runReviewCli(\n argv: string[],\n io: ReviewCliIo = {\n out: (line) => process.stdout.write(`${line}\\n`),\n err: (line) => process.stderr.write(`${line}\\n`),\n }\n): Promise<number> {\n let args: ParsedArgs;\n try {\n args = parseArgs(argv);\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n io.err(USAGE);\n return 2;\n }\n\n if (args.help) {\n io.out(USAGE);\n return 0;\n }\n\n const rootDir = path.resolve(args.dir);\n const base = args.base ?? (await defaultBase(rootDir));\n if (!base) {\n io.err(\n `Could not find a base ref in ${rootDir} (tried origin/HEAD, origin/main, origin/master, main). Pass one with --base.`\n );\n return 2;\n }\n\n const report = await computeReview(rootDir, base);\n if (!report) {\n io.err(\n `Could not resolve a merge base between ${base} and HEAD in ${rootDir} – not a git repository, unknown ref, or unrelated histories.`\n );\n return 2;\n }\n\n if (args.json) {\n io.out(JSON.stringify(report, null, 2));\n } else {\n io.out(formatReviewSummary(report));\n }\n return report.missingPartners.length > 0 ? 1 : 0;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport { loadDecisions } from \"../decisions/decisions.js\";\nimport type { DecisionRecord } from \"../decisions/decisions.js\";\nimport { findMissingPartners } from \"./cochange.js\";\nimport type { CochangeFinding } from \"./cochange.js\";\n\nconst exec = promisify(execFile);\n\n/** Diffs larger than this are refactors; partner analysis would be noise. */\nconst MAX_ANALYZED_FILES = 50;\n\nexport interface TouchedDecision {\n id: string;\n title: string;\n body: string;\n category: string;\n anchors: string[];\n touchedFiles: string[];\n}\n\nexport interface ReviewReport {\n /** Additive-only schema. */\n version: 1;\n root: string;\n base: string;\n mergeBase: string;\n changedFiles: string[];\n /** Historical partners this diff leaves untouched — drive exit 1. */\n missingPartners: CochangeFinding[];\n /** Decisions whose anchors the diff touches — informational only. */\n touchedDecisions: TouchedDecision[];\n historyAvailable: boolean;\n truncated: boolean;\n}\n\nasync function resolveMergeBase(\n resolvedRoot: string,\n base: string\n): Promise<string | null> {\n try {\n const { stdout } = await exec(\"git\", [\"merge-base\", base, \"HEAD\"], {\n cwd: resolvedRoot,\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/** First base ref that resolves: origin/HEAD, origin/main, origin/master, main. */\nexport async function defaultBase(resolvedRoot: string): Promise<string | null> {\n for (const ref of [\"origin/HEAD\", \"origin/main\", \"origin/master\", \"main\"]) {\n try {\n await exec(\"git\", [\"rev-parse\", \"--verify\", \"--quiet\", ref], {\n cwd: resolvedRoot,\n });\n return ref;\n } catch {\n // Try the next candidate.\n }\n }\n return null;\n}\n\nfunction anchorsTouched(\n record: DecisionRecord,\n changedFiles: string[]\n): string[] {\n return changedFiles.filter((file) =>\n record.files.some((anchor) => {\n const a = anchor.replace(/\\/+$/, \"\");\n return a === file || file.startsWith(`${a}/`);\n })\n );\n}\n\n/**\n * Review a diff against what git history and the decision store know:\n * co-change partners the diff forgot, and recorded constraints it touches.\n * Deterministic — no LLM, no network. Returns null when the base ref or\n * merge base cannot be resolved.\n */\nexport async function computeReview(\n rootDir: string,\n base: string\n): Promise<ReviewReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const mergeBase = await resolveMergeBase(resolvedRoot, base);\n if (!mergeBase) return null;\n\n const changes = await getChangesWithStatus(resolvedRoot, mergeBase);\n if (changes === null) return null;\n\n const changedFiles = [\n ...new Set(\n changes\n .filter((c) => c.status !== \"deleted\")\n .map((c) => c.path)\n ),\n ].sort();\n\n const report: ReviewReport = {\n version: 1,\n root: resolvedRoot,\n base,\n mergeBase,\n changedFiles,\n missingPartners: [],\n touchedDecisions: [],\n historyAvailable: true,\n truncated: false,\n };\n if (changedFiles.length === 0) return report;\n\n let analyzed = changedFiles;\n if (changedFiles.length > MAX_ANALYZED_FILES) {\n analyzed = changedFiles.slice(0, MAX_ANALYZED_FILES);\n report.truncated = true;\n }\n\n const partners = await findMissingPartners(\n resolvedRoot,\n analyzed,\n async (relPath) => {\n try {\n await fs.access(path.join(resolvedRoot, relPath));\n return true;\n } catch {\n return false;\n }\n }\n );\n if (partners === null) {\n report.historyAvailable = false;\n } else {\n report.missingPartners = partners;\n }\n\n const decisions = await loadDecisions(resolvedRoot);\n for (const record of decisions) {\n if (record.status !== \"active\" || record.files.length === 0) continue;\n const touched = anchorsTouched(record, changedFiles);\n if (touched.length > 0) {\n report.touchedDecisions.push({\n id: record.id,\n title: record.title,\n body: record.body,\n category: record.category,\n anchors: record.files,\n touchedFiles: touched,\n });\n }\n }\n\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport {\n loadSnapshot,\n getCurrentGitHash,\n listSourceFiles,\n} from \"../snapshot/snapshot.js\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\n\nconst exec = promisify(execFile);\n\n// Incremental refresh stops paying off once a large share of the map is\n// touched — but small absolute counts are always cheap to refresh in place,\n// so both thresholds must be exceeded before recommending a full rebuild.\nconst FULL_REBUILD_FRACTION = 0.4;\nconst FULL_REBUILD_MIN_CHANGED_MAPPED_FILES = 10;\n\nexport type ChangeStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\nexport interface FileChange {\n status: ChangeStatus;\n /** Current path (the new path for renames). */\n path: string;\n /** Pre-rename path, only present for renames. */\n previousPath?: string;\n}\n\nexport type DriftRecommendation = \"up-to-date\" | \"incremental\" | \"full-rebuild\";\n\nexport interface DriftReport {\n stale: boolean;\n snapshotHash: string;\n headHash: string;\n /** Commits between the snapshot and HEAD; null when history is unavailable. */\n commitsBehind: number | null;\n /**\n * False when the snapshot commit is unreachable (shallow clone, rewritten\n * history) — staleFeatures/unmappedFiles/renames cannot be computed then.\n */\n historyAvailable: boolean;\n /** Current paths of every file changed since the snapshot. */\n changedFiles: string[];\n /** Stale feature name → the mapped files that changed under it. */\n staleFeatures: Record<string, string[]>;\n /** Stale flow name → the chain files that changed under it. */\n staleFlows: Record<string, string[]>;\n totalFeatures: number;\n totalFlows: number;\n /** New source files not referenced by any feature or flow. */\n unmappedFiles: string[];\n /** Files referenced by the map that no longer exist on disk. */\n ghostFiles: string[];\n renames: Array<{ from: string; to: string }>;\n recommendation: DriftRecommendation;\n}\n\nexport async function getChangesWithStatus(\n resolvedRoot: string,\n fromHash: string\n): Promise<FileChange[] | null> {\n if (!fromHash || fromHash === \"unknown\") return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\"diff\", \"--name-status\", \"-M\", fromHash, \"HEAD\"],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n\n const changes: FileChange[] = [];\n for (const line of stdout.split(\"\\n\")) {\n if (!line.trim()) continue;\n const parts = line.split(\"\\t\");\n // Mason's own metadata changes on every save — never count it as drift.\n if (parts.some((p) => p.startsWith(\".mason/\"))) continue;\n const code = parts[0];\n if (code.startsWith(\"R\") && parts.length >= 3) {\n changes.push({\n status: \"renamed\",\n path: parts[2],\n previousPath: parts[1],\n });\n } else if (code.startsWith(\"C\") && parts.length >= 3) {\n // A copy leaves the original in place — only the new path is a change.\n changes.push({ status: \"added\", path: parts[2] });\n } else if (code === \"A\" && parts.length >= 2) {\n changes.push({ status: \"added\", path: parts[1] });\n } else if (code === \"D\" && parts.length >= 2) {\n changes.push({ status: \"deleted\", path: parts[1] });\n } else if (parts.length >= 2) {\n // M, T (typechange), and anything unrecognized count as modified.\n changes.push({ status: \"modified\", path: parts[1] });\n }\n }\n return changes;\n } catch {\n return null;\n }\n}\n\nasync function countCommitsBehind(\n resolvedRoot: string,\n fromHash: string\n): Promise<number | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"rev-list\", \"--count\", `${fromHash}..HEAD`],\n { cwd: resolvedRoot }\n );\n const count = Number.parseInt(stdout.trim(), 10);\n return Number.isNaN(count) ? null : count;\n } catch {\n return null;\n }\n}\n\nfunction collectMappedFiles(snapshot: Snapshot): Set<string> {\n const mappedFiles = new Set<string>();\n for (const feature of Object.values(snapshot.features)) {\n for (const f of feature.files) mappedFiles.add(f);\n for (const t of feature.tests ?? []) mappedFiles.add(t);\n }\n for (const flow of Object.values(snapshot.flows)) {\n for (const f of flow.chain) mappedFiles.add(f);\n }\n return mappedFiles;\n}\n\nasync function findGhostFiles(\n resolvedRoot: string,\n mappedFiles: Set<string>\n): Promise<string[]> {\n const ghosts: string[] = [];\n for (const file of mappedFiles) {\n try {\n await fs.access(path.join(resolvedRoot, file));\n } catch {\n ghosts.push(file);\n }\n }\n return ghosts.sort();\n}\n\n/**\n * Compare the concept map against HEAD and report feature-level drift.\n * Fully deterministic — git + filesystem only, no LLM involved.\n * Returns null when no snapshot exists.\n */\nexport async function computeDrift(\n rootDir: string\n): Promise<DriftReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const snapshot = await loadSnapshot(resolvedRoot);\n if (!snapshot) return null;\n\n const headHash = await getCurrentGitHash(resolvedRoot);\n const totalFeatures = Object.keys(snapshot.features).length;\n const totalFlows = Object.keys(snapshot.flows).length;\n\n // Each entry is only verified as of its refreshedHash (falling back to the\n // top-level gitHash), so drift is evaluated per distinct hash — a partially\n // refreshed map can be fresh at the top level and still hold stale entries.\n const hashFor = (entry: { refreshedHash?: string }): string =>\n entry.refreshedHash ?? snapshot.gitHash;\n\n const distinctHashes = new Set<string>([snapshot.gitHash]);\n for (const feature of Object.values(snapshot.features)) {\n distinctHashes.add(hashFor(feature));\n }\n for (const flow of Object.values(snapshot.flows)) {\n distinctHashes.add(hashFor(flow));\n }\n distinctHashes.delete(\"unknown\");\n\n const staleHashes =\n headHash === \"unknown\"\n ? []\n : [...distinctHashes].filter((h) => h !== headHash);\n const stale = staleHashes.length > 0;\n\n const report: DriftReport = {\n stale,\n snapshotHash: snapshot.gitHash,\n headHash,\n commitsBehind: stale ? null : 0,\n historyAvailable: true,\n changedFiles: [],\n staleFeatures: {},\n staleFlows: {},\n totalFeatures,\n totalFlows,\n unmappedFiles: [],\n ghostFiles: [],\n renames: [],\n recommendation: \"up-to-date\",\n };\n\n if (!stale) return report;\n\n const mappedFiles = collectMappedFiles(snapshot);\n report.ghostFiles = await findGhostFiles(resolvedRoot, mappedFiles);\n\n const changesByHash = new Map<string, FileChange[]>();\n const touchedByHash = new Map<string, Set<string>>();\n for (const hash of staleHashes) {\n const changes = await getChangesWithStatus(resolvedRoot, hash);\n if (changes === null) {\n // One unreachable base commit is enough to make per-entry drift\n // uncomputable — we know the map is stale but not how.\n report.historyAvailable = false;\n report.recommendation = \"full-rebuild\";\n return report;\n }\n changesByHash.set(hash, changes);\n // Every path a change touches, old and new — an entry referencing either\n // side of a rename is stale.\n const touched = new Set<string>();\n for (const change of changes) {\n touched.add(change.path);\n if (change.previousPath) touched.add(change.previousPath);\n }\n touchedByHash.set(hash, touched);\n }\n\n // The oldest verification state in the map is the honest answer to \"how\n // far behind is this snapshot\".\n const commitCounts = await Promise.all(\n staleHashes.map((hash) => countCommitsBehind(resolvedRoot, hash))\n );\n const validCounts = commitCounts.filter((c): c is number => c !== null);\n report.commitsBehind =\n validCounts.length > 0 ? Math.max(...validCounts) : null;\n\n const emptySet = new Set<string>();\n const touchedFor = (entry: { refreshedHash?: string }): Set<string> =>\n touchedByHash.get(hashFor(entry)) ?? emptySet;\n\n for (const [name, feature] of Object.entries(snapshot.features)) {\n const touched = touchedFor(feature);\n const hits = [...feature.files, ...(feature.tests ?? [])].filter((f) =>\n touched.has(f)\n );\n if (hits.length > 0) report.staleFeatures[name] = [...new Set(hits)];\n }\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n const touched = touchedFor(flow);\n const hits = flow.chain.filter((f) => touched.has(f));\n if (hits.length > 0) report.staleFlows[name] = [...new Set(hits)];\n }\n\n const allChanges = [...changesByHash.values()].flat();\n report.changedFiles = [...new Set(allChanges.map((c) => c.path))].sort();\n\n // New source files (added, or the new side of a rename) missing from the map.\n const sourceFileSet = new Set(await listSourceFiles(resolvedRoot));\n const newPaths = allChanges\n .filter((c) => c.status === \"added\" || c.status === \"renamed\")\n .map((c) => c.path);\n report.unmappedFiles = [...new Set(newPaths)]\n .filter((p) => sourceFileSet.has(p) && !mappedFiles.has(p))\n .sort();\n\n const renameKeys = new Set<string>();\n for (const change of allChanges) {\n if (change.status !== \"renamed\" || !change.previousPath) continue;\n const key = `${change.previousPath}\u0000${change.path}`;\n if (renameKeys.has(key)) continue;\n renameKeys.add(key);\n report.renames.push({ from: change.previousPath, to: change.path });\n }\n\n const changedMapped = new Set<string>([\n ...Object.values(report.staleFeatures).flat(),\n ...Object.values(report.staleFlows).flat(),\n ]);\n const changedFraction =\n mappedFiles.size > 0 ? changedMapped.size / mappedFiles.size : 0;\n report.recommendation =\n changedMapped.size >= FULL_REBUILD_MIN_CHANGED_MAPPED_FILES &&\n changedFraction > FULL_REBUILD_FRACTION\n ? \"full-rebuild\"\n : \"incremental\";\n\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { readFullFile } from \"../mcp/sampler.js\";\nimport { buildTestMap } from \"../test-map.js\";\n\nconst exec = promisify(execFile);\n\nexport interface FeatureEntry {\n description: string;\n files: string[];\n tests?: string[];\n /**\n * Commit this entry was last verified against. Entries updated by an\n * incremental save carry HEAD here; untouched entries keep the hash the\n * map had before the save, so drift stays visible per entry. Absent means\n * \"as of the snapshot's top-level gitHash\".\n */\n refreshedHash?: string;\n /**\n * Whether this is a user-facing capability or internal infrastructure\n * (DI wiring, config loading, logging, provider/transport plumbing).\n * Capabilities are published to product-facing docs (Confluence);\n * infrastructure stays in the AI concept map only. Defaults to \"capability\"\n * when absent (older snapshots) or unrecognized — see normalizeFeatureType.\n */\n type?: \"capability\" | \"infrastructure\";\n /**\n * When an assistant last confirmed this entry's files actually implement\n * the claimed feature (verify_snapshot flow). Absent on older snapshots\n * and never-verified entries. Drift checks freshness against git; this\n * checks the map was CORRECT in the first place.\n */\n verifiedAt?: string;\n /** Set when verification judged the entry wrong — re-map it. */\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport type FeatureType = \"capability\" | \"infrastructure\";\n\n/**\n * Coerce an arbitrary type value to a known classification. Anything that\n * isn't explicitly \"infrastructure\" defaults to \"capability\" — so older\n * snapshots and unclassified entries are treated as user-facing (published),\n * never silently hidden.\n */\nexport function normalizeFeatureType(value: unknown): FeatureType {\n return value === \"infrastructure\" ? \"infrastructure\" : \"capability\";\n}\n\nexport interface FlowEntry {\n description: string;\n chain: string[];\n /** See FeatureEntry.refreshedHash. */\n refreshedHash?: string;\n /** See FeatureEntry.verifiedAt / verificationFailed. */\n verifiedAt?: string;\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport interface Snapshot {\n version: 2;\n createdAt: string;\n updatedAt: string;\n gitHash: string;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nfunction snapshotDir(rootDir: string): string {\n return path.join(rootDir, \".mason\");\n}\n\nfunction snapshotPath(rootDir: string): string {\n return path.join(snapshotDir(rootDir), \"snapshot.json\");\n}\n\nexport async function loadSnapshot(rootDir: string): Promise<Snapshot | null> {\n try {\n const raw = await fs.readFile(snapshotPath(rootDir), \"utf-8\");\n const parsed = JSON.parse(raw);\n // Skip v1 snapshots — they're the old per-file format\n if (parsed.version !== 2) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nexport async function saveSnapshot(\n rootDir: string,\n snapshot: Snapshot\n): Promise<void> {\n await fs.mkdir(snapshotDir(rootDir), { recursive: true });\n await fs.writeFile(\n snapshotPath(rootDir),\n JSON.stringify(snapshot, null, 2),\n \"utf-8\"\n );\n}\n\nexport async function getCurrentGitHash(rootDir: string): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"rev-parse\", \"HEAD\"], {\n cwd: rootDir,\n });\n return stdout.trim();\n } catch {\n return \"unknown\";\n }\n}\n\nexport const SOURCE_GLOB =\n \"**/*.{ts,tsx,js,jsx,kt,kts,java,py,go,rs,swift,rb,cs,cpp,c,dart}\";\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\",\n \"**/generated/**\", \"**/R.java\", \"**/BuildConfig.java\",\n];\n\nexport const DEFAULT_BATCH_SIZE = 50;\nconst SKELETON_CHARS = 500;\nconst DEEP_SAMPLE_CHARS = 1500;\nconst DEEP_SAMPLES_PER_BATCH = 3;\n\nexport interface SnapshotBatch {\n offset: number;\n batchSize: number;\n nextOffset: number | null;\n totalFiles: number;\n skeletons: Array<{ path: string; content: string }>;\n samples: Array<{ path: string; content: string }>;\n testPairs: Array<{ test: string; source: string; confidence: string }>;\n}\n\nexport async function listSourceFiles(resolvedRoot: string): Promise<string[]> {\n const all = await fg(SOURCE_GLOB, {\n cwd: resolvedRoot,\n ignore: SOURCE_IGNORE,\n });\n // Deterministic order so the same offset always returns the same batch.\n return [...all].sort();\n}\n\nexport async function prepareSnapshotBatch(\n rootDir: string,\n offset: number,\n batchSize: number = DEFAULT_BATCH_SIZE,\n scopeFiles?: string[]\n): Promise<SnapshotBatch> {\n const resolvedRoot = path.resolve(rootDir);\n let allFiles = await listSourceFiles(resolvedRoot);\n if (scopeFiles) {\n // Intersect with the real source list: keeps ignore rules and path safety,\n // and silently drops scope entries that no longer exist on disk. An empty\n // scope stays empty — it must not fall back to walking the whole project.\n const scopeSet = new Set(scopeFiles);\n allFiles = allFiles.filter((f) => scopeSet.has(f));\n }\n const totalFiles = allFiles.length;\n const safeOffset = Math.max(0, Math.min(offset, totalFiles));\n const batchPaths = allFiles.slice(safeOffset, safeOffset + batchSize);\n\n const skeletons: Array<{ path: string; content: string }> = [];\n for (const filePath of batchPaths) {\n const full = await readFullFile(resolvedRoot, filePath);\n if (full) {\n skeletons.push({\n path: full.path,\n content: full.content.slice(0, SKELETON_CHARS),\n });\n }\n }\n\n // Pick a few files from this batch to read deeply for grounding. Spread\n // evenly across the batch so the deep samples represent the batch's range.\n const samples: Array<{ path: string; content: string }> = [];\n if (skeletons.length > 0) {\n const step = Math.max(1, Math.floor(skeletons.length / DEEP_SAMPLES_PER_BATCH));\n for (let i = 0; i < skeletons.length && samples.length < DEEP_SAMPLES_PER_BATCH; i += step) {\n const full = await readFullFile(resolvedRoot, skeletons[i].path);\n if (full) {\n samples.push({\n path: full.path,\n content: full.content.slice(0, DEEP_SAMPLE_CHARS),\n });\n }\n }\n }\n\n // Only include test pairs that involve files in this batch — keeps the\n // appendix relevant and small.\n const batchPathSet = new Set(batchPaths);\n const allTestPairs = (await buildTestMap(resolvedRoot)).paired;\n const testPairs = allTestPairs.filter(\n (p) => batchPathSet.has(p.test) || batchPathSet.has(p.source)\n );\n\n const nextOffset =\n safeOffset + batchSize >= totalFiles ? null : safeOffset + batchSize;\n\n return {\n offset: safeOffset,\n batchSize,\n nextOffset,\n totalFiles,\n skeletons,\n samples,\n testPairs,\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\n\nconst exec = promisify(execFile);\n\nconst SOURCE_EXTENSIONS = [\n \"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"mjs\",\n \"kt\", \"kts\", \"java\",\n \"py\",\n \"go\",\n \"rs\",\n \"swift\",\n \"rb\",\n \"cs\", \"cpp\", \"c\", \"h\",\n \"dart\",\n];\n\nconst CONFIG_FILES = [\n // Build & project config\n \"package.json\",\n \"tsconfig.json\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"Gemfile\",\n \"*.csproj\",\n // Version catalogs & dependency locks\n \"gradle/libs.versions.toml\",\n // Code quality & formatting\n \".editorconfig\",\n \".eslintrc.*\",\n \"eslint.config.*\",\n \".prettierrc\",\n \"rustfmt.toml\",\n \".swiftlint.yml\",\n // CI/CD\n \".github/workflows/*.yml\",\n \".gitlab-ci.yml\",\n \"Jenkinsfile\",\n // Containerization\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n];\n\nconst ENTRY_POINT_PATTERNS = [\n \"src/main.*\",\n \"src/index.*\",\n \"src/app.*\",\n \"main.*\",\n \"index.*\",\n \"app.*\",\n \"App.*\",\n \"**/Main.kt\",\n \"**/Application.kt\",\n \"**/main.py\",\n \"**/main.go\",\n \"**/main.rs\",\n \"**/lib.rs\",\n \"**/Program.cs\",\n];\n\n// Filename patterns that reveal architectural patterns and conventions.\n// These are language-agnostic — the suffixes appear across ecosystems.\n// Ordered by architectural importance — most distinctive patterns first.\nconst ARCHITECTURAL_PATTERNS = [\n // State/data flow\n { glob: \"**/*ViewModel.*\", category: \"state\", reason: \"viewmodel (state management)\" },\n { glob: \"**/*Store.*\", category: \"state\", reason: \"store (state management)\" },\n { glob: \"**/*Reducer.*\", category: \"state\", reason: \"reducer (state management)\" },\n // Data layer — interface\n { glob: \"**/*Repository.*\", category: \"data-interface\", reason: \"repository interface (data layer contract)\" },\n { glob: \"**/*Dao.*\", category: \"data-interface\", reason: \"DAO (data access)\" },\n { glob: \"**/*DataSource.*\", category: \"data-interface\", reason: \"data source\" },\n // Data layer — implementation (where actual patterns live: mappers, retry, IO dispatchers)\n { glob: \"**/*RepositoryImpl.*\", category: \"data-impl\", reason: \"repository implementation (data layer patterns)\" },\n { glob: \"**/*ServiceImpl.*\", category: \"data-impl\", reason: \"service implementation\" },\n { glob: \"**/*Impl.*\", category: \"data-impl\", reason: \"implementation (concrete patterns)\" },\n // Data transformation\n { glob: \"**/*Mapper.*\", category: \"transform\", reason: \"mapper (data transformation)\" },\n { glob: \"**/*Converter.*\", category: \"transform\", reason: \"converter (data transformation)\" },\n { glob: \"**/*Adapter.*\", category: \"transform\", reason: \"adapter (interface adaptation)\" },\n // Dependency injection / wiring\n { glob: \"**/*Module.*\", category: \"di\", reason: \"module (DI/wiring)\" },\n { glob: \"**/*Provider.*\", category: \"di\", reason: \"provider (DI/wiring)\" },\n { glob: \"**/*Container.*\", category: \"di\", reason: \"container (DI/wiring)\" },\n { glob: \"**/*Factory.*\", category: \"di\", reason: \"factory (object creation)\" },\n // API / network\n { glob: \"**/*Service.*\", category: \"api\", reason: \"service (business/API layer)\" },\n { glob: \"**/*Client.*\", category: \"api\", reason: \"client (API/network layer)\" },\n { glob: \"**/*Api.*\", category: \"api\", reason: \"API interface definition\" },\n // Interface contracts / protocols\n { glob: \"**/*Interface.*\", category: \"contract\", reason: \"interface definition\" },\n { glob: \"**/*Protocol.*\", category: \"contract\", reason: \"protocol definition\" },\n { glob: \"**/*Trait.*\", category: \"contract\", reason: \"trait definition\" },\n // Routing / navigation\n { glob: \"**/*Router.*\", category: \"routing\", reason: \"router (navigation/routing)\" },\n { glob: \"**/*Route.*\", category: \"routing\", reason: \"route definition\" },\n { glob: \"**/*NavHost.*\", category: \"routing\", reason: \"navigation host\" },\n { glob: \"**/*Controller.*\", category: \"routing\", reason: \"controller (request handling)\" },\n { glob: \"**/*Handler.*\", category: \"routing\", reason: \"handler (request handling)\" },\n // Middleware / interceptors\n { glob: \"**/*Middleware.*\", category: \"middleware\", reason: \"middleware (request pipeline)\" },\n { glob: \"**/*Interceptor.*\", category: \"middleware\", reason: \"interceptor (cross-cutting)\" },\n { glob: \"**/*Plugin.*\", category: \"middleware\", reason: \"plugin (extensibility)\" },\n // Models / types\n { glob: \"**/*Model.*\", category: \"model\", reason: \"model (domain types)\" },\n { glob: \"**/*Entity.*\", category: \"model\", reason: \"entity (persistence types)\" },\n { glob: \"**/*Dto.*\", category: \"model\", reason: \"DTO (data transfer types)\" },\n { glob: \"**/*Schema.*\", category: \"model\", reason: \"schema (data validation)\" },\n // Use cases / commands\n { glob: \"**/*UseCase.*\", category: \"usecase\", reason: \"use case (business logic)\" },\n { glob: \"**/*Interactor.*\", category: \"usecase\", reason: \"interactor (business logic)\" },\n { glob: \"**/*Command.*\", category: \"usecase\", reason: \"command (CQRS pattern)\" },\n];\n\nconst IGNORE_PATTERNS = [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.gradle/**\",\n \"**/target/**\",\n \"**/.git/**\",\n \"**/vendor/**\",\n \"**/__pycache__/**\",\n \"**/venv/**\",\n \"**/.venv/**\",\n \"**/*.min.*\",\n \"**/*.map\",\n \"**/package-lock.json\",\n \"**/yarn.lock\",\n \"**/pnpm-lock.yaml\",\n \"**/*.lock\",\n \"**/*.generated.*\",\n \"**/generated/**\",\n \"**/R.java\",\n \"**/BuildConfig.java\",\n];\n\nconst PREVIEW_LINES = 60;\n\nexport interface ProjectConfig {\n patterns?: string[];\n alwaysInclude?: string[];\n ignore?: string[];\n}\n\nexport interface SampledFile {\n path: string;\n preview: string;\n totalLines: number;\n sizeBytes: number;\n reason: string;\n}\n\nasync function loadProjectConfig(\n rootDir: string\n): Promise<ProjectConfig> {\n try {\n const raw = await fs.readFile(\n path.join(rootDir, \".mason\", \"config.json\"),\n \"utf-8\"\n );\n return JSON.parse(raw);\n } catch {\n return {};\n }\n}\n\nasync function getTrackedFiles(rootDir: string): Promise<Set<string> | null> {\n try {\n const { stdout } = await exec(\"git\", [\"ls-files\", \"--cached\", \"--others\", \"--exclude-standard\"], {\n cwd: rootDir,\n maxBuffer: 10_000_000,\n });\n return new Set(stdout.trim().split(\"\\n\").filter(Boolean));\n } catch {\n return null; // Not a git repo — skip filtering\n }\n}\n\nexport async function sampleFiles(\n rootDir: string,\n maxFiles: number = 25\n): Promise<SampledFile[]> {\n const selected = new Map<string, string>(); // path -> reason\n const projectConfig = await loadProjectConfig(rootDir);\n const ignorePatterns = [...IGNORE_PATTERNS, ...(projectConfig.ignore ?? [])];\n const trackedFiles = await getTrackedFiles(rootDir);\n\n // 0. Always-include files from project config (highest priority)\n for (const filePath of projectConfig.alwaysInclude ?? []) {\n if (selected.size >= maxFiles) break;\n // Validate path stays within project root\n const resolvedPath = path.resolve(rootDir, filePath);\n if (!resolvedPath.startsWith(path.resolve(rootDir))) continue;\n selected.set(filePath, \"always-include (project config)\");\n }\n\n // 1. Config files (cap at 5)\n let configCount = 0;\n for (const pattern of CONFIG_FILES) {\n if (configCount >= 5) break;\n const matches = await fg(pattern, {\n cwd: rootDir,\n ignore: ignorePatterns,\n deep: 3,\n });\n for (const match of matches) {\n if (configCount >= 5 || selected.size >= maxFiles) break;\n selected.set(match, \"config file\");\n configCount++;\n }\n }\n\n // 2. Module build/config files — build files from subdirectories reveal dependency graph\n const moduleBuildPatterns = [\n // Gradle\n \"**/build.gradle.kts\",\n \"**/build.gradle\",\n // Cargo workspace members\n \"**/Cargo.toml\",\n // Node workspaces\n \"**/package.json\",\n // Go sub-modules\n \"**/go.mod\",\n ];\n let moduleBuildCount = 0;\n for (const pattern of moduleBuildPatterns) {\n const matches = await fg(pattern, {\n cwd: rootDir,\n ignore: ignorePatterns,\n deep: 4,\n });\n // Skip root-level files (already captured as config)\n const subMatches = matches.filter((m) => m.includes(\"/\"));\n for (const match of subMatches) {\n if (moduleBuildCount >= 4 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"module build file (reveals dependency graph)\");\n moduleBuildCount++;\n }\n }\n if (moduleBuildCount >= 4) break;\n }\n\n // 3. Entry points (cap at 2)\n let entryCount = 0;\n for (const pattern of ENTRY_POINT_PATTERNS) {\n if (entryCount >= 2) break;\n const matches = await fg(pattern, {\n cwd: rootDir,\n ignore: ignorePatterns,\n deep: 5,\n });\n for (const match of matches) {\n if (entryCount >= 2 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"entry point\");\n entryCount++;\n }\n }\n }\n\n // 4. Hot files from git (up to 5)\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const fileCounts = new Map<string, number>();\n for (const line of stdout.split(\"\\n\")) {\n if (!line) continue;\n if (\n line.includes(\"node_modules\") ||\n line.includes(\"/build/\") ||\n line.includes(\".gradle\") ||\n line.includes(\"/generated/\")\n )\n continue;\n const ext = path.extname(line).slice(1);\n if (!SOURCE_EXTENSIONS.includes(ext)) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const hotFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n for (const [file, count] of hotFiles) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, `frequently changed (${count} commits in 3 months)`);\n }\n }\n } catch {\n // No git\n }\n\n // 5. Architectural pattern files — one per category (cap at 8)\n const seenCategories = new Set<string>();\n let patternCount = 0;\n for (const pattern of ARCHITECTURAL_PATTERNS) {\n if (patternCount >= 8 || selected.size >= maxFiles) break;\n if (seenCategories.has(pattern.category)) continue;\n\n const matches = await fg(pattern.glob, {\n cwd: rootDir,\n ignore: ignorePatterns,\n });\n\n if (matches.length > 0) {\n for (const match of matches) {\n if (!selected.has(match)) {\n selected.set(match, pattern.reason);\n seenCategories.add(pattern.category);\n patternCount++;\n break;\n }\n }\n }\n }\n\n // 5b. Custom patterns from project config\n for (const customGlob of projectConfig.patterns ?? []) {\n if (selected.size >= maxFiles) break;\n const matches = await fg(customGlob, {\n cwd: rootDir,\n ignore: ignorePatterns,\n });\n for (const match of matches) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"custom pattern (project config)\");\n break; // one per pattern\n }\n }\n }\n\n // 6. Test examples — diverse across file types (cap at 3)\n const testPatternGroups = [\n // JS/TS tests\n { patterns: [\"**/*.test.*\", \"**/*.spec.*\"], label: \"JS/TS test\" },\n // JVM tests\n { patterns: [\"**/*Test.kt\", \"**/*Test.java\"], label: \"JVM test\" },\n // Python tests\n { patterns: [\"**/test_*.py\", \"**/*_test.py\"], label: \"Python test\" },\n // Go tests\n { patterns: [\"**/*_test.go\"], label: \"Go test\" },\n // Swift tests\n { patterns: [\"**/*Tests.swift\", \"**/*Test.swift\"], label: \"Swift test\" },\n // Rust tests\n { patterns: [\"**/*_test.rs\"], label: \"Rust test\" },\n ];\n let testCount = 0;\n for (const group of testPatternGroups) {\n if (testCount >= 3 || selected.size >= maxFiles) break;\n const testFiles = await fg(group.patterns, {\n cwd: rootDir,\n ignore: ignorePatterns,\n });\n if (testFiles.length > 0) {\n for (const file of testFiles) {\n if (!selected.has(file)) {\n selected.set(file, `test example (${group.label})`);\n testCount++;\n break;\n }\n }\n }\n }\n\n // 7. Directory breadth — fill remaining slots with one file per top-level dir\n const sourceGlobs = SOURCE_EXTENSIONS.map((ext) => `**/*.${ext}`);\n const allSourceFiles = await fg(sourceGlobs, {\n cwd: rootDir,\n ignore: ignorePatterns,\n });\n\n const dirRepresentatives = new Map<string, string>();\n const boringFiles = /\\.(gradle|gradle\\.kts|json|toml|yaml|yml|xml|properties)$/;\n for (const file of allSourceFiles) {\n const topDir = file.split(\"/\")[0];\n if (!dirRepresentatives.has(topDir) && !boringFiles.test(file)) {\n dirRepresentatives.set(topDir, file);\n }\n }\n\n for (const [, file] of dirRepresentatives) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, \"directory representative\");\n }\n }\n\n // Read file previews\n const results: SampledFile[] = [];\n for (const [filePath, reason] of selected) {\n try {\n const fullPath = path.resolve(rootDir, filePath);\n if (!fullPath.startsWith(path.resolve(rootDir))) continue;\n if (isSensitiveFile(filePath)) continue;\n if (trackedFiles && !trackedFiles.has(filePath)) continue; // respect .gitignore\n const stat = await fs.stat(fullPath);\n if (stat.size > 100_000) continue;\n\n const content = await fs.readFile(fullPath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const preview = lines.slice(0, PREVIEW_LINES).join(\"\\n\");\n\n results.push({\n path: filePath,\n preview,\n totalLines: lines.length,\n sizeBytes: stat.size,\n reason,\n });\n } catch {\n // Skip\n }\n }\n\n return results;\n}\n\nconst SENSITIVE_PATTERNS = [\n /^\\.env$/,\n /^\\.env\\./,\n /\\.pem$/,\n /\\.key$/,\n /\\.p12$/,\n /\\.pfx$/,\n /\\.jks$/,\n /id_rsa/,\n /id_ed25519/,\n /credentials\\./,\n /secret/i,\n /\\.keystore$/,\n /local\\.properties$/,\n];\n\nfunction isSensitiveFile(filePath: string): boolean {\n const basename = path.basename(filePath);\n return SENSITIVE_PATTERNS.some((p) => p.test(basename));\n}\n\nexport async function readFullFile(\n rootDir: string,\n filePath: string\n): Promise<{ path: string; content: string; totalLines: number } | null> {\n try {\n const fullPath = path.join(path.resolve(rootDir), filePath);\n if (!fullPath.startsWith(path.resolve(rootDir))) return null;\n if (isSensitiveFile(filePath)) return null;\n\n const content = await fs.readFile(fullPath, \"utf-8\");\n return {\n path: filePath,\n content,\n totalLines: content.split(\"\\n\").length,\n };\n } catch {\n return null;\n }\n}\n","import path from \"node:path\";\nimport fg from \"fast-glob\";\n\nconst IGNORE = [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.gradle/**\",\n \"**/target/**\",\n \"**/.git/**\",\n \"**/vendor/**\",\n \"**/__pycache__/**\",\n \"**/venv/**\",\n \"**/.venv/**\",\n \"**/*.min.*\",\n \"**/*.map\",\n];\n\nexport interface TestPair {\n test: string;\n source: string;\n confidence: string;\n}\n\nexport interface TestMapResult {\n totalTestFiles: number;\n paired: TestPair[];\n unmatched: string[];\n}\n\nexport async function buildTestMap(dir: string): Promise<TestMapResult> {\n const rootDir = path.resolve(dir);\n\n // Find all test files\n const testPatterns = [\n \"**/*.test.*\", \"**/*.spec.*\",\n \"**/*Test.kt\", \"**/*Test.java\", \"**/*Tests.kt\", \"**/*Tests.java\",\n \"**/test_*.py\", \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\", \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n const testFiles = await fg(testPatterns, { cwd: rootDir, ignore: IGNORE });\n\n // Find all source files\n const sourceFiles = await fg(\n \"**/*.{ts,tsx,js,jsx,kt,kts,java,py,go,rs,swift,rb,cs,cpp,dart}\",\n { cwd: rootDir, ignore: IGNORE }\n );\n\n // Build source file index by base name (without extension)\n const sourceByBaseName = new Map<string, string[]>();\n for (const file of sourceFiles) {\n if (testFiles.includes(file)) continue; // Skip test files\n const baseName = path.basename(file).replace(/\\.[^.]+$/, \"\");\n const existing = sourceByBaseName.get(baseName) ?? [];\n existing.push(file);\n sourceByBaseName.set(baseName, existing);\n }\n\n // Match test files to source files by name\n const paired: TestPair[] = [];\n const unmatched: string[] = [];\n\n for (const testFile of testFiles) {\n const testBaseName = path.basename(testFile).replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes/prefixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (!sourceName) {\n unmatched.push(testFile);\n continue;\n }\n\n const candidates = sourceByBaseName.get(sourceName);\n if (candidates && candidates.length > 0) {\n // If multiple candidates, prefer one in a similar directory path\n const testDir = path.dirname(testFile);\n const bestMatch = candidates.reduce((best, candidate) => {\n const candidateDir = path.dirname(candidate);\n const bestDir = path.dirname(best);\n const candidateOverlap = commonSegments(testDir, candidateDir);\n const bestOverlap = commonSegments(testDir, bestDir);\n return candidateOverlap > bestOverlap ? candidate : best;\n });\n\n paired.push({\n test: testFile,\n source: bestMatch,\n confidence: candidates.length === 1 ? \"exact\" : \"best-guess\",\n });\n } else {\n unmatched.push(testFile);\n }\n }\n\n return { totalTestFiles: testFiles.length, paired, unmatched };\n}\n\nfunction commonSegments(pathA: string, pathB: string): number {\n const segsA = pathA.split(\"/\");\n const segsB = pathB.split(\"/\");\n let count = 0;\n for (let i = 0; i < Math.min(segsA.length, segsB.length); i++) {\n if (segsA[i] === segsB[i]) count++;\n else break;\n }\n return count;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { jaccard, tokenSet } from \"../context/lexical.js\";\n\nexport type DecisionCategory =\n | \"decision\"\n | \"gotcha\"\n | \"deprecation\"\n | \"convention\";\nexport type DecisionStatus = \"active\" | \"superseded\";\n\n/**\n * One unit of team knowledge the code alone can't express: a failed\n * approach, a deprecation, a workaround's reason, a review-settled\n * convention. Stored one file per record under .mason/decisions/ so\n * concurrent additions on different branches merge without conflict,\n * while concurrent edits to the SAME record conflict — contested\n * knowledge should reach a human.\n */\nexport interface DecisionRecord {\n version: 1;\n id: string;\n title: string;\n body: string;\n category: DecisionCategory;\n /** Repo-relative anchor files. Empty means pure prose — never goes stale. */\n files: string[];\n createdAt: string;\n updatedAt: string;\n /** Commit this record was last verified against. */\n refreshedHash: string;\n status: DecisionStatus;\n supersededBy?: string;\n}\n\nexport const TITLE_MAX_CHARS = 80;\nexport const BODY_MAX_CHARS = 1500;\nexport const MAX_ACTIVE_DECISIONS = 150;\n\nconst DUPLICATE_JACCARD = 0.5;\nconst DUPLICATE_JACCARD_WITH_SHARED_FILE = 0.35;\n\nfunction decisionsDir(rootDir: string): string {\n return path.join(rootDir, \".mason\", \"decisions\");\n}\n\nexport async function loadDecisions(\n rootDir: string\n): Promise<DecisionRecord[]> {\n let entries: string[];\n try {\n entries = await fs.readdir(decisionsDir(rootDir));\n } catch {\n return [];\n }\n const records: DecisionRecord[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\")) continue;\n try {\n const raw = await fs.readFile(\n path.join(decisionsDir(rootDir), entry),\n \"utf-8\"\n );\n const parsed = JSON.parse(raw);\n // Skip unknown versions and malformed records individually — one bad\n // merge artifact must not take down the store.\n if (parsed.version !== 1 || !parsed.id || !parsed.title || !parsed.body) {\n continue;\n }\n records.push(parsed);\n } catch {\n continue;\n }\n }\n return records.sort((a, b) => a.id.localeCompare(b.id));\n}\n\nexport async function saveDecisionRecord(\n rootDir: string,\n record: DecisionRecord\n): Promise<void> {\n await fs.mkdir(decisionsDir(rootDir), { recursive: true });\n await fs.writeFile(\n path.join(decisionsDir(rootDir), `${record.id}.json`),\n JSON.stringify(record, null, 2) + \"\\n\",\n \"utf-8\"\n );\n}\n\n/**\n * Deterministic, human-readable id: kebab slug of the title, ≤60 chars.\n * A slug collision with a DIFFERENT record appends a 6-hex content suffix.\n */\nexport function decisionIdFor(\n title: string,\n body: string,\n existingIds: Set<string>\n): string {\n const slug = title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60)\n .replace(/-+$/, \"\");\n if (!existingIds.has(slug)) return slug || \"decision\";\n const suffix = createHash(\"sha1\")\n .update(title + body)\n .digest(\"hex\")\n .slice(0, 6);\n return `${slug}-${suffix}`;\n}\n\nexport function findNearDuplicate(\n candidate: { title: string; body: string; files: string[] },\n existing: DecisionRecord[]\n): { record: DecisionRecord; similarity: number } | null {\n const candidateTokens = tokenSet(`${candidate.title} ${candidate.body}`);\n const candidateFiles = new Set(candidate.files);\n let best: { record: DecisionRecord; similarity: number } | null = null;\n\n for (const record of existing) {\n if (record.status !== \"active\") continue;\n const similarity = jaccard(\n candidateTokens,\n tokenSet(`${record.title} ${record.body}`)\n );\n const sharesFile = record.files.some((f) => candidateFiles.has(f));\n const threshold = sharesFile\n ? DUPLICATE_JACCARD_WITH_SHARED_FILE\n : DUPLICATE_JACCARD;\n if (similarity >= threshold && (!best || similarity > best.similarity)) {\n best = { record, similarity };\n }\n }\n return best;\n}\n\nfunction sanitizeAnchorFiles(rootDir: string, files: string[]): string[] {\n const resolvedRoot = path.resolve(rootDir);\n return files.filter((f) => {\n const resolved = path.resolve(resolvedRoot, f);\n return (\n resolved.startsWith(resolvedRoot) &&\n !f.startsWith(\"/\") &&\n !f.includes(\"..\")\n );\n });\n}\n\nexport interface UpsertDecisionInput {\n title: string;\n body: string;\n category: DecisionCategory;\n files?: string[];\n /** Existing id to update. Same id + unchanged content = re-verify (re-pin to HEAD). */\n id?: string;\n /** Id of a decision this one replaces; the old record is kept, marked superseded. */\n supersedes?: string;\n /** Save even when a near-duplicate was detected. */\n force?: boolean;\n}\n\nexport type UpsertDecisionResult =\n | {\n status: \"created\" | \"updated\" | \"reverified\" | \"superseded_and_created\";\n id: string;\n totalActive: number;\n warnings: string[];\n pruneCandidates?: string[];\n }\n | { status: \"duplicate_suspected\"; existing: DecisionRecord; hint: string }\n | { status: \"error\"; error: string };\n\nexport async function upsertDecision(\n rootDir: string,\n input: UpsertDecisionInput\n): Promise<UpsertDecisionResult> {\n const title = input.title.trim();\n const body = input.body.trim();\n if (title.length === 0 || body.length === 0) {\n return { status: \"error\", error: \"title and body must be non-empty\" };\n }\n if (title.length > TITLE_MAX_CHARS) {\n return {\n status: \"error\",\n error: `title exceeds ${TITLE_MAX_CHARS} chars — tighten it to a specific headline`,\n };\n }\n if (body.length > BODY_MAX_CHARS) {\n return {\n status: \"error\",\n error: `body exceeds ${BODY_MAX_CHARS} chars — record the decision, not the transcript`,\n };\n }\n\n const existing = await loadDecisions(rootDir);\n const byId = new Map(existing.map((r) => [r.id, r]));\n const now = new Date().toISOString();\n const head = await getCurrentGitHash(rootDir);\n const warnings: string[] = [];\n\n const files = sanitizeAnchorFiles(rootDir, input.files ?? []);\n if (input.files && files.length < input.files.length) {\n warnings.push(\"some anchor paths were outside the repo and were dropped\");\n }\n // Nonexistent anchors warn but save — a deprecation note may outlive its file.\n for (const f of files) {\n try {\n await fs.access(path.join(rootDir, f));\n } catch {\n warnings.push(`anchor file does not exist on disk: ${f}`);\n }\n }\n\n // Update / re-verify path\n if (input.id) {\n const record = byId.get(input.id);\n if (!record) {\n return { status: \"error\", error: `no decision with id \"${input.id}\"` };\n }\n const unchanged =\n record.title === title &&\n record.body === body &&\n record.category === input.category &&\n JSON.stringify(record.files) === JSON.stringify(files.length > 0 ? files : record.files);\n const updated: DecisionRecord = {\n ...record,\n title,\n body,\n category: input.category,\n files: input.files !== undefined ? files : record.files,\n updatedAt: now,\n refreshedHash: head,\n };\n await saveDecisionRecord(rootDir, updated);\n return {\n status: unchanged ? \"reverified\" : \"updated\",\n id: record.id,\n totalActive: existing.filter((r) => r.status === \"active\").length,\n warnings,\n };\n }\n\n // Create path — dedupe first\n if (!input.force) {\n const duplicate = findNearDuplicate({ title, body, files }, existing);\n if (duplicate) {\n return {\n status: \"duplicate_suspected\",\n existing: duplicate.record,\n hint: `A similar decision exists (\"${duplicate.record.title}\"). Call save_decision with id=\"${duplicate.record.id}\" to update/merge into it, or force:true if genuinely distinct.`,\n };\n }\n }\n\n // Supersede\n if (input.supersedes) {\n const old = byId.get(input.supersedes);\n if (!old) {\n return {\n status: \"error\",\n error: `no decision with id \"${input.supersedes}\" to supersede`,\n };\n }\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n await saveDecisionRecord(rootDir, {\n ...old,\n status: \"superseded\",\n supersededBy: id,\n updatedAt: now,\n });\n const record: DecisionRecord = {\n version: 1,\n id,\n title,\n body,\n category: input.category,\n files,\n createdAt: now,\n updatedAt: now,\n refreshedHash: head,\n status: \"active\",\n };\n await saveDecisionRecord(rootDir, record);\n return {\n status: \"superseded_and_created\",\n id,\n totalActive: existing.filter((r) => r.status === \"active\").length,\n warnings,\n };\n }\n\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n const record: DecisionRecord = {\n version: 1,\n id,\n title,\n body,\n category: input.category,\n files,\n createdAt: now,\n updatedAt: now,\n refreshedHash: head,\n status: \"active\",\n };\n await saveDecisionRecord(rootDir, record);\n\n const totalActive =\n existing.filter((r) => r.status === \"active\").length + 1;\n const result: UpsertDecisionResult = {\n status: \"created\",\n id,\n totalActive,\n warnings,\n };\n if (totalActive > MAX_ACTIVE_DECISIONS) {\n // Never auto-evict git-committed team knowledge — surface candidates\n // for a human cleanup PR instead.\n result.pruneCandidates = existing\n .filter((r) => r.status === \"superseded\")\n .map((r) => r.id)\n .slice(0, 10);\n warnings.push(\n `${totalActive} active decisions exceeds the soft cap of ${MAX_ACTIVE_DECISIONS} — consider a cleanup PR (superseded records first)`\n );\n }\n return result;\n}\n","import path from \"node:path\";\n\n// Question/filler words that carry no signal about which entry a task\n// touches. Domain words (\"auth\", \"drift\") are never in this list.\nconst STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"and\", \"or\", \"of\", \"to\", \"in\", \"on\", \"for\", \"with\",\n \"how\", \"does\", \"do\", \"is\", \"are\", \"was\", \"what\", \"where\", \"which\", \"why\",\n \"when\", \"who\", \"i\", \"we\", \"my\", \"our\", \"you\", \"your\", \"it\", \"its\", \"this\",\n \"that\", \"these\", \"those\", \"can\", \"could\", \"should\", \"would\", \"will\",\n \"want\", \"need\", \"please\", \"about\", \"into\", \"from\", \"when\", \"there\", \"any\",\n \"all\", \"some\", \"not\", \"but\", \"also\", \"just\", \"like\", \"get\", \"make\", \"use\",\n \"new\", \"work\", \"works\", \"working\", \"implement\", \"implemented\", \"change\",\n \"changed\", \"file\", \"files\", \"code\",\n]);\n\n/** Split camelCase/PascalCase/kebab/snake/path into lowercase word tokens. */\nexport function tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 2 && !STOPWORDS.has(t));\n}\n\n/** Crude singular/plural folding so \"flows\" matches \"flow\" etc. */\nexport function stem(token: string): string {\n return token.length > 3 && token.endsWith(\"s\") ? token.slice(0, -1) : token;\n}\n\nexport function tokenSet(text: string): Set<string> {\n return new Set(tokenize(text).map(stem));\n}\n\nexport interface Scorable {\n name: string;\n description: string;\n files: string[];\n}\n\n/**\n * Lexical relevance of one entry to the task. Name hits are the strongest\n * signal, then description, then file-path words. Each distinct task token\n * counts once at its best weight, so a token appearing everywhere doesn't\n * triple-count.\n */\nexport function scoreEntry(taskTokens: Set<string>, entry: Scorable): number {\n const nameTokens = tokenSet(entry.name);\n const descTokens = tokenSet(entry.description);\n const fileTokens = tokenSet(entry.files.map((f) => path.basename(f)).join(\" \"));\n\n let score = 0;\n for (const token of taskTokens) {\n if (nameTokens.has(token)) score += 3;\n else if (descTokens.has(token)) score += 1;\n else if (fileTokens.has(token)) score += 1;\n }\n return score;\n}\n\n/** Jaccard similarity of two token sets: |∩| / |∪|, 0 when both empty. */\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersection = 0;\n for (const token of a) if (b.has(token)) intersection++;\n return intersection / (a.size + b.size - intersection);\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\n/**\n * History window for the co-change matrix. One capped git log for the whole\n * repo — unlike impact.ts's per-target walk, review analyzes many files at\n * once and needs a single pass.\n */\nconst HISTORY_COMMITS = 1500;\n\n/** Below this many commits for a file, a co-change rate is noise. */\nconst MIN_FILE_COMMITS = 5;\n/** A partner must share at least this many commits to count. */\nconst MIN_SHARED_COMMITS = 4;\n/** ...and appear in at least this fraction of the changed file's commits. */\nconst MIN_COCHANGE_RATE = 0.6;\n/** Commits touching more files than this are refactors, not signal. */\nconst MAX_COMMIT_FILES = 30;\n\nexport interface CochangeFinding {\n changedFile: string;\n missingPartner: string;\n sharedCommits: number;\n fileCommits: number;\n /** sharedCommits / fileCommits, rounded to 2 places. */\n rate: number;\n}\n\ninterface CochangeMatrix {\n commitsByFile: Map<string, Set<number>>;\n totalCommits: number;\n}\n\nasync function buildMatrix(resolvedRoot: string): Promise<CochangeMatrix | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", `-n${HISTORY_COMMITS}`, \"--format=%x01\", \"--name-only\", \"-M\"],\n { cwd: resolvedRoot, maxBuffer: 100 * 1024 * 1024 }\n );\n const commitsByFile = new Map<string, Set<number>>();\n const blocks = stdout.split(\"\\x01\");\n let index = 0;\n for (const block of blocks) {\n const files = block\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0 && !l.startsWith(\".mason/\"));\n if (files.length === 0 || files.length > MAX_COMMIT_FILES) continue;\n for (const file of files) {\n let set = commitsByFile.get(file);\n if (!set) {\n set = new Set();\n commitsByFile.set(file, set);\n }\n set.add(index);\n }\n index++;\n }\n return { commitsByFile, totalCommits: index };\n } catch {\n return null;\n }\n}\n\n/**\n * For each changed file, find its historical co-change partners that this\n * diff leaves untouched: files that appeared in >= MIN_COCHANGE_RATE of the\n * changed file's commits (within the window) but are absent from the diff.\n * Deterministic — pure git history, no LLM. Returns null when history is\n * unavailable.\n */\nexport async function findMissingPartners(\n resolvedRoot: string,\n changedFiles: string[],\n existsOnDisk: (relPath: string) => Promise<boolean>\n): Promise<CochangeFinding[] | null> {\n const matrix = await buildMatrix(resolvedRoot);\n if (!matrix) return null;\n\n const changedSet = new Set(changedFiles);\n const findings: CochangeFinding[] = [];\n\n for (const changedFile of changedFiles) {\n const fileCommits = matrix.commitsByFile.get(changedFile);\n if (!fileCommits || fileCommits.size < MIN_FILE_COMMITS) continue;\n\n for (const [partner, partnerCommits] of matrix.commitsByFile) {\n if (partner === changedFile || changedSet.has(partner)) continue;\n let shared = 0;\n for (const c of fileCommits) {\n if (partnerCommits.has(c)) shared++;\n }\n if (shared < MIN_SHARED_COMMITS) continue;\n const rate = shared / fileCommits.size;\n if (rate < MIN_COCHANGE_RATE) continue;\n if (!(await existsOnDisk(partner))) continue;\n findings.push({\n changedFile,\n missingPartner: partner,\n sharedCommits: shared,\n fileCommits: fileCommits.size,\n rate: Math.round(rate * 100) / 100,\n });\n }\n }\n\n findings.sort((a, b) => b.rate - a.rate || b.sharedCommits - a.sharedCommits);\n return findings;\n}\n","import { runReviewCli } from \"../src/review/cli.js\";\n\nrunReviewCli(process.argv.slice(2)).then(\n (code) => process.exit(code),\n (err) => {\n process.stderr.write(`mason-review error: ${err}\\n`);\n process.exit(2);\n }\n);\n"],"mappings":";;;AAAA,OAAOA,WAAU;;;ACAjB,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACH1B,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACH1B,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;AAC1B,OAAOC,SAAQ;;;ACJf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS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AAU,IAAI;AAAA,EACvB,SAAS,OAAO;AACd,OAAG,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAC7D,OAAG,IAAI,KAAK;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,KAAK,MAAM;AACb,OAAG,IAAI,KAAK;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,UAAUE,MAAK,QAAQ,KAAK,GAAG;AACrC,QAAM,OAAO,KAAK,QAAS,MAAM,YAAY,OAAO;AACpD,MAAI,CAAC,MAAM;AACT,OAAG;AAAA,MACD,gCAAgC,OAAO;AAAA,IACzC;AACA,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,MAAM,cAAc,SAAS,IAAI;AAChD,MAAI,CAAC,QAAQ;AACX,OAAG;AAAA,MACD,0CAA0C,IAAI,gBAAgB,OAAO;AAAA,IACvE;AACA,WAAO;AAAA,EACT;AAEA,MAAI,KAAK,MAAM;AACb,OAAG,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,EACxC,OAAO;AACL,OAAG,IAAI,oBAAoB,MAAM,CAAC;AAAA,EACpC;AACA,SAAO,OAAO,gBAAgB,SAAS,IAAI,IAAI;AACjD;;;ASxJA,aAAa,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAClC,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,QAAQ;AACP,YAAQ,OAAO,MAAM,uBAAuB,GAAG;AAAA,CAAI;AACnD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["path","fs","path","execFile","promisify","fs","path","execFile","promisify","fs","path","execFile","promisify","fg","path","fg","exec","promisify","execFile","exec","promisify","execFile","exec","fs","path","path","path","fs","execFile","promisify","exec","exec","promisify","execFile","path","fs","path"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mason-context",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "MCP server for codebase context engineering — feature-to-file concept maps, change impact, and Confluence wiki sync for AI coding assistants",
5
5
  "type": "module",
6
6
  "mcpName": "com.adrianczuczka/mason",
@@ -10,7 +10,8 @@
10
10
  "mason-context": "dist/mason-mcp.js",
11
11
  "mason-drift": "dist/mason-drift.js",
12
12
  "mason-audit": "dist/mason-audit.js",
13
- "mason-hook": "dist/mason-hook.js"
13
+ "mason-hook": "dist/mason-hook.js",
14
+ "mason-review": "dist/mason-review.js"
14
15
  },
15
16
  "scripts": {
16
17
  "build": "tsup",