mason-context 0.11.0 → 0.13.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/CHANGELOG.md +26 -0
- package/README.md +77 -6
- package/dist/mason-audit.js +105 -33
- package/dist/mason-audit.js.map +1 -1
- package/dist/mason-auto.js +4487 -0
- package/dist/mason-auto.js.map +1 -0
- package/dist/mason-drift.js +1 -1
- package/dist/mason-drift.js.map +1 -1
- package/dist/mason-hook.js +1 -1
- package/dist/mason-hook.js.map +1 -1
- package/dist/mason-mcp.js +5974 -4308
- package/dist/mason-mcp.js.map +1 -1
- package/dist/mason-review.js +1 -1
- package/dist/mason-review.js.map +1 -1
- package/package.json +4 -1
package/dist/mason-audit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/audit/cli.ts","../src/audit/audit.ts","../src/drift/drift.ts","../src/snapshot/snapshot.ts","../src/utils/files.ts","../src/utils/paths.ts","../src/utils/storage.ts","../src/test-map.ts","../src/audit/docs.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/audit/git.ts","../src/audit/types.ts","../src/audit/checks/deleted-reference.ts","../src/audit/checks/new-module.ts","../src/audit/checks/stale-count.ts","../src/audit/checks/dead-command.ts","../src/audit/checks/deps-changed.ts","../src/decisions/drift.ts","../src/decisions/decisions.ts","../src/context/lexical.ts","../src/decisions/provenance.ts","../src/audit/checks/decision-anchor.ts","../src/audit/checks/index.ts","../src/audit/repair.ts","../bin/mason-audit.ts"],"sourcesContent":["import path from \"node:path\";\nimport { computeAudit } from \"./audit.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport { prepareRepair, verifyRepair, formatRepairSummary, repairExitCode } from \"./repair.js\";\nimport type { AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits the repo's AI context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\nagainst repo reality: referenced paths that no longer exist, undocumented\nmodules, stale counts, dead npm scripts, and manifests newer than the doc.\nDeterministic: no LLM call, no network – safe for CI. Works on any repo with\na context file; no Mason setup required.\n\nOptions:\n --dir <path> Project root to audit (default: current directory)\n --json Print the full audit report as JSON (additive-only schema)\n --fix-prompt When issues exist, print a work order for ANY coding agent\n (Claude, Codex, Gemini, ...) – pipe it to your agent CLI to\n repair the findings. Includes advisories that require review.\n --prepare-repair Save the original audit under .mason/reports/repairs/ before edits\n --verify-repair <path>\n Compare against that saved baseline, using its original checks\n --checks <list> Comma-separated subset of checks to run (default: all):\n ${ALL_CHECKS.join(\", \")}\n --help Show this help\n\nExit codes:\n 0 no issues (advisories may still be present)\n 1 provable issues found\n 2 error (no context file, not a git repository, bad arguments)\n\nWith --verify-repair: 0 verified by the original checks; 1 issues remain;\n2 incomplete (unverified findings, skipped checks, or advisories needing review).\nPreparation writes only a baseline; verification and ordinary audits are read-only.`;\n\nexport interface AuditCliIo {\n out: (line: string) => void;\n err: (line: string) => void;\n}\n\ninterface ParsedArgs {\n dir: string;\n json: boolean;\n fixPrompt: boolean;\n help: boolean;\n checks: CheckName[] | undefined;\n prepareRepair: boolean;\n baseline?: string;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const parsed: ParsedArgs = {\n dir: process.cwd(),\n json: false,\n fixPrompt: false,\n help: false,\n checks: undefined,\n prepareRepair: 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 === \"--fix-prompt\") {\n parsed.fixPrompt = true;\n } else if (arg === \"--prepare-repair\") {\n parsed.prepareRepair = true;\n } else if (arg === \"--verify-repair\") {\n const value = argv[++i];\n if (!value || value.startsWith(\"--\")) throw new Error(\"--verify-repair requires a baseline path\");\n parsed.baseline = value;\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 === \"--checks\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--checks requires a comma-separated list\");\n const names = value.split(\",\").map((n) => n.trim()).filter(Boolean);\n if (!names.length) throw new Error(\"--checks requires at least one check\");\n for (const name of names) {\n if (!ALL_CHECKS.includes(name as CheckName)) {\n throw new Error(\n `Unknown check: ${name} (valid: ${ALL_CHECKS.join(\", \")})`\n );\n }\n }\n parsed.checks = names as CheckName[];\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\nfunction issueLine(issue: AuditIssue): string {\n const where =\n issue.anchor.line !== null ? `line ${issue.anchor.line}` : \"doc-level\";\n const likely = issue.confidence === \"likely\" ? \" (likely)\" : \"\";\n return ` [${issue.type}]${likely} ${where}: ${issue.message}`;\n}\n\nexport function formatAuditSummary(report: AuditReport): string {\n const lines: string[] = [];\n const reviewCount = report.advisories.length + (report.suppressedAdvisories?.length ?? 0);\n\n for (const doc of report.docs) {\n const docIssues = report.issues.filter((i) => i.anchor.doc === doc.path);\n const committed = doc.lastCommit\n ? `last committed ${doc.lastCommit.date.slice(0, 10)}, ${doc.lastCommit.hash.slice(0, 7)}`\n : \"untracked\";\n if (docIssues.length === 0) {\n lines.push(`${doc.path} – clean (${committed})`);\n continue;\n }\n lines.push(\n `${doc.path} – ${docIssues.length} issue${docIssues.length === 1 ? \"\" : \"s\"} (${committed})`\n );\n for (const issue of docIssues) lines.push(issueLine(issue));\n }\n\n // Issues anchored outside the docs list (defensive; new-module anchors to\n // the primary doc, so this should stay empty).\n const docPaths = new Set(report.docs.map((d) => d.path));\n for (const issue of report.issues) {\n if (!docPaths.has(issue.anchor.doc)) lines.push(issueLine(issue));\n }\n\n if (report.advisories.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of report.advisories) {\n lines.push(` [${advisory.type}] ${advisory.anchor.doc}: ${advisory.message}`);\n }\n }\n if (report.skippedChecks.length > 0) {\n for (const skip of report.skippedChecks) {\n lines.push(` [skipped] ${skip.check}: ${skip.reason}`);\n }\n }\n\n for (const advisory of report.suppressedAdvisories ?? []) {\n lines.push(` [suppressed; unresolved] ${advisory.type} ${advisory.anchor.doc}: ${advisory.message}`);\n }\n\n lines.push(\n report.clean\n ? reviewCount || report.skippedChecks.length\n ? `No audit issues detected (${report.docs.length} docs audited); ${reviewCount} advisories remain for review, ${report.skippedChecks.length} checks skipped.`\n : `Context files are clean (${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"} audited).`\n : `${report.issues.length} issue${report.issues.length === 1 ? \"\" : \"s\"} across ${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"}.`\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Provider-neutral work order: any coding agent can execute it. The evidence\n * is deterministic; the agent's job is judgment scoped to exactly these\n * claims – never a free-form doc rewrite.\n */\nexport function formatFixPrompt(report: AuditReport, baselinePath?: string): string {\n const flaggedDocs = [...new Set(report.issues.map((i) => i.anchor.doc))];\n const lines: string[] = [];\n lines.push(\n \"Review the flagged context claims using the evidence below. Make minimal repairs within the user's authorized scope. A setup-only or audit-only request does not authorize rewriting existing documentation.\"\n );\n lines.push(\"\");\n lines.push(\"RULES:\");\n lines.push(baselinePath\n ? `- Preserve the original repair baseline: ${JSON.stringify(baselinePath)}. Do not replace it after editing.`\n : \"- Before the first edit, call mason_repair with action: prepare, or run mason-audit --prepare-repair --json with the same --dir and --checks. Keep the returned baselinePath through verification.\");\n lines.push(\n `- Edit ONLY these files: ${flaggedDocs.join(\", \") || \"none (advisory review only)\"}. Bring the docs into agreement with verified source evidence; do not change source code or configs to silence findings.`\n );\n lines.push(\n \"- Keep diffs minimal: change the smallest span that makes each claim true.\"\n );\n lines.push(\n \"- Never invent content. Every replacement must be grounded in the evidence below or in files you read from this repository.\"\n );\n lines.push(\"- Inspect likely findings before editing: heuristic evidence may describe an intentional omission or an example.\");\n lines.push(\n \"- deleted-reference: if evidence shows renamedTo, update the path; otherwise remove the reference, or rephrase to past tense if the sentence is about history. Deleted paths inside directory trees: delete the tree line.\"\n );\n lines.push(\n \"- stale-count: replace the number with the actual count from the evidence.\"\n );\n lines.push(\n \"- dead-command: replace with the correct script from availableScripts if an obvious rename exists; otherwise remove the command mention.\"\n );\n lines.push(\n \"- new-module: add a one-line factual mention of the directory where sibling modules are described; read the directory's files first and describe only what you verified.\"\n );\n lines.push(\n \"- ADVISORIES require a separate assessment of the cited commits or decision evidence. Report any review you perform and what remains unknown. Their disappearance after edits or a commit does not establish review or approval.\"\n );\n lines.push(\"\");\n lines.push(\"AUDIT REPORT (current context files and repository evidence, including local edits):\");\n lines.push(\n JSON.stringify(\n { root: report.root, checks: report.checksRun, issues: report.issues, advisories: report.advisories,\n suppressedAdvisories: report.suppressedAdvisories, skippedChecks: report.skippedChecks },\n null,\n 2\n )\n );\n lines.push(\"\");\n lines.push(\n \"After edits, call mason_repair with action: verify and the original baselinePath, or mason-audit --verify-repair <baselinePath> --dir <project>. Repeat against the same baseline after any final documentation commit. Summarize resolved, unresolved, review-required, unverified, and new findings with their evidence. Do not report a suppressed or unavailable check as fixed. This audit covers the listed context files; independently discovered README or application issues need their own validation.\"\n );\n return lines.join(\"\\n\");\n}\n\nexport async function runAuditCli(\n argv: string[],\n io: AuditCliIo = {\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 if (args.json && args.fixPrompt) {\n throw new Error(\"--json and --fix-prompt are mutually exclusive\");\n }\n if (args.baseline && (args.prepareRepair || args.checks || args.fixPrompt)) {\n throw new Error(\"--verify-repair cannot be combined with --prepare-repair, --checks, or --fix-prompt; verification uses the original scope\");\n }\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 if (args.baseline || args.prepareRepair) {\n try {\n if (args.baseline) {\n const verification = await verifyRepair(rootDir, args.baseline);\n io.out(args.json ? JSON.stringify(verification, null, 2) : formatRepairSummary(verification));\n return repairExitCode(verification);\n }\n const prepared = await prepareRepair(rootDir, args.checks);\n io.out(args.json ? JSON.stringify({ ...prepared, workOrder: formatFixPrompt(prepared.report, prepared.baselinePath) }, null, 2)\n : args.fixPrompt ? formatFixPrompt(prepared.report, prepared.baselinePath)\n : `Repair baseline: ${prepared.baselinePath}\\n${formatAuditSummary(prepared.report)}`);\n return prepared.report.clean ? 0 : 1;\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n return 2;\n }\n }\n const report = await computeAudit(rootDir, { checks: args.checks });\n\n if (!report) {\n io.err(\n `No CLAUDE.md, .claude/CLAUDE.md, or AGENTS.md found in ${rootDir}.`\n );\n return 2;\n }\n\n if (!report.gitAvailable) {\n io.err(\n `Could not determine git HEAD in ${rootDir} – not a git repository, or git is unavailable.`\n );\n return 2;\n }\n\n if (args.fixPrompt) {\n io.out(\n report.clean && !report.advisories.length && !report.suppressedAdvisories?.length\n ? formatAuditSummary(report) : formatFixPrompt(report)\n );\n return report.clean ? 0 : 1;\n }\n\n if (args.json) {\n io.out(JSON.stringify(report, null, 2));\n } else {\n io.out(formatAuditSummary(report));\n }\n return report.clean ? 0 : 1;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport type { FileChange } from \"../drift/drift.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { discoverDocs } from \"./docs.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { CHECKS } from \"./checks/index.js\";\nimport type { CheckContext } from \"./checks/index.js\";\n\nexport interface AuditOptions {\n /** Subset of checks to run; defaults to all. */\n checks?: CheckName[];\n}\n\n/**\n * Audit the repo's context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\n * against repo reality. Fully deterministic — git, filesystem, and lexical\n * extraction only; no LLM, no network. Returns null when no context file\n * exists.\n */\nexport async function computeAudit(\n rootDir: string,\n options: AuditOptions = {}\n): Promise<AuditReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const docs = await discoverDocs(resolvedRoot);\n if (docs.length === 0) return null;\n\n const headHash = await getCurrentGitHash(resolvedRoot);\n const report: AuditReport = {\n version: 1,\n root: resolvedRoot,\n gitAvailable: headHash !== \"unknown\",\n headHash,\n checksRun: [],\n docs: docs.map((d) => ({\n path: d.path,\n lastCommit: d.lastCommit,\n dirty: d.dirty,\n lineCount: d.lineCount,\n })),\n decisionsChecked: false,\n issues: [],\n advisories: [],\n suppressedAdvisories: [],\n skippedChecks: [],\n clean: true,\n };\n\n // Without git the provability gates cannot run — the caller treats this\n // as an error rather than silently degrading precision.\n if (!report.gitAvailable) return report;\n\n const changesSinceDoc = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n changesSinceDoc.set(\n doc.path,\n doc.lastCommit\n ? await getChangesWithStatus(resolvedRoot, doc.lastCommit.hash)\n : null\n );\n }\n\n let decisionsPresent = false;\n try {\n await fs.access(path.join(resolvedRoot, \".mason\", \"decisions\"));\n decisionsPresent = true;\n } catch {\n // No decision store — the check stays dark (zero-setup path).\n }\n report.decisionsChecked = decisionsPresent;\n\n const ctx: CheckContext = {\n root: resolvedRoot,\n docs,\n headHash,\n changesSinceDoc,\n decisionsPresent,\n };\n\n const selected = options.checks ?? ALL_CHECKS;\n for (const name of ALL_CHECKS) {\n if (!selected.includes(name)) continue;\n const { issues, advisories, suppressedAdvisories, skipped } = await CHECKS[name](ctx);\n report.checksRun!.push(name);\n report.issues.push(...issues);\n report.advisories.push(...advisories);\n report.suppressedAdvisories!.push(...(suppressedAdvisories ?? []));\n report.skippedChecks.push(...skipped);\n }\n\n report.clean = report.issues.length === 0;\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\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { matchingPaths } from \"../utils/paths.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 WorkingTreeReport {\n available: boolean;\n changedFiles: string[];\n untrackedFiles: string[];\n}\n\nexport interface DriftReport {\n /** Live entry state; committed drift alone continues to drive CLI exit codes. */\n featureFreshness?: Record<string, Freshness>;\n flowFreshness?: Record<string, Freshness>;\n workingTree?: WorkingTreeReport;\n verification?: { neverVerified: number; failed: string[] };\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\nfunction parseChanges(output: string): FileChange[] {\n const fields = output.split(\"\\0\");\n const changes: FileChange[] = [];\n for (let i = 0; i < fields.length && fields[i];) {\n const code = fields[i++];\n const first = fields[i++];\n if (!first) break;\n const second = /^[RC]/.test(code) ? fields[i++] : undefined;\n const change: FileChange = second\n ? code.startsWith(\"R\") ? { status: \"renamed\", path: second, previousPath: first } : { status: \"added\", path: second }\n : { status: code === \"A\" ? \"added\" : code === \"D\" ? \"deleted\" : \"modified\", path: first };\n if (change.path.startsWith(\".mason/\") && (!change.previousPath || change.previousPath.startsWith(\".mason/\"))) continue;\n changes.push(change);\n }\n return changes;\n}\n\nexport function touchedPaths(changes: FileChange[]): string[] {\n return [...new Set(changes.flatMap(c => c.previousPath ? [c.previousPath, c.path] : [c.path]))].sort();\n}\n\nexport async function getChangesWithStatus(resolvedRoot: string, fromHash: string, toHash = \"HEAD\"): Promise<FileChange[] | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\") || !toHash || toHash === \"unknown\" || toHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", fromHash, toHash, \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 });\n return parseChanges(stdout);\n } catch { return null; }\n}\n\nexport async function getWorkingTree(resolvedRoot: string): Promise<WorkingTreeReport> {\n try {\n const [diff, untracked] = await Promise.all([\n exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n exec(\"git\", [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n ]);\n const untrackedFiles = untracked.stdout.split(\"\\0\").filter(f => f && !f.startsWith(\".mason/\"));\n return { available: true, changedFiles: [...new Set([...touchedPaths(parseChanges(diff.stdout)), ...untrackedFiles])].sort(), untrackedFiles };\n } catch { return { available: false, changedFiles: [], untrackedFiles: [] }; }\n}\n\nasync function countCommitsBehind(\n resolvedRoot: string,\n fromHash: string\n): Promise<number | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\")) return 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(rootDir: string): Promise<DriftReport | null> {\n const root = path.resolve(rootDir);\n const snapshot = await loadSnapshot(root);\n if (!snapshot) return null;\n const [headHash, workingTree] = await Promise.all([getCurrentGitHash(root), getWorkingTree(root)]);\n const hashFor = (entry: { refreshedHash?: string }) => entry.refreshedHash ?? snapshot.gitHash;\n const entries = [...Object.values(snapshot.features), ...Object.values(snapshot.flows)];\n const hashes = new Set([snapshot.gitHash, ...entries.map(hashFor)]);\n const changesByHash = new Map<string, FileChange[] | null>();\n await Promise.all([...hashes].map(async hash => {\n changesByHash.set(hash, hash === headHash && headHash !== \"unknown\" ? [] : await getChangesWithStatus(root, hash));\n }));\n const historyAvailable = headHash !== \"unknown\" && [...changesByHash.values()].every(changes => changes !== null);\n const mappedFiles = collectMappedFiles(snapshot);\n const report: DriftReport = {\n stale: !historyAvailable,\n snapshotHash: snapshot.gitHash, headHash,\n commitsBehind: 0, historyAvailable,\n changedFiles: [], staleFeatures: {}, staleFlows: {},\n totalFeatures: Object.keys(snapshot.features).length,\n totalFlows: Object.keys(snapshot.flows).length,\n unmappedFiles: [], ghostFiles: await findGhostFiles(root, mappedFiles), renames: [],\n recommendation: historyAvailable ? \"up-to-date\" : \"full-rebuild\",\n featureFreshness: {}, flowFreshness: {}, workingTree,\n verification: {\n neverVerified: entries.filter(e => !e.verifiedAt).length,\n failed: [...Object.entries(snapshot.features), ...Object.entries(snapshot.flows)].filter(([, e]) => e.verificationFailed).map(([name]) => name),\n },\n };\n const counts = await Promise.all([...hashes].map(hash => hash === headHash ? 0 : countCommitsBehind(root, hash)));\n const knownCounts = counts.filter((n): n is number => n !== null);\n report.commitsBehind = knownCounts.length ? Math.max(...knownCounts) : null;\n\n const check = (name: string, files: string[], hash: string, staleEntries: Record<string, string[]>, freshness: Record<string, Freshness>) => {\n const changes = changesByHash.get(hash);\n const committedHits = changes ? matchingPaths(files, touchedPaths(changes)) : [];\n if (committedHits.length) staleEntries[name] = committedHits;\n const localHits = matchingPaths(files, workingTree.changedFiles);\n freshness[name] = files.length === 0 || changes === null || changes === undefined || !workingTree.available ? \"unknown\"\n : committedHits.length || localHits.length || files.some(f => report.ghostFiles.includes(f)) ? \"changed\" : \"current\";\n };\n for (const [name, feature] of Object.entries(snapshot.features)) {\n check(name, [...feature.files, ...(feature.tests ?? [])], hashFor(feature), report.staleFeatures, report.featureFreshness!);\n }\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n check(name, flow.chain, hashFor(flow), report.staleFlows, report.flowFreshness!);\n }\n\n const allChanges = [...changesByHash.values()].flatMap(changes => changes ?? []);\n report.changedFiles = [...new Set(allChanges.map(c => c.path))].sort();\n // Complete coverage, including omissions from a map saved at HEAD. Untracked\n // files remain in workingTree and never change the committed-drift exit code.\n const sourceFiles = new Set(await listSourceFiles(root));\n let committedFiles: Set<string> = new Set();\n try {\n const { stdout } = await exec(\"git\", [\"ls-tree\", \"-r\", \"--name-only\", \"-z\", \"HEAD\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n committedFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch { report.historyAvailable = false; report.stale = true; }\n report.unmappedFiles = [...sourceFiles].filter(f => committedFiles.has(f) && !mappedFiles.has(f)).sort();\n const renames = new Map<string, { from: string; to: string }>();\n for (const change of allChanges) {\n if (change.status === \"renamed\" && change.previousPath) renames.set(`${change.previousPath}\\0${change.path}`, { from: change.previousPath, to: change.path });\n }\n report.renames = [...renames.values()];\n const changedMapped = new Set([...Object.values(report.staleFeatures).flat(), ...Object.values(report.staleFlows).flat()]);\n // A locally deleted file is a live-edit warning, not committed map drift.\n const committedGhosts = report.ghostFiles.filter(f => !workingTree.changedFiles.includes(f));\n report.stale ||= changedMapped.size > 0 || report.unmappedFiles.length > 0 || committedGhosts.length > 0;\n if (!report.historyAvailable) report.recommendation = \"full-rebuild\";\n else if (!report.stale) report.recommendation = \"up-to-date\";\n else report.recommendation = changedMapped.size >= FULL_REBUILD_MIN_CHANGED_MAPPED_FILES && changedMapped.size / Math.max(1, mappedFiles.size) > FULL_REBUILD_FRACTION ? \"full-rebuild\" : \"incremental\";\n return report;\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess } from \"../utils/files.js\";\nexport { SOURCE_GLOB, SOURCE_IGNORE } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.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) — 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 verifiedHash?: 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 verifiedHash?: 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\nconst repoPath = z.string().refine(value => normalizeRepoPath(value) !== null, \"Expected a relative repository path\");\nconst verificationFields = {\n refreshedHash: z.string().optional(), verifiedAt: z.string().optional(),\n verifiedHash: z.string().optional(), verificationFailed: z.boolean().optional(),\n verificationNote: z.string().optional(),\n};\nexport const featureSchema = z.object({\n description: z.string(), files: z.array(repoPath), tests: z.array(repoPath).optional(),\n type: z.enum([\"capability\", \"infrastructure\"]).optional(), ...verificationFields,\n}).passthrough();\nexport const flowSchema = z.object({ description: z.string(), chain: z.array(repoPath), ...verificationFields }).passthrough();\nconst snapshotSchema = z.object({\n version: z.literal(2), createdAt: z.string(), updatedAt: z.string(), gitHash: z.string(),\n features: z.record(featureSchema), flows: z.record(flowSchema),\n}).passthrough();\n\nexport async function loadSnapshot(rootDir: string): Promise<Snapshot | null> {\n const parsed = await readStoreJson(rootDir, \".mason/snapshot.json\");\n if (parsed === null || (parsed as { version?: number }).version === 1) return null;\n const result = snapshotSchema.safeParse(parsed);\n if (!result.success) throw new Error(`Invalid Mason snapshot: ${result.error.message}`);\n return result.data;\n}\n\n/** Context and onboarding can use decisions even when the optional map is broken. */\nexport async function inspectSnapshot(rootDir: string): Promise<{\n status: \"available\" | \"missing\" | \"invalid\";\n snapshot: Snapshot | null;\n diagnostics: StoreDiagnostic[];\n}> {\n try {\n const raw = await readStoreJson(rootDir, \".mason/snapshot.json\");\n const snapshot = raw === null ? null : snapshotSchema.parse(raw);\n return { status: snapshot ? \"available\" : \"missing\", snapshot, diagnostics: [] };\n } catch (error) {\n return { status: \"invalid\", snapshot: null, diagnostics: [{\n path: \".mason/snapshot.json\", message: error instanceof Error ? error.message : String(error),\n }] };\n }\n}\n\nexport async function saveSnapshot(rootDir: string, snapshot: Snapshot): Promise<void> {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(snapshot));\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 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 return (await createFileAccess(resolvedRoot)).list();\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 const access = await createFileAccess(resolvedRoot);\n let allFiles = await access.list();\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 access.read(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 access.read(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 { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\nconst exec = promisify(execFile);\nexport const SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\", \"vue\", \"svelte\", \"kt\", \"kts\", \"java\", \"py\", \"go\", \"rs\", \"swift\", \"rb\", \"cs\", \"cpp\", \"c\", \"h\", \"hpp\", \"dart\", \"php\"];\nexport const SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(\",\")}}`;\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/.mason/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\", \"**/*.lock\",\n \"**/generated/**\", \"**/*.generated.*\", \"**/R.java\", \"**/BuildConfig.java\",\n \"**/package-lock.json\", \"**/yarn.lock\", \"**/pnpm-lock.yaml\",\n];\nexport const MAX_SOURCE_BYTES = 1024 * 1024;\nexport interface ProjectConfig { patterns?: string[]; alwaysInclude?: string[]; ignore?: string[] }\nexport interface SourceFile { path: string; content: string; totalLines: number }\n\nexport function isSensitiveFile(file: string): boolean {\n return file.split(/[\\\\/]/).some(part =>\n /^(?:\\.env(?:\\..*)?|id_rsa.*|id_ed25519.*)$|\\.(?:pem|key|p12|pfx|jks|keystore)$|credentials\\.|secret|^local\\.properties$/i.test(part)\n );\n}\n\n/** Bound reads even if a file grows after stat. Only read regular files. */\nexport async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {\n // Do not block on a FIFO or follow a symlink substituted after resolution.\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > maxBytes) return null;\n const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));\n let bytes = 0;\n while (bytes < buffer.length) {\n const result = await handle.read(buffer, bytes, buffer.length - bytes, null);\n if (result.bytesRead === 0) break;\n bytes += result.bytesRead;\n }\n return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString(\"utf8\");\n } finally { await handle.close(); }\n}\n\nexport async function loadProjectConfig(root: string): Promise<ProjectConfig> {\n try {\n const canonicalRoot = await fs.realpath(root);\n const configPath = await fs.realpath(path.join(root, \".mason/config.json\"));\n if (!isWithinRoot(canonicalRoot, configPath)) throw new Error(\"Project configuration resolves outside the repository\");\n const raw = await readBoundedFile(configPath, 64 * 1024);\n if (raw === null) throw new Error(\"Project configuration is not a regular file or exceeds 64 KiB\");\n const value = JSON.parse(raw);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Expected a configuration object\");\n const config: ProjectConfig = {};\n for (const key of [\"patterns\", \"alwaysInclude\", \"ignore\"] as const) {\n if (value[key] === undefined) continue;\n if (!Array.isArray(value[key]) || !value[key].every((s: unknown) => typeof s === \"string\")) {\n throw new Error(`Configuration ${key} must be an array of strings`);\n }\n config[key] = value[key];\n }\n return config;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new Error(`Cannot apply project file policy: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/** Scoped to one operation, so a later tool call sees newly edited files/ignores. */\nexport async function createFileAccess(rootDir: string) {\n const root = path.resolve(rootDir);\n const canonicalRoot = await fs.realpath(root).catch(() => root);\n const config = await loadProjectConfig(root);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n let gitFiles: Set<string> | null = null;\n try {\n const { stdout } = await exec(\"git\", [\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n gitFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch {\n // File-system projects are supported. Fail closed if this IS a Git repo.\n let inGit = false;\n try { await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: root }); inGit = true; } catch { /* no Git */ }\n if (inGit) throw new Error(\"Cannot enumerate Git files safely\");\n }\n\n async function resolve(file: string): Promise<string | null> {\n const relative = normalizeRepoPath(file);\n if (!relative || isSensitiveFile(relative) || (gitFiles && !gitFiles.has(relative))) return null;\n const candidate = path.join(root, relative);\n try {\n const real = await fs.realpath(candidate);\n if (!isWithinRoot(canonicalRoot, real) || isSensitiveFile(path.relative(canonicalRoot, real))) return null;\n const stat = await fs.stat(real);\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) return null;\n // A symlink must not bypass the target's ignore policy either.\n if (gitFiles && !gitFiles.has(path.relative(canonicalRoot, real).split(path.sep).join(\"/\"))) return null;\n return real;\n } catch { return null; }\n }\n\n async function list(patterns: string | string[] = SOURCE_GLOB, options: { deep?: number; dot?: boolean } = {}): Promise<string[]> {\n const found = await fg(patterns, { cwd: root, ignore, followSymbolicLinks: false, ...options });\n const safe = await Promise.all(found.map(async f => (await resolve(f)) ? f : null));\n return safe.filter((f): f is string => f !== null).sort();\n }\n\n async function read(file: string): Promise<SourceFile | null> {\n const relative = normalizeRepoPath(file);\n if (!relative) return null;\n const real = await resolve(relative);\n if (!real) return null;\n // Apply the same glob exclusions to explicit reads and symlink targets.\n for (const rel of new Set([relative, path.relative(canonicalRoot, real).split(path.sep).join(\"/\")])) {\n if (!(await fg(fg.escapePath(rel), { cwd: root, ignore, dot: true })).length) return null;\n }\n try {\n const content = await readBoundedFile(real, MAX_SOURCE_BYTES);\n return content === null ? null : { path: relative, content, totalLines: content.split(\"\\n\").length };\n } catch { return null; }\n }\n return { root, config, list, read };\n}\n","import path from \"node:path\";\n\n/** One canonical representation for stored paths and decision anchors. */\nexport function normalizeRepoPath(value: string): string | null {\n const slash = value.replace(/\\\\/g, \"/\");\n if (!slash || slash.includes(\"\\0\") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;\n if (slash.split(\"/\").includes(\"..\")) return null;\n const normalized = path.posix.normalize(slash).replace(/\\/$/, \"\");\n return normalized === \".\" ? null : normalized;\n}\n\nexport function sanitizeRepoPaths(files: string[]): string[] {\n return [...new Set(files.map(normalizeRepoPath).filter((p): p is string => p !== null))];\n}\n\nexport function isWithinRoot(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nexport function anchorMatches(anchor: string, file: string): boolean {\n const a = normalizeRepoPath(anchor);\n const f = normalizeRepoPath(file);\n return a !== null && f !== null && (a === f || f.startsWith(`${a}/`));\n}\n\nexport function matchingPaths(anchors: string[], files: Iterable<string>): string[] {\n return [...new Set(files)].filter(file => anchors.some(anchor => anchorMatches(anchor, file)));\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { normalizeRepoPath } from \"./paths.js\";\nimport { readBoundedFile } from \"./files.js\";\n\nexport interface StoreDiagnostic { path: string; message: string }\n\n/** Metadata paths may not contain symlinks, including their parent directories. */\nexport async function storePath(root: string, relative: string, createParents = false): Promise<string> {\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Invalid store path: ${relative}`);\n let current = await fs.realpath(root);\n const parts = normalized.split(\"/\");\n for (let i = 0; i < parts.length; i++) {\n current = path.join(current, parts[i]);\n let stat;\n try { stat = await fs.lstat(current); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n if (createParents && i < parts.length - 1) {\n try { await fs.mkdir(current); } catch (mkdirError) {\n if ((mkdirError as NodeJS.ErrnoException).code !== \"EEXIST\") throw mkdirError;\n }\n stat = await fs.lstat(current);\n }\n }\n if (stat?.isSymbolicLink()) throw new Error(`Symlink in store path: ${relative}`);\n }\n return current;\n}\n\nexport async function readStoreJson(root: string, relative: string): Promise<unknown | null> {\n try {\n const file = await storePath(root, relative);\n const raw = await readBoundedFile(file, 10 * 1024 * 1024);\n if (raw === null) throw new Error(\"file is not regular or exceeds 10 MiB\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null) throw new Error(\"expected a JSON object, received null\");\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new Error(`Invalid Mason store ${relative}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function writeStoreJson(root: string, relative: string, value: unknown): Promise<void> {\n const payload = JSON.stringify(value, null, 2) + \"\\n\";\n if (Buffer.byteLength(payload) > 10 * 1024 * 1024) {\n throw new Error(`Mason store ${relative} exceeds 10 MiB`);\n }\n const file = await storePath(root, relative, true);\n const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);\n try {\n const handle = await fs.open(temporary, \"wx\", 0o600);\n try { await handle.writeFile(payload, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n await fs.rename(temporary, file);\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import path from \"node:path\";\nimport { createFileAccess } from \"./utils/files.js\";\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 const access = await createFileAccess(rootDir);\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 access.list(testPatterns);\n\n // Find all source files\n const sourceFiles = await access.list();\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 { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * All context files audited in v1, in the precedence order the setup\n * playbook uses. Every candidate that exists is audited — a repo can\n * legitimately carry both AGENTS.md and CLAUDE.md, and drift can live in\n * either.\n */\nexport const DOC_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".claude/CLAUDE.md\",\n] as const;\n\nexport interface AuditDoc {\n /** Repo-relative posix path. */\n path: string;\n content: string;\n lineCount: number;\n /** Null when the doc is untracked. */\n lastCommit: CommitRef | null;\n /** Uncommitted edits present. */\n dirty: boolean;\n claims: DocClaims;\n}\n\nasync function isDirty(resolvedRoot: string, relPath: string): Promise<boolean> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"status\", \"--porcelain\", \"--\", relPath],\n { cwd: resolvedRoot }\n );\n return stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs: AuditDoc[] = [];\n for (const candidate of DOC_CANDIDATES) {\n let content: string;\n try {\n content = await fs.readFile(path.join(resolvedRoot, candidate), \"utf-8\");\n } catch {\n continue;\n }\n docs.push({\n path: candidate,\n content,\n lineCount: content.split(\"\\n\").length,\n lastCommit: await lastCommitOf(resolvedRoot, candidate),\n dirty: await isDirty(resolvedRoot, candidate),\n claims: extractClaims(content),\n });\n }\n return docs;\n}\n","import type { PathClaim } from \"./types.js\";\n\n/**\n * A fenced block is treated as a directory tree only when it clearly is one —\n * below this many branch-glyph lines it's more likely an ASCII sketch.\n */\nconst MIN_GLYPH_LINES = 3;\n\nconst GLYPHS = [\"├──\", \"└──\"] as const;\n\nfunction glyphIndex(line: string): number {\n for (const glyph of GLYPHS) {\n const idx = line.indexOf(glyph);\n if (idx !== -1) return idx;\n }\n return -1;\n}\n\n/** Tree furniture: blank, or only vertical bars and whitespace. */\nfunction isSpacerLine(line: string): boolean {\n return /^[\\s│|]*$/.test(line);\n}\n\n/**\n * Strip an inline comment/annotation from a tree entry. Entries commonly\n * carry `# comment` or column-aligned notes after two or more spaces.\n */\nfunction entryName(afterGlyph: string): string | null {\n let name = afterGlyph.replace(/^\\s+/, \"\");\n const hash = name.search(/\\s+#/);\n if (hash !== -1) name = name.slice(0, hash);\n const columns = name.search(/\\s{2,}/);\n if (columns !== -1) name = name.slice(0, columns);\n name = name.trim();\n // A name with remaining internal whitespace is not a path — treat the\n // line as malformed rather than guessing.\n if (!name || /\\s/.test(name)) return null;\n return name;\n}\n\n/**\n * Reconstruct full paths from an ASCII directory tree inside a fenced block.\n *\n * The failure mode must always be a missed claim, never an invented path: a\n * line that doesn't parse cleanly aborts reconstruction below it, and every\n * emitted path still passes the deleted-reference provability gate later.\n *\n * `blockLines` are the fence's content lines; `blockStartLine` is the 1-based\n * doc line number of the first content line.\n */\nexport function extractTreeClaims(\n blockLines: string[],\n blockStartLine: number\n): PathClaim[] {\n const glyphLines = blockLines.filter((l) => glyphIndex(l) !== -1).length;\n if (glyphLines < MIN_GLYPH_LINES) return [];\n\n const claims: PathClaim[] = [];\n // Directories on the path from the root to the current entry, keyed by the\n // column their branch glyph appeared at.\n const stack: Array<{ col: number; name: string }> = [];\n let rootPrefix = \"\";\n let started = false;\n\n for (let i = 0; i < blockLines.length; i++) {\n const line = blockLines[i];\n const col = glyphIndex(line);\n\n if (col === -1) {\n if (isSpacerLine(line)) continue;\n if (!started) {\n // A bare `src/` line above the first glyph names the tree's root.\n const candidate = line.trim();\n if (candidate.endsWith(\"/\") && !/\\s/.test(candidate)) {\n rootPrefix = candidate.replace(/\\/+$/, \"\");\n claims.push({\n path: rootPrefix,\n line: blockStartLine + i,\n excerpt: candidate,\n });\n }\n continue;\n }\n // Unparseable line after the tree began: stop here, keep what we have.\n return claims;\n }\n\n started = true;\n const name = entryName(line.slice(col + GLYPHS[0].length));\n if (name === null) return claims;\n\n while (stack.length > 0 && stack[stack.length - 1].col >= col) {\n stack.pop();\n }\n\n const isDir = name.endsWith(\"/\");\n const cleanName = name.replace(/\\/+$/, \"\");\n const segments = [\n ...(rootPrefix ? [rootPrefix] : []),\n ...stack.map((s) => s.name),\n cleanName,\n ];\n claims.push({\n path: segments.join(\"/\"),\n line: blockStartLine + i,\n excerpt: name,\n });\n\n if (isDir) stack.push({ col, name: cleanName });\n }\n\n return claims;\n}\n","import type {\n CommandClaim,\n CountClaim,\n DocClaims,\n PathClaim,\n} from \"./types.js\";\nimport { extractTreeClaims } from \"./tree.js\";\n\n/**\n * Single-segment names that count as path claims without containing a \"/\".\n * Anything else without a slash is prose (\"name your file `config.ts`\"), not\n * a claim about this repo.\n */\nconst ROOT_FILE_NAMES = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-workspace.yaml\",\n \"tsconfig.json\",\n \"tsup.config.ts\",\n \"vitest.config.ts\",\n \"Makefile\",\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"go.sum\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"manifest.json\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\",\n \"CLAUDE.md\",\n \"AGENTS.md\",\n \".gitignore\",\n \".env.example\",\n]);\n\nconst SHELL_FENCE_INFOS = new Set([\"\", \"bash\", \"sh\", \"shell\", \"console\", \"zsh\"]);\n\nconst COMMAND_RE = /\\b(npm|pnpm|yarn)\\s+run\\s+([A-Za-z0-9:_.-]+)/g;\nconst COUNT_RE = /(\\d+)\\s+(modules?|packages?|workspaces?|crates?)\\b/gi;\n/** \"3 package managers\" is not a package count. */\nconst COUNT_DENYLIST_RE = /^\\s*(manager|registr|lock|json)/i;\n\nconst IGNORE_LINE = \"<!-- mason:ignore -->\";\nconst IGNORE_START = \"<!-- mason:ignore-start -->\";\nconst IGNORE_END = \"<!-- mason:ignore-end -->\";\n\n/**\n * Normalize a candidate token into a repo-relative path claim, or return\n * null when the token is not a claim about this repo (URL, glob,\n * placeholder, relative import example, bare word).\n */\nexport function normalizePathToken(token: string): string | null {\n let t = token.trim();\n if (!t) return null;\n if (/\\s/.test(t)) return null;\n if (t.includes(\"://\") || t.includes(\"\\\\\")) return null;\n if (/[*?[\\]{}<>$`]/.test(t)) return null;\n if (t.startsWith(\"/\") || t.startsWith(\"~\") || t.startsWith(\"./\") || t.startsWith(\"../\")) {\n return null;\n }\n // `src/mcp/tools.ts:189` claims the file, not the line.\n t = t.replace(/:\\d+(?:-\\d+)?$/, \"\");\n if (t.includes(\":\")) return null;\n const normalized = t.replace(/\\/+$/, \"\");\n if (!normalized) return null;\n // `server/src/test/kotlin/...` — a dots-only segment is an \"and so on\"\n // placeholder, not a claim.\n if (normalized.split(\"/\").some((seg) => /^\\.+$/.test(seg))) return null;\n if (normalized.includes(\"/\")) return normalized;\n return ROOT_FILE_NAMES.has(normalized) ? normalized : null;\n}\n\n/** A fence line that is exactly one path-shaped token is a file-list claim. */\nfunction exactTokenPath(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed || /\\s/.test(trimmed) || !trimmed.includes(\"/\")) return null;\n return normalizePathToken(trimmed);\n}\n\nfunction computeIgnoredLines(lines: string[]): boolean[] {\n const ignored = new Array<boolean>(lines.length).fill(false);\n let inRegion = false;\n let ignoreNext = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.includes(IGNORE_START)) {\n inRegion = true;\n ignored[i] = true;\n continue;\n }\n if (line.includes(IGNORE_END)) {\n inRegion = false;\n ignored[i] = true;\n continue;\n }\n if (inRegion) {\n ignored[i] = true;\n continue;\n }\n if (ignoreNext) {\n if (line.trim().length === 0) continue; // skip blanks to the next real line\n ignored[i] = true;\n ignoreNext = false;\n continue;\n }\n if (line.includes(IGNORE_LINE)) {\n ignored[i] = true;\n const rest = line.replace(IGNORE_LINE, \"\").trim();\n if (rest.length === 0) ignoreNext = true;\n }\n }\n return ignored;\n}\n\n/**\n * Extract every checkable claim from a context-file's markdown. Deterministic\n * and purely lexical — precision comes from the checks' provability gates,\n * not from clever parsing here.\n */\nexport function extractClaims(content: string): DocClaims {\n const lines = content.split(\"\\n\");\n const ignored = computeIgnoredLines(lines);\n\n const paths = new Map<string, PathClaim>();\n const counts: CountClaim[] = [];\n const commands = new Map<string, CommandClaim>();\n\n const addPath = (claim: PathClaim): void => {\n if (!paths.has(claim.path)) paths.set(claim.path, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n if (!commands.has(claim.scriptName)) commands.set(claim.scriptName, claim);\n };\n\n let inFence = false;\n let fenceInfo = \"\";\n let fenceMarker = \"\";\n let blockLines: string[] = [];\n let blockStartLine = 0;\n\n const processBlock = (): void => {\n for (const claim of extractTreeClaims(blockLines, blockStartLine)) {\n addPath(claim);\n }\n for (let i = 0; i < blockLines.length; i++) {\n const exact = exactTokenPath(blockLines[i]);\n if (exact) {\n addPath({\n path: exact,\n line: blockStartLine + i,\n excerpt: blockLines[i].trim(),\n });\n }\n }\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNo = i + 1;\n const fenceMatch = line.match(/^\\s*(```+|~~~+)(.*)$/);\n\n if (fenceMatch) {\n if (!inFence) {\n inFence = true;\n fenceMarker = fenceMatch[1][0];\n fenceInfo = fenceMatch[2].trim().toLowerCase();\n blockLines = [];\n blockStartLine = lineNo + 1;\n } else if (fenceMatch[1][0] === fenceMarker) {\n inFence = false;\n processBlock();\n }\n continue;\n }\n\n if (inFence) {\n // Ignored lines become spacers so the rest of a tree still parses.\n blockLines.push(ignored[i] ? \"\" : line);\n if (!ignored[i] && SHELL_FENCE_INFOS.has(fenceInfo)) {\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n continue;\n }\n\n if (ignored[i]) continue;\n\n for (const m of line.matchAll(/`([^`]+)`/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(/\"([A-Za-z][\\w.@-]*(?:\\/[\\w.@-]+)+\\/?)\"/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(COUNT_RE)) {\n const rest = line.slice((m.index ?? 0) + m[0].length);\n if (COUNT_DENYLIST_RE.test(rest)) continue;\n counts.push({\n count: Number.parseInt(m[1], 10),\n unit: m[2].toLowerCase(),\n line: lineNo,\n excerpt: m[0],\n });\n }\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n\n // An unclosed fence still gets its block processed — trees at the end of a\n // truncated doc are claims too.\n if (inFence) processBlock();\n\n return {\n paths: [...paths.values()],\n counts,\n commands: [...commands.values()],\n };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CommitRef } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\nconst COMMIT_FORMAT = \"%H%x09%cI%x09%s\";\n\nfunction parseCommitLine(line: string): CommitRef | null {\n const parts = line.split(\"\\t\");\n if (parts.length < 3 || !parts[0]) return null;\n return { hash: parts[0], date: parts[1], subject: parts.slice(2).join(\"\\t\") };\n}\n\n/** Most recent commit touching a path, or null if the path was never tracked. */\nexport async function lastCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** The commit that deleted a path, or null if none did. */\nexport async function deletingCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n relPath,\n ],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** Oldest commit touching a path (used to date a directory's appearance). */\nexport async function firstCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\nexport interface RangeCommits {\n commits: Array<CommitRef & { files: string[] }>;\n total: number;\n}\n\n/**\n * Commits in fromHash..HEAD touching any of the pathspecs, newest first, with\n * the touched files per commit. Rev-range, not --since: immune to rebase date\n * skew and CI checkout mtimes. Returns null when the range is uncomputable\n * (unreachable base commit, shallow clone, no git).\n */\nexport async function commitsTouchingSince(\n resolvedRoot: string,\n fromHash: string,\n pathspecs: string[]\n): Promise<RangeCommits | null> {\n if (!fromHash || fromHash === \"unknown\") return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `${fromHash}..HEAD`,\n `--format=%x01${COMMIT_FORMAT}`,\n \"--name-only\",\n \"--\",\n ...pathspecs,\n ],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n\n const commits: Array<CommitRef & { files: string[] }> = [];\n // \\x01 marks each commit header so name-only file lists can't be\n // mistaken for headers.\n for (const block of stdout.split(\"\\x01\")) {\n if (!block.trim()) continue;\n const lines = block.split(\"\\n\").filter((l) => l.trim().length > 0);\n const ref = parseCommitLine(lines[0]);\n if (!ref) continue;\n commits.push({ ...ref, files: lines.slice(1).map((l) => l.trim()) });\n }\n return { commits, total: commits.length };\n } catch {\n return null;\n }\n}\n","import type { decisionProvenance } from \"../decisions/provenance.js\";\n\nexport type IssueType =\n | \"deleted-reference\"\n | \"new-module\"\n | \"stale-count\"\n | \"dead-command\";\n\nexport type AdvisoryType = \"deps-changed\" | \"decision-anchor-drift\";\n\nexport type CheckName = IssueType | AdvisoryType;\n\nexport const ALL_CHECKS: CheckName[] = [\n \"deleted-reference\",\n \"new-module\",\n \"stale-count\",\n \"dead-command\",\n \"deps-changed\",\n \"decision-anchor-drift\",\n];\n\n/**\n * \"certain\" — the claim is provably false (a tracked path is gone, a computed\n * count differs, a script exists in no manifest). \"likely\" — evidence-backed\n * but heuristic (an unmentioned directory; a never-tracked path whose parent\n * exists). Certain-class issues are safe to auto-fix; likely-class issues\n * deserve a look.\n */\nexport type Confidence = \"certain\" | \"likely\";\n\nexport interface CommitRef {\n hash: string;\n date: string;\n subject: string;\n}\n\nexport interface DocAnchor {\n /** Repo-relative doc path, e.g. \"CLAUDE.md\" or \".claude/CLAUDE.md\". */\n doc: string;\n /** 1-based line of the claim; null for doc-level issues (new-module). */\n line: number | null;\n /** The claim exactly as written, e.g. \"src/utils/logger.ts\". */\n excerpt: string | null;\n}\n\nexport type Evidence =\n | {\n kind: \"missing-path\";\n claimed: string;\n renamedTo: string | null;\n deletedInCommit: CommitRef | null;\n everTracked: boolean;\n parentDirExists: boolean;\n }\n | {\n kind: \"unmentioned-dir\";\n dir: string;\n sourceFileCount: number;\n firstCommit: CommitRef | null;\n checkedDocs: string[];\n }\n | {\n kind: \"count-mismatch\";\n claimed: number;\n actual: number;\n unit: string;\n /** Where the actual count came from, e.g. \"package.json workspaces\". */\n countedFrom: string;\n members: string[];\n }\n | {\n kind: \"missing-script\";\n scriptName: string;\n invocation: string;\n manifestsChecked: string[];\n availableScripts: string[];\n }\n | {\n kind: \"doc-behind-manifests\";\n docLastCommit: CommitRef;\n manifestCommits: Array<CommitRef & { files: string[] }>;\n totalCommits: number;\n }\n | {\n kind: \"decision-anchor\";\n provenance?: ReturnType<typeof decisionProvenance>;\n decisionId: string;\n title: string;\n changedFiles: string[];\n refreshedHash: string;\n };\n\nexport interface AuditIssue {\n type: IssueType;\n message: string;\n anchor: DocAnchor;\n confidence: Confidence;\n evidence: Evidence;\n}\n\n/**\n * Advisories are facts the fixing agent cannot close by editing the doc (a\n * manifest commit after the doc's commit stays true forever; decision records\n * must be re-verified by humans). They NEVER affect the exit code — same\n * precedent as decision staleness in mason-drift.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n}\n\nexport interface AuditDocInfo {\n path: string;\n lastCommit: CommitRef | null;\n /** Uncommitted edits present — deps-changed is suppressed for dirty docs. */\n dirty: boolean;\n lineCount: number;\n}\n\nexport interface AuditReport {\n /** Additive-only schema — this output is a CI contract. */\n version: 1;\n root: string;\n gitAvailable: boolean;\n /** Commit and exact check scope used by this run. */\n headHash?: string;\n checksRun?: CheckName[];\n docs: AuditDocInfo[];\n /** Whether .mason/decisions/ existed and was checked. */\n decisionsChecked: boolean;\n /** Drive exit code 1. */\n issues: AuditIssue[];\n /** Never drive the exit code. */\n advisories: AuditAdvisory[];\n /** Original committed evidence retained while local doc edits suppress reporting. */\n suppressedAdvisories?: AuditAdvisory[];\n skippedChecks: Array<{ check: string; reason: string; doc?: string }>;\n clean: boolean;\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CountClaim {\n count: number;\n unit: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CommandClaim {\n scriptName: string;\n invocation: string;\n line: number;\n excerpt: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport type { AuditIssue } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nasync function exists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A claimed path that is missing on disk is only flagged when the repo can\n * prove it was ever real: a rename since the doc's last commit, or git\n * history for the path, or at least an existing parent directory. Paths with\n * none of those are illustrative examples and are dropped silently.\n */\nexport async function checkDeletedReferences(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map<string, string>();\n for (const change of changes ?? []) {\n if (change.status === \"renamed\" && change.previousPath) {\n renames.set(change.previousPath, change.path);\n }\n }\n\n for (const claim of doc.claims.paths) {\n // Mason's own metadata is optional state, not repo structure — docs\n // legitimately describe .mason/ files that a given repo doesn't have.\n if (claim.path === \".mason\" || claim.path.startsWith(\".mason/\")) {\n continue;\n }\n if (await exists(path.join(ctx.root, claim.path))) continue;\n\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const renamedTo = renames.get(claim.path) ?? null;\n\n if (renamedTo) {\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` was renamed to \\`${renamedTo}\\``,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo,\n deletedInCommit: null,\n everTracked: true,\n parentDirExists: true,\n },\n });\n continue;\n }\n\n const tracked = await lastCommitOf(ctx.root, claim.path);\n if (tracked) {\n const deleted = await deletingCommitOf(ctx.root, claim.path);\n const detail = deleted\n ? ` – deleted in ${deleted.hash.slice(0, 7)} \"${deleted.subject}\" (${deleted.date.slice(0, 10)})`\n : \"\";\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` no longer exists${detail}`,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: deleted,\n everTracked: true,\n parentDirExists: await exists(\n path.join(ctx.root, path.dirname(claim.path))\n ),\n },\n });\n continue;\n }\n\n const parentDirExists = await exists(\n path.join(ctx.root, path.dirname(claim.path))\n );\n if (!parentDirExists) continue;\n\n const issue: AuditIssue = {\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` does not exist (never tracked in git – possible typo or invented path)`,\n anchor,\n confidence: \"likely\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: null,\n everTracked: false,\n parentDirExists: true,\n },\n };\n result.issues.push(issue);\n }\n }\n\n return result;\n}\n","import fg from \"fast-glob\";\nimport path from \"node:path\";\nimport { SOURCE_GLOB, SOURCE_IGNORE } from \"../../snapshot/snapshot.js\";\nimport { firstCommitOf } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Directories that are never \"modules\" worth documenting. */\nconst DIR_DENYLIST = new Set([\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \"coverage\",\n \"target\",\n \"vendor\",\n \"__pycache__\",\n \"venv\",\n \".venv\",\n \".git\",\n \".gradle\",\n \".mason\",\n \".claude\",\n \".github\",\n \".vscode\",\n \".idea\",\n]);\n\n/** Second-level dirs need a bit more substance before they count. */\nconst SECOND_LEVEL_MIN_SOURCE_FILES = 2;\n/**\n * Descend into a top-level dir only when the docs evidently enumerate its\n * children — at least this many of its subdirs already mentioned.\n */\nconst ENUMERATION_THRESHOLD = 2;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Word-boundary mention check across the union of all docs — `app` must not\n * match \"application\", and a dir mentioned only in AGENTS.md must not be\n * flagged against CLAUDE.md.\n */\nfunction isMentioned(combinedDocs: string, name: string): boolean {\n const re = new RegExp(\n `(^|[^A-Za-z0-9_-])${escapeRegExp(name)}(/|[^A-Za-z0-9_-]|$)`,\n \"im\"\n );\n return re.test(combinedDocs);\n}\n\nasync function listSubdirs(absDir: string): Promise<string[]> {\n const dirs = await fg(\"*\", {\n cwd: absDir,\n onlyDirectories: true,\n suppressErrors: true,\n });\n return dirs.filter((d) => !DIR_DENYLIST.has(d)).sort();\n}\n\nasync function countSourceFiles(absDir: string): Promise<number> {\n const files = await fg(SOURCE_GLOB, {\n cwd: absDir,\n ignore: SOURCE_IGNORE,\n suppressErrors: true,\n });\n return files.length;\n}\n\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = ctx.docs.map((d) => d.content).join(\"\\n\");\n const primaryDoc = ctx.docs[0].path;\n const checkedDocs = ctx.docs.map((d) => d.path);\n\n const flag = async (dir: string, sourceFileCount: number): Promise<void> => {\n result.issues.push({\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in any context file`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\n confidence: \"likely\",\n evidence: {\n kind: \"unmentioned-dir\",\n dir,\n sourceFileCount,\n firstCommit: await firstCommitOf(ctx.root, dir),\n checkedDocs,\n },\n });\n };\n\n for (const topDir of await listSubdirs(ctx.root)) {\n const absTop = path.join(ctx.root, topDir);\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(absTop);\n if (count >= 1) await flag(topDir, count);\n continue;\n }\n\n // The docs know this dir. If they enumerate its children (several\n // subdirs already mentioned), an unmentioned sibling is drift — this is\n // how a freshly added module under src/ gets caught.\n const subdirs = await listSubdirs(absTop);\n const mentioned = subdirs.filter((s) => isMentioned(combinedDocs, s));\n if (mentioned.length < ENUMERATION_THRESHOLD) continue;\n\n for (const sub of subdirs) {\n if (isMentioned(combinedDocs, sub)) continue;\n const count = await countSourceFiles(path.join(absTop, sub));\n if (count >= SECOND_LEVEL_MIN_SOURCE_FILES) {\n await flag(`${topDir}/${sub}`, count);\n }\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CountClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MEMBERS_CAP = 50;\n\ninterface CountSource {\n actual: number;\n countedFrom: string;\n members: string[];\n}\n\nasync function readIfExists(absPath: string): Promise<string | null> {\n try {\n return await fs.readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readIfExists(path.join(root, name));\n if (content === null) continue;\n // include(\":a\", \":b\") — count quoted project strings, not include() calls.\n const members: string[] = [];\n for (const call of content.matchAll(/include\\s*\\(([^)]*)\\)/g)) {\n for (const proj of call[1].matchAll(/[\"']([^\"']+)[\"']/g)) {\n members.push(proj[1]);\n }\n }\n if (members.length === 0) return null;\n return { actual: members.length, countedFrom: name, members };\n }\n return null;\n}\n\nasync function countNpmWorkspaces(root: string): Promise<CountSource | null> {\n const pkgRaw = await readIfExists(path.join(root, \"package.json\"));\n if (pkgRaw !== null) {\n try {\n const pkg = JSON.parse(pkgRaw);\n const globs: string[] = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n } catch {\n // Malformed package.json — nothing provable here.\n }\n }\n\n const pnpmRaw = await readIfExists(path.join(root, \"pnpm-workspace.yaml\"));\n if (pnpmRaw !== null) {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of pnpmRaw.split(\"\\n\")) {\n if (/^packages\\s*:/.test(line)) {\n inPackages = true;\n continue;\n }\n if (inPackages) {\n const entry = line.match(/^\\s*-\\s*[\"']?([^\"'#\\s]+)/);\n if (entry) {\n if (!entry[1].startsWith(\"!\")) globs.push(entry[1]);\n } else if (line.trim().length > 0 && !line.startsWith(\" \")) {\n inPackages = false;\n }\n }\n }\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"pnpm-workspace.yaml\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n return null;\n}\n\nasync function countCargoCrates(root: string): Promise<CountSource | null> {\n const content = await readIfExists(path.join(root, \"Cargo.toml\"));\n if (content === null) return null;\n const membersBlock = content.match(/members\\s*=\\s*\\[([\\s\\S]*?)\\]/);\n if (!membersBlock) return null;\n const entries = [...membersBlock[1].matchAll(/[\"']([^\"']+)[\"']/g)].map(\n (m) => m[1]\n );\n if (entries.length === 0) return null;\n\n // Workspace members may be globs (\"crates/*\") — resolve them against\n // directories that actually contain a Cargo.toml.\n const members = new Set<string>();\n for (const entry of entries) {\n if (/[*?[\\]{}]/.test(entry)) {\n const matched = await fg(`${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n cwd: root,\n ignore: [\"**/target/**\"],\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readIfExists(path.join(root, entry, \"Cargo.toml\"))) !== null\n ) {\n members.add(entry);\n }\n }\n if (members.size === 0) return null;\n return {\n actual: members.size,\n countedFrom: \"Cargo.toml workspace members\",\n members: [...members].sort(),\n };\n}\n\n/**\n * Map a claim's unit to the ecosystem that can prove it. When the mapped\n * ecosystem has no workspace manifest in this repo, the claim is skipped —\n * \"12 packages\" in a Gradle repo proves nothing either way.\n */\nasync function resolveCountSource(\n root: string,\n claim: CountClaim\n): Promise<CountSource | null> {\n const unit = claim.unit.replace(/s$/, \"\");\n if (unit === \"module\") return countGradleModules(root);\n if (unit === \"workspace\") return countNpmWorkspaces(root);\n if (unit === \"crate\") return countCargoCrates(root);\n // \"packages\" is ecosystem-ambiguous — first manifest that resolves wins.\n return (\n (await countNpmWorkspaces(root)) ??\n (await countCargoCrates(root)) ??\n (await countGradleModules(root))\n );\n}\n\nexport async function checkStaleCounts(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n for (const claim of doc.claims.counts) {\n const source = await resolveCountSource(ctx.root, claim);\n if (source === null) {\n result.skipped.push({ check: \"stale-count\", doc: doc.path,\n reason: `${doc.path}: cannot resolve a workspace manifest for \"${claim.excerpt}\"` });\n continue;\n }\n if (source.actual === claim.count) continue;\n result.issues.push({\n type: \"stale-count\",\n message: `says \"${claim.excerpt}\" but ${source.countedFrom} resolves to ${source.actual}`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"count-mismatch\",\n claimed: claim.count,\n actual: source.actual,\n unit: claim.unit,\n countedFrom: source.countedFrom,\n members: source.members.slice(0, MEMBERS_CAP),\n },\n });\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\n\nasync function scriptsOf(absManifest: string): Promise<string[] | null> {\n try {\n const pkg = JSON.parse(await fs.readFile(absManifest, \"utf-8\"));\n return pkg && typeof pkg.scripts === \"object\" && pkg.scripts !== null\n ? Object.keys(pkg.scripts)\n : [];\n } catch {\n return null;\n }\n}\n\n/**\n * `npm run <script>` claims checked against package.json scripts — the one\n * ecosystem where task discovery is a single JSON parse. A script missing\n * from the root manifest is searched in every workspace manifest before\n * being flagged; docs legitimately say \"in packages/foo run `npm run build`\".\n */\nexport async function checkDeadCommands(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n const commandClaims = ctx.docs.flatMap((doc) =>\n doc.claims.commands.map((claim) => ({ doc, claim }))\n );\n if (commandClaims.length === 0) return result;\n\n const rootScripts = await scriptsOf(path.join(ctx.root, \"package.json\"));\n if (rootScripts === null) {\n result.skipped.push({\n check: \"dead-command\",\n reason: \"no package.json at the repo root\",\n });\n return result;\n }\n const rootSet = new Set(rootScripts);\n\n let workspaceScripts: Set<string> | null = null;\n let manifestsChecked: string[] = [\"package.json\"];\n const loadWorkspaceScripts = async (): Promise<Set<string>> => {\n if (workspaceScripts !== null) return workspaceScripts;\n workspaceScripts = new Set<string>();\n const manifests = await fg(\"**/package.json\", {\n cwd: ctx.root,\n ignore: [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"package.json\",\n ],\n });\n manifestsChecked = [\"package.json\", ...manifests.sort()];\n for (const manifest of manifests) {\n const scripts = await scriptsOf(path.join(ctx.root, manifest));\n for (const name of scripts ?? []) workspaceScripts.add(name);\n }\n return workspaceScripts;\n };\n\n for (const { doc, claim } of commandClaims) {\n if (rootSet.has(claim.scriptName)) continue;\n const elsewhere = await loadWorkspaceScripts();\n if (elsewhere.has(claim.scriptName)) continue;\n\n result.issues.push({\n type: \"dead-command\",\n message: `\\`${claim.invocation}\\` refers to script \"${claim.scriptName}\", which exists in no package.json`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"missing-script\",\n scriptName: claim.scriptName,\n invocation: claim.invocation,\n manifestsChecked,\n availableScripts: rootScripts.slice(0, AVAILABLE_SCRIPTS_CAP),\n },\n });\n }\n\n return result;\n}\n","import { commitsTouchingSince } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MANIFEST_COMMITS_CAP = 10;\n\n/**\n * Tracked manifest files at any depth. Lockfiles are pure churn and are\n * deliberately not matched.\n */\nconst MANIFEST_PATHSPECS = [\n \":(glob)**/package.json\",\n \":(glob)**/build.gradle.kts\",\n \":(glob)**/build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \":(glob)**/Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n];\n\n/**\n * Advisory, never an issue: a manifest commit after the doc's last commit\n * proves recency ordering, not that any specific claim is false — and it can\n * never be closed by editing the doc within the same run.\n */\nexport async function checkDepsChanged(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n result.suppressedAdvisories = [];\n\n for (const doc of ctx.docs) {\n if (!doc.lastCommit) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has no commit history`,\n });\n continue;\n }\n if (doc.dirty) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has uncommitted edits – suppressed while in flight`,\n });\n }\n\n const range = await commitsTouchingSince(\n ctx.root,\n doc.lastCommit.hash,\n MANIFEST_PATHSPECS\n );\n if (range === null) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path}: commit range unreachable (shallow clone?)`,\n });\n continue;\n }\n if (range.total === 0) continue;\n\n const latest = range.commits[0];\n (doc.dirty ? result.suppressedAdvisories : result.advisories).push({\n type: \"deps-changed\",\n message: `dependency manifests touched by ${range.total} commit${range.total === 1 ? \"\" : \"s\"} since ${doc.path} was last committed (latest: ${latest.hash.slice(0, 7)} \"${latest.subject}\")`,\n anchor: { doc: doc.path, line: null, excerpt: null },\n evidence: {\n kind: \"doc-behind-manifests\",\n docLastCommit: doc.lastCommit,\n manifestCommits: range.commits.slice(0, MANIFEST_COMMITS_CAP),\n totalCommits: range.total,\n },\n });\n }\n\n return result;\n}\n","import path from \"node:path\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { loadDecisionStore } from \"./decisions.js\";\nimport type { DecisionRecord } from \"./decisions.js\";\nimport { effectiveDecision } from \"./provenance.js\";\n\n/**\n * Deliberately separate from DriftReport: mason-drift's exit codes and\n * --json shape are a CI contract, and `stale` there means MAP staleness.\n * Decision staleness is additive on top.\n */\nexport interface DecisionDriftReport {\n historyAvailable: boolean;\n freshness?: Record<string, Freshness>;\n diagnostics?: StoreDiagnostic[];\n totalDecisions: number;\n /** Decision id → anchor files changed since the record's refreshedHash. */\n staleDecisions: Record<string, string[]>;\n /** Draft anchors have their own freshness; they cannot replace accepted anchors. */\n pendingProposals?: Record<string, { freshness: Freshness; changedFiles: string[] }>;\n}\n\n/**\n * Flag active decisions whose anchor files changed since the record was\n * last verified. Anchorless decisions have unknown freshness and do not\n * contribute to committed drift.\n * Deterministic — git only, no LLM.\n */\nexport async function computeDecisionDrift(\n rootDir: string,\n decisions?: DecisionRecord[]\n): Promise<DecisionDriftReport> {\n const resolvedRoot = path.resolve(rootDir);\n const store = decisions ? { records: decisions, diagnostics: [] } : await loadDecisionStore(resolvedRoot);\n const report: DecisionDriftReport = { historyAvailable: true, totalDecisions: store.records.length, staleDecisions: {}, freshness: {}, diagnostics: store.diagnostics };\n const [head, workingTree] = await Promise.all([getCurrentGitHash(resolvedRoot), getWorkingTree(resolvedRoot)]);\n const changesByHash = new Map<string, string[] | null>();\n const inspect = async (record: DecisionRecord): Promise<{ freshness: Freshness; changedFiles: string[] }> => {\n if (record.files.length === 0) return { freshness: \"unknown\", changedFiles: [] };\n let touched = changesByHash.get(record.refreshedHash);\n if (touched === undefined) {\n const changes = record.refreshedHash === head && head !== \"unknown\" ? [] : await getChangesWithStatus(resolvedRoot, record.refreshedHash);\n touched = changes === null ? null : touchedPaths(changes);\n changesByHash.set(record.refreshedHash, touched);\n }\n if (touched === null) report.historyAvailable = false;\n const hits = touched ? matchingPaths(record.files, touched) : [];\n const localHits = matchingPaths(record.files, workingTree.changedFiles);\n return { freshness: touched === null || !workingTree.available ? \"unknown\" : hits.length || localHits.length ? \"changed\" : \"current\", changedFiles: hits };\n };\n for (const record of store.records) {\n if (record.status !== \"active\") continue;\n const effective = effectiveDecision(record);\n const state = await inspect(effective);\n report.freshness![record.id] = state.freshness;\n if (state.changedFiles.length) report.staleDecisions[record.id] = state.changedFiles;\n if (effective !== record) (report.pendingProposals ??= {})[record.id] = await inspect(record);\n }\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { readStoreJson, writeStoreJson, storePath, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { jaccard, tokenSet } from \"../context/lexical.js\";\nimport { attributionSchema, decisionSchema, decisionContent, decisionApproval, effectiveDecision, importLegacy, type DecisionSource, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nexport type { DecisionRecord } from \"./provenance.js\";\n\nexport type DecisionCategory =\n | \"decision\"\n | \"gotcha\"\n | \"deprecation\"\n | \"convention\";\nexport type DecisionStatus = \"active\" | \"superseded\" | \"retired\";\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\nexport async function loadDecisionStore(rootDir: string): Promise<{ records: DecisionRecord[]; diagnostics: StoreDiagnostic[] }> {\n const records: DecisionRecord[] = [];\n const diagnostics: StoreDiagnostic[] = [];\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, \".mason/decisions\")); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") diagnostics.push({ path: \".mason/decisions\", message: String(error) });\n return { records, diagnostics };\n }\n for (const entry of entries.sort()) {\n if (!entry.endsWith(\".json\")) continue;\n const relative = `.mason/decisions/${entry}`;\n try {\n const record = decisionSchema.parse(await readStoreJson(rootDir, relative));\n if (entry !== `${record.id}.json`) throw new Error(\"Record id does not match its filename\");\n records.push(record);\n } catch (error) { diagnostics.push({ path: relative, message: error instanceof Error ? error.message : String(error) }); }\n }\n return { records, diagnostics };\n}\n\nexport async function loadDecisions(rootDir: string): Promise<DecisionRecord[]> {\n return (await loadDecisionStore(rootDir)).records;\n}\n\nexport async function saveDecisionRecord(rootDir: string, record: DecisionRecord): Promise<void> {\n const validated = decisionSchema.parse(record);\n await writeStoreJson(rootDir, `.mason/decisions/${validated.id}.json`, validated);\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\nexport interface UpsertDecisionInput {\n title: string;\n body: string;\n category: DecisionCategory;\n files?: string[];\n owner?: string | null;\n sources?: DecisionSource[];\n /** Only supply a known identity; never infer authorship from Git configuration. */\n actor?: string;\n /** Existing id to revise. Unchanged content is a no-op; use review_decision to reaffirm. */\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\" | \"unchanged\" | \"superseded_and_created\";\n id: string;\n totalActive: number;\n warnings: string[];\n approval?: \"unreviewed\" | \"proposed\" | \"accepted\";\n hint?: string;\n pruneCandidates?: string[];\n }\n | { status: \"duplicate_suspected\"; existing: DecisionRecord; hint: string }\n | { status: \"error\"; error: string };\n\n/** Serialize tool writes so prepared reviews cannot overwrite another decision edit. */\nexport async function withDecisionWrite<T>(root: string, operation: () => Promise<T>): Promise<T | { status: \"error\"; error: string }> {\n const lockPath = await storePath(root, \".mason/decisions/.write-lock\", true);\n let lock;\n try { lock = await fs.open(lockPath, \"wx\", 0o600); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return { status: \"error\", error: \"Decision store is locked by another write. Retry after it finishes; an abandoned .mason/decisions/.write-lock must be removed only after confirming no writer is running.\" };\n throw error;\n }\n try { return await operation(); }\n finally { await lock.close(); await fs.unlink(lockPath); }\n}\n\nexport async function upsertDecision(rootDir: string, input: UpsertDecisionInput): Promise<UpsertDecisionResult> {\n const title = input.title.trim(), body = input.body.trim();\n if (!title || !body) return { status: \"error\", error: \"title and body must be non-empty\" };\n if (title.length > TITLE_MAX_CHARS) return { status: \"error\", error: `title exceeds ${TITLE_MAX_CHARS} chars — tighten it to a specific headline` };\n if (body.length > BODY_MAX_CHARS) return { status: \"error\", error: `body exceeds ${BODY_MAX_CHARS} chars — record the decision, not the transcript` };\n const attribution = attributionSchema.safeParse(input);\n if (!attribution.success) return { status: \"error\", error: attribution.error.message };\n if (input.id && input.supersedes) return { status: \"error\", error: \"Use either id to revise or supersedes to replace a record, not both.\" };\n return withDecisionWrite(rootDir, async () => {\n const store = await loadDecisionStore(rootDir);\n if (store.diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before saving: \" + store.diagnostics.map(d => d.path).join(\", \") };\n const existing = store.records, byId = new Map(existing.map(r => [r.id, r]));\n const now = new Date().toISOString(), head = await getCurrentGitHash(rootDir);\n const warnings: string[] = [];\n const files = sanitizeRepoPaths(input.files ?? []);\n if (input.files && files.length < input.files.length) warnings.push(\"some anchor paths were outside the repo or duplicated and were dropped\");\n for (const file of files) {\n try { await fs.access(path.join(rootDir, file)); }\n catch { warnings.push(`anchor file does not exist on disk: ${file}`); }\n }\n const hint = \"Saved locally for review and commit. Proposals are not accepted constraints; an existing accepted revision remains operative while its replacement is proposed. Use review_decision to inspect evidence and record an authorized acceptance or reaffirmation.\";\n if (input.id) {\n const original = byId.get(input.id);\n if (!original) return { status: \"error\", error: `no decision with id \"${input.id}\"` };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived records cannot be revised; create a new proposal.\" };\n const record = importLegacy(original, now);\n const content = decisionContent({ ...record, title, body, category: input.category,\n files: input.files !== undefined ? files : record.files,\n owner: attribution.data.owner === undefined ? record.owner : attribution.data.owner ?? undefined,\n sources: attribution.data.sources ?? record.sources,\n });\n if (JSON.stringify(content) === JSON.stringify(decisionContent(record))) {\n return { status: \"unchanged\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: decisionApproval(original), warnings,\n hint: \"Unchanged content; no review or freshness stamp was written. Use review_decision for explicit re-verification.\" };\n }\n const revision = record.revision + 1;\n const updated: ReviewedDecisionRecord = { ...record, ...content, owner: content.owner, updatedAt: now, revision, approval: \"proposed\",\n history: [...record.history, { kind: \"revised\", at: now, actor: attribution.data.actor, revision, content, approval: \"proposed\", status: \"active\", refreshedHash: record.refreshedHash }],\n };\n await saveDecisionRecord(rootDir, updated);\n return { status: \"updated\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: \"proposed\", warnings, hint };\n }\n const old = input.supersedes ? byId.get(input.supersedes) : undefined;\n if (input.supersedes && !old) return { status: \"error\", error: `no decision with id \"${input.supersedes}\" to supersede` };\n if (old && (old.status !== \"active\" || decisionApproval(effectiveDecision(old)) === \"accepted\")) {\n return { status: \"error\", error: \"A proposal cannot supersede an accepted or archived record. Create and review the replacement separately, then explicitly retire the old decision with review_decision.\" };\n }\n if (!input.force) {\n const duplicate = findNearDuplicate({ title, body, files }, existing);\n if (duplicate) return { status: \"duplicate_suspected\", existing: duplicate.record, hint: `A similar decision exists (\"${duplicate.record.title}\"). Call save_decision with id=\"${duplicate.record.id}\" to revise it, or force:true if distinct.` };\n }\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n if (byId.has(id)) return { status: \"error\", error: `Decision id collision: ${id}. Choose a distinct title or revise the existing record.` };\n const content = decisionContent({ title, body, category: input.category, files, owner: attribution.data.owner ?? undefined, sources: attribution.data.sources ?? [] });\n const record: ReviewedDecisionRecord = { ...content, version: 2, id, createdAt: now, updatedAt: now, refreshedHash: head,\n status: \"active\", approval: \"proposed\", revision: 1,\n history: [{ kind: \"created\", at: now, actor: attribution.data.actor, revision: 1, content, approval: \"proposed\", status: \"active\", refreshedHash: head }],\n };\n // Write the replacement first: a failed second write leaves both records\n // available instead of removing the original before its replacement exists.\n await saveDecisionRecord(rootDir, record);\n if (old) {\n const imported = importLegacy(old, now);\n await saveDecisionRecord(rootDir, { ...imported, status: \"superseded\", supersededBy: id, updatedAt: now,\n history: [...imported.history, { kind: \"superseded\", at: now, actor: attribution.data.actor, note: `Replaced by proposal ${id}`,\n revision: imported.revision, content: decisionContent(imported), approval: imported.approval, status: \"superseded\", refreshedHash: imported.refreshedHash }],\n });\n }\n const totalActive = existing.filter(r => r.status === \"active\").length + (old ? 0 : 1);\n const result: UpsertDecisionResult = { status: old ? \"superseded_and_created\" : \"created\", id, totalActive, approval: \"proposed\", warnings, hint };\n if (totalActive > MAX_ACTIVE_DECISIONS) {\n result.pruneCandidates = existing.filter(r => r.status !== \"active\").map(r => r.id).slice(0, 10);\n warnings.push(`${totalActive} active decisions exceeds the soft cap of ${MAX_ACTIVE_DECISIONS} — consider a cleanup PR (archived records first)`);\n }\n return result;\n });\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 { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { assessTrust, type Freshness } from \"../context/trust.js\";\n\nconst text = (max: number) => z.string().trim().min(1).max(max);\nexport const decisionSourceSchema = z.object({\n kind: z.enum([\"pull_request\", \"issue\", \"incident\", \"discussion\", \"document\", \"other\"]),\n reference: text(1000),\n note: text(500).optional(),\n}).strict();\nexport type DecisionSource = z.infer<typeof decisionSourceSchema>;\nexport const attributionSchema = z.object({\n owner: text(200).nullable().optional(),\n sources: z.array(decisionSourceSchema).max(20).optional(),\n actor: text(200).optional(),\n});\nconst contentSchema = z.object({\n title: z.string().min(1), body: z.string().min(1),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z.array(z.string().refine(f => normalizeRepoPath(f) !== null)),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n});\nconst approvalSchema = z.enum([\"unreviewed\", \"proposed\", \"accepted\"]);\nconst statusSchema = z.enum([\"active\", \"superseded\", \"retired\"]);\nexport const reviewEvidenceSchema = z.object({\n baseHash: z.string(), headHash: z.string(), historyAvailable: z.boolean(),\n changedFiles: z.array(z.string()), localChanges: z.array(z.string()),\n});\nconst eventSchema = z.object({\n kind: z.enum([\"imported\", \"created\", \"revised\", \"accepted\", \"reaffirmed\", \"retired\", \"superseded\"]),\n at: z.string().datetime(), actor: text(200).optional(), note: text(1500).optional(),\n revision: z.number().int().positive(), content: contentSchema,\n approval: approvalSchema, status: statusSchema, refreshedHash: z.string(),\n evidence: reviewEvidenceSchema.optional(),\n});\nexport type DecisionEvent = z.infer<typeof eventSchema>;\nexport type DecisionApproval = z.infer<typeof approvalSchema>;\nexport type DecisionContent = z.infer<typeof contentSchema>;\n\nconst legacySchema = z.object({\n version: z.literal(1), id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n title: z.string().min(1), body: z.string().min(1),\n category: contentSchema.shape.category, files: contentSchema.shape.files,\n createdAt: z.string(), updatedAt: z.string(), refreshedHash: z.string(),\n status: z.enum([\"active\", \"superseded\"]), supersededBy: z.string().optional(),\n}).passthrough();\nconst currentSchema = legacySchema.extend({\n version: z.literal(2), status: statusSchema,\n approval: approvalSchema, revision: z.number().int().positive(),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n history: z.array(eventSchema).min(1),\n}).superRefine((record, ctx) => {\n const invalid = (message: string) => ctx.addIssue({ code: \"custom\", message });\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n let previous: DecisionEvent | undefined;\n for (const event of record.history) {\n if (!previous) {\n if (![\"created\", \"imported\"].includes(event.kind) || event.revision !== 1) invalid(\"History must begin with creation or legacy import at revision 1\");\n if (event.approval !== (event.kind === \"created\" ? \"proposed\" : \"unreviewed\")) invalid(\"Initial records cannot claim acceptance\");\n } else {\n if ([\"created\", \"imported\"].includes(event.kind)) invalid(\"History cannot restart\");\n if (previous.status !== \"active\") invalid(\"Archived decisions cannot be changed\");\n if (event.revision !== previous.revision + (event.kind === \"revised\" ? 1 : 0)) invalid(\"Invalid revision sequence\");\n if (event.kind !== \"revised\" && !same(event.content, previous.content)) invalid(\"A review cannot silently revise decision content\");\n if (event.kind === \"reaffirmed\" && previous.approval !== \"accepted\") invalid(\"Only accepted decisions can be reaffirmed\");\n if (event.kind === \"accepted\" && previous.approval === \"accepted\") invalid(\"Use reaffirmation for an accepted decision\");\n const approval = event.kind === \"revised\" ? \"proposed\" : [\"accepted\", \"reaffirmed\"].includes(event.kind) ? \"accepted\" : previous.approval;\n if (event.approval !== approval) invalid(\"Approval disagrees with review history\");\n if (![\"accepted\", \"reaffirmed\"].includes(event.kind) && event.refreshedHash !== previous.refreshedHash) invalid(\"Only a review can refresh the evidence baseline\");\n }\n if (event.kind !== \"imported\" && event.status !== (event.kind === \"retired\" ? \"retired\" : event.kind === \"superseded\" ? \"superseded\" : \"active\")) invalid(\"Lifecycle disagrees with history\");\n if ([\"accepted\", \"reaffirmed\", \"retired\"].includes(event.kind) && (!event.actor || !event.note || !event.evidence)) invalid(\"Reviews require a named reviewer, reason, and code evidence\");\n if ([\"accepted\", \"reaffirmed\"].includes(event.kind)) {\n if (!event.content.owner || !event.content.sources.length) invalid(\"Accepted decisions require an owner and source\");\n if (!event.evidence || !/^[a-f0-9]{40,64}$/.test(event.evidence.headHash) || event.refreshedHash !== event.evidence.headHash || event.evidence.localChanges.length) invalid(\"Acceptance requires a committed evidence baseline\");\n }\n previous = event;\n }\n if (!previous || !same(previous.content, decisionContent(record)) || previous.approval !== record.approval || previous.status !== record.status || previous.revision !== record.revision || previous.refreshedHash !== record.refreshedHash) invalid(\"Decision does not match the final history event\");\n});\n\nexport const decisionSchema = z.union([legacySchema, currentSchema]);\nexport type DecisionRecord = z.infer<typeof decisionSchema>;\nexport type ReviewedDecisionRecord = z.infer<typeof currentSchema>;\n\nexport function decisionContent(record: Pick<DecisionRecord, \"title\" | \"body\" | \"category\" | \"files\"> & { owner?: unknown; sources?: unknown }): DecisionContent {\n return { title: record.title, body: record.body, category: record.category, files: record.files,\n ...(typeof record.owner === \"string\" ? { owner: record.owner } : {}),\n sources: Array.isArray(record.sources) ? record.sources as DecisionSource[] : [],\n };\n}\n\n/** Reading legacy records never upgrades their approval or rewrites their files. */\nexport function decisionApproval(record: DecisionRecord): DecisionApproval {\n return record.version === 1 ? \"unreviewed\" : record.approval;\n}\n\n/** The last accepted revision remains operative while a replacement is drafted.\n * This is a read-only projection; writes and review tokens use the complete record.\n * Archived records never regain authority from their history.\n */\nexport function effectiveDecision(record: DecisionRecord): DecisionRecord {\n if (record.version !== 2 || record.status !== \"active\" || record.approval !== \"proposed\") return record;\n let index = record.history.length - 1;\n while (index >= 0 && ![\"accepted\", \"reaffirmed\"].includes(record.history[index].kind)) index--;\n if (index < 0) return record;\n const event = record.history[index];\n return { ...record, ...event.content, owner: event.content.owner, approval: \"accepted\", revision: event.revision,\n refreshedHash: event.refreshedHash, updatedAt: event.at, history: record.history.slice(0, index + 1) };\n}\n\n/** Anchors relevant to either the operative knowledge or its pending proposal. */\nexport function decisionAnchors(record: DecisionRecord): string[] {\n return [...new Set([...effectiveDecision(record).files, ...record.files])];\n}\n\nexport function importLegacy(record: DecisionRecord, now: string): ReviewedDecisionRecord {\n if (record.version === 2) return record;\n // Ignore unrecognized legacy fields: they are not evidence of authorship or approval.\n const content = decisionContent({ title: record.title, body: record.body, category: record.category, files: record.files });\n return { id: record.id, createdAt: record.createdAt, updatedAt: record.updatedAt, status: record.status, refreshedHash: record.refreshedHash, supersededBy: record.supersededBy, ...content, version: 2, approval: \"unreviewed\", revision: 1,\n history: [{ kind: \"imported\", at: now, revision: 1, content, approval: \"unreviewed\", status: record.status, refreshedHash: record.refreshedHash,\n note: \"Imported a legacy record. Prior authorship and review history are unknown.\" }],\n };\n}\n\nexport function decisionProvenance(record: DecisionRecord, freshness: Freshness = \"unknown\") {\n const approval = decisionApproval(record);\n const review = record.version === 2 ? [...record.history].reverse().find(e => [\"accepted\", \"reaffirmed\"].includes(e.kind) && e.revision === record.revision) : undefined;\n return {\n approval, revision: record.version === 2 ? record.revision : 0,\n owner: record.version === 2 ? record.owner ?? null : null,\n sources: record.version === 2 ? record.sources : [],\n guidance: record.status !== \"active\" ? \"historical\" : approval === \"accepted\" ? \"constraint\" : approval === \"proposed\" ? \"proposal\" : \"unreviewed\",\n reviewRequired: record.status === \"active\" && (approval !== \"accepted\" || freshness !== \"current\"),\n lastReview: review ? { reviewer: review.actor!, at: review.at, note: review.note!, gitHash: review.refreshedHash } : null,\n };\n}\n\nexport function decisionTrust(record: DecisionRecord, freshness: Freshness) {\n const review = decisionProvenance(record, freshness).lastReview;\n return assessTrust(review ? { verifiedAt: review.at, verifiedHash: review.gitHash } : {}, freshness);\n}\n\nfunction revisionKnowledge(record: DecisionRecord, freshness: Freshness) {\n return { ...decisionContent(record), ...decisionProvenance(record, freshness), trust: decisionTrust(record, freshness) };\n}\n\n/** Readers show accepted content first and label the unaccepted draft separately. */\nexport function decisionKnowledge(record: DecisionRecord, freshness: Freshness = \"unknown\", proposalFreshness: Freshness = \"unknown\") {\n const effective = effectiveDecision(record);\n return { ...revisionKnowledge(effective, freshness),\n ...(effective !== record ? { pendingProposal: revisionKnowledge(record, proposalFreshness) } : {}) };\n}\n\nexport function compactDecisionKnowledge(...args: Parameters<typeof decisionKnowledge>) {\n const { body, pendingProposal, ...summary } = decisionKnowledge(...args);\n if (!pendingProposal) return summary;\n const { body: proposalBody, ...proposal } = pendingProposal;\n return { ...summary, pendingProposal: proposal };\n}\n\nexport const DECISION_GUIDANCE = \"Accepted decisions are recorded team constraints, subject to freshness checks. A pendingProposal is an unaccepted replacement; the accepted revision remains operative until explicit acceptance or retirement. Proposals are suggestions; legacy unreviewed records need confirmation. Use review_decision to inspect provenance and record an authorized review; identities and sources are recorded assertions, not authenticated proof.\";\n","import { computeDecisionDrift } from \"../../decisions/drift.js\";\nimport { loadDecisionStore } from \"../../decisions/decisions.js\";\nimport { decisionProvenance, effectiveDecision } from \"../../decisions/provenance.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/**\n * Advisory only, and only when .mason/decisions/ exists (the zero-setup\n * path stays dark on bare repos). Decision records encode human knowledge —\n * they are surfaced for re-verification, never rewritten by the fix agent.\n */\nexport async function checkDecisionAnchors(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n if (!ctx.decisionsPresent) return result;\n\n const store = await loadDecisionStore(ctx.root);\n const records = store.records;\n for (const diagnostic of store.diagnostics) result.skipped.push({ check: \"decision-anchor-drift\", reason: `${diagnostic.path}: ${diagnostic.message}` });\n const drift = await computeDecisionDrift(ctx.root, records);\n if (!drift.historyAvailable) {\n result.skipped.push({\n check: \"decision-anchor-drift\",\n reason: \"some decision base commits are unreachable (shallow clone?)\",\n });\n }\n\n const changed = records.flatMap(record => [\n { record: effectiveDecision(record), changedFiles: drift.staleDecisions[record.id] ?? [], freshness: drift.freshness?.[record.id] ?? \"unknown\" },\n { record, changedFiles: drift.pendingProposals?.[record.id]?.changedFiles ?? [], freshness: drift.pendingProposals?.[record.id]?.freshness ?? \"unknown\" },\n ] as const);\n for (const { record, changedFiles, freshness } of changed) {\n if (!changedFiles.length) continue;\n const id = record.id;\n const provenance = decisionProvenance(record, freshness);\n result.advisories.push({\n type: \"decision-anchor-drift\",\n message: `decision \"${record.title}\" (${provenance.approval}) has anchor files that changed since its evidence baseline – needs human review`,\n anchor: {\n doc: `.mason/decisions/${id}.json`,\n line: null,\n excerpt: record.title,\n },\n evidence: {\n kind: \"decision-anchor\",\n provenance,\n decisionId: id,\n title: record.title,\n changedFiles,\n refreshedHash: record.refreshedHash,\n },\n });\n }\n\n return result;\n}\n","import type { FileChange } from \"../../drift/drift.js\";\nimport type { AuditAdvisory, AuditIssue, CheckName } from \"../types.js\";\nimport type { AuditDoc } from \"../docs.js\";\nimport { checkDeletedReferences } from \"./deleted-reference.js\";\nimport { checkNewModules } from \"./new-module.js\";\nimport { checkStaleCounts } from \"./stale-count.js\";\nimport { checkDeadCommands } from \"./dead-command.js\";\nimport { checkDepsChanged } from \"./deps-changed.js\";\nimport { checkDecisionAnchors } from \"./decision-anchor.js\";\n\nexport interface CheckContext {\n root: string;\n docs: AuditDoc[];\n headHash: string;\n /** Doc path → changes since the doc's last commit; null when uncomputable. */\n changesSinceDoc: Map<string, FileChange[] | null>;\n /** Whether .mason/decisions/ exists. */\n decisionsPresent: boolean;\n}\n\nexport interface CheckResult {\n issues: AuditIssue[];\n advisories: AuditAdvisory[];\n suppressedAdvisories?: AuditAdvisory[];\n skipped: Array<{ check: string; reason: string; doc?: string }>;\n}\n\nexport type CheckFn = (ctx: CheckContext) => Promise<CheckResult>;\n\nexport const CHECKS: Record<CheckName, CheckFn> = {\n \"deleted-reference\": checkDeletedReferences,\n \"new-module\": checkNewModules,\n \"stale-count\": checkStaleCounts,\n \"dead-command\": checkDeadCommands,\n \"deps-changed\": checkDepsChanged,\n \"decision-anchor-drift\": checkDecisionAnchors,\n};\n\nexport function emptyResult(): CheckResult {\n return { issues: [], advisories: [], skipped: [] };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit } from \"./audit.js\";\nimport { DOC_CANDIDATES } from \"./docs.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { isWithinRoot } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditAdvisory, AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nconst checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nconst commitSchema = z.object({ hash: z.string().regex(/^[a-f0-9]{40,64}$/), date: z.string(), subject: z.string() });\nconst anchorSchema = z.object({ doc: z.string(), line: z.number().int().positive().nullable(), excerpt: z.string().nullable() });\nconst count = z.number().int().nonnegative();\nconst evidenceSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"missing-path\"), claimed: z.string(), renamedTo: z.string().nullable(),\n deletedInCommit: commitSchema.nullable(), everTracked: z.boolean(), parentDirExists: z.boolean() }),\n z.object({ kind: z.literal(\"unmentioned-dir\"), dir: z.string(), sourceFileCount: count,\n firstCommit: commitSchema.nullable(), checkedDocs: z.array(z.string()) }),\n z.object({ kind: z.literal(\"count-mismatch\"), claimed: count, actual: count, unit: z.string(),\n countedFrom: z.string(), members: z.array(z.string()) }),\n z.object({ kind: z.literal(\"missing-script\"), scriptName: z.string(), invocation: z.string(),\n manifestsChecked: z.array(z.string()), availableScripts: z.array(z.string()) }),\n z.object({ kind: z.literal(\"doc-behind-manifests\"), docLastCommit: commitSchema,\n manifestCommits: z.array(commitSchema.extend({ files: z.array(z.string()) })), totalCommits: count }),\n z.object({ kind: z.literal(\"decision-anchor\"), decisionId: z.string(), title: z.string(),\n changedFiles: z.array(z.string()), refreshedHash: z.string(),\n provenance: z.object({}).passthrough().optional() }),\n]);\nconst findingSchema = z.object({ message: z.string(), anchor: anchorSchema, evidence: evidenceSchema });\nconst issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nconst advisorySchema = findingSchema.extend({ type: z.enum([\"deps-changed\", \"decision-anchor-drift\"]) });\nconst reportSchema = z.object({\n version: z.literal(1), root: z.string(), gitAvailable: z.literal(true),\n headHash: commitSchema.shape.hash, checksRun: z.array(checkSchema).nonempty(),\n docs: z.array(z.object({ path: z.enum(DOC_CANDIDATES), lastCommit: commitSchema.nullable(),\n dirty: z.boolean(), lineCount: count })).nonempty(),\n decisionsChecked: z.boolean(), clean: z.boolean(),\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skippedChecks: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst baselineSchema = z.object({\n kind: z.literal(\"mason-audit-repair\"), version: z.literal(1),\n createdAt: z.string().datetime(), report: reportSchema, digest: z.string().regex(/^[a-f0-9]{64}$/),\n});\nconst digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\ntype Finding = AuditIssue | AuditAdvisory;\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n}\nexport interface RepairVerification {\n version: 1;\n action: \"verify\";\n baselinePath: string;\n baselineHead: string;\n currentHead: string | null;\n status: \"verified\" | \"issues-remain\" | \"incomplete\";\n findings: RepairFinding[];\n newFindings: Finding[];\n diagnostics: string[];\n currentAudit: AuditReport | null;\n counts: Record<RepairStatus, number>;\n scope: string;\n}\n\n/** Lines and wording can change without changing the underlying claim. */\nfunction findingId(finding: Finding): string {\n const e = finding.evidence;\n let key: unknown;\n switch (e.kind) {\n case \"missing-path\": key = e.claimed; break;\n case \"unmentioned-dir\": key = e.dir; break;\n case \"count-mismatch\": key = [e.unit.replace(/s$/, \"\"), e.countedFrom]; break;\n case \"missing-script\": key = e.scriptName; break;\n case \"doc-behind-manifests\": key = null; break;\n case \"decision-anchor\": key = [e.decisionId, e.provenance?.revision, e.provenance?.approval]; break;\n }\n return digest([finding.type, finding.anchor.doc, key]);\n}\nfunction allFindings(report: AuditReport): Finding[] {\n return [...report.issues, ...report.advisories, ...(report.suppressedAdvisories ?? [])];\n}\n\nasync function docState(root: string): Promise<string> {\n const docs = [];\n for (const doc of DOC_CANDIDATES) {\n try {\n const content = await readBoundedFile(await storePath(root, doc), 10 * 1024 * 1024);\n if (content === null) throw new Error(\"Context file is not regular or exceeds 10 MiB: \" + doc);\n docs.push([doc, digest(content)]);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n docs.push([doc, null]);\n }\n }\n return digest(docs);\n}\n\n/** Refuse a verification assembled across a commit or instruction-file edit. */\nasync function stableAudit(root: string, checks: CheckName[]) {\n const head = await getCurrentGitHash(root);\n const before = await docState(root);\n const report = await computeAudit(root, { checks });\n if (head !== await getCurrentGitHash(root) || before !== await docState(root) ||\n (report && report.headHash !== head)) {\n throw new Error(\"HEAD or context files changed during the audit; retry against a stable checkout.\");\n }\n return report;\n}\n\nexport async function prepareRepair(rootDir: string, checks: CheckName[] = ALL_CHECKS) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await stableAudit(root, selected);\n if (!report) throw new Error(\"No context files found to prepare a repair.\");\n if (!report.gitAvailable) throw new Error(\"Readable Git history is required to prepare a repair.\");\n // Canonicalize before hashing; validation on read must yield the same bytes.\n const storedReport = reportSchema.parse(report);\n const payload = { kind: \"mason-audit-repair\" as const, version: 1 as const,\n createdAt: new Date().toISOString(), report: storedReport };\n const baselinePath = \".mason/reports/repairs/\" + randomUUID() + \".json\";\n await writeStoreJson(root, baselinePath, { ...payload, digest: digest(payload) });\n return { version: 1 as const, action: \"prepare\" as const, baselinePath, report };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string): Promise<RepairVerification> {\n const root = await fs.realpath(rootDir);\n const declaredRoot = path.resolve(rootDir);\n const relative = path.isAbsolute(baselinePath)\n ? path.relative(isWithinRoot(declaredRoot, baselinePath) ? declaredRoot : root, baselinePath)\n : baselinePath;\n const stored = baselineSchema.parse(await readStoreJson(root, relative));\n const { digest: savedDigest, ...payload } = stored;\n if (digest(payload) !== savedDigest) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n if (stored.report.root !== root) throw new Error(\"Repair baseline belongs to a different repository.\");\n const original = stored.report as AuditReport;\n const diagnostics: string[] = [];\n let current: AuditReport | null = null;\n try {\n current = await stableAudit(root, original.checksRun!);\n if (!current) diagnostics.push(\"No context files remain available to audit.\");\n else if (!current.gitAvailable) diagnostics.push(\"Git history is unavailable.\");\n for (const doc of original.docs) {\n if (!original.issues.some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await readBoundedFile(await storePath(root, doc.path), 10 * 1024 * 1024);\n if (content === null || !content.trim()) {\n diagnostics.push(\"Original context file \" + doc.path + \" is empty or unreadable; losing its claims does not verify a repair.\");\n }\n }\n if (await getChangesWithStatus(root, original.headHash!) === null) {\n diagnostics.push(\"The original audit commit is unavailable; repair history cannot be verified.\");\n }\n } catch (error) {\n diagnostics.push(error instanceof Error ? error.message : String(error));\n }\n const currentById = new Map((current ? allFindings(current) : []).map(f => [findingId(f), f]));\n const originalFindings = allFindings(original);\n const originalIds = new Set(originalFindings.map(findingId));\n const missingDocs = original.docs.filter(doc => !current?.docs.some(d => d.path === doc.path));\n for (const doc of missingDocs) diagnostics.push(\"Original context file \" + doc.path + \" is unavailable; removing it does not verify a repair.\");\n const findings = originalFindings.map((finding): RepairFinding => {\n const id = findingId(finding);\n const now = currentById.get(id);\n const base = { id, original: finding, ...(now ? { current: now } : {}) };\n if (diagnostics.length || !current) {\n return { ...base, status: \"unverified\", reason: \"The original audit scope could not be verified. See diagnostics.\" };\n }\n if (\"confidence\" in finding && now) {\n return { ...base, status: \"unresolved\", reason: \"The original check still reports this claim.\" };\n }\n const skipped = current.skippedChecks.filter(s => s.check === finding.type && (!s.doc || s.doc === finding.anchor.doc));\n if (!current.checksRun?.includes(finding.type) || skipped.length) {\n return { ...base, status: \"unverified\", reason: skipped.map(s => s.reason).join(\"; \") || \"The original check did not run.\" };\n }\n if (!(\"confidence\" in finding)) {\n return { ...base, status: \"review-required\",\n reason: \"An audit cannot establish that this advisory was reviewed. Retain its original evidence and report a separate assessment; editing or committing the doc is not approval.\" };\n }\n return { ...base, status: \"resolved\", reason: \"The original check ran and no longer reports this claim. Inspect the edit for semantic correctness.\" };\n });\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const counts: Record<RepairStatus, number> = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const f of findings) counts[f.status]++;\n const incomplete = diagnostics.length > 0 || counts.unverified > 0 || counts[\"review-required\"] > 0 ||\n (current?.skippedChecks.length ?? 0) > 0 || newFindings.some(f => !(\"confidence\" in f));\n const issuesRemain = counts.unresolved > 0 || newFindings.some(f => \"confidence\" in f);\n return {\n version: 1, action: \"verify\", baselinePath: relative, baselineHead: original.headHash!,\n currentHead: current?.gitAvailable ? current.headHash! : null,\n status: incomplete ? \"incomplete\" : issuesRemain ? \"issues-remain\" : \"verified\",\n findings, newFindings, diagnostics, currentAudit: current, counts,\n scope: \"Original audit checks over current context files and repository evidence. Resolved means no longer detected by that check. Advisories require separate review; this is not a certification of documentation or application correctness.\",\n };\n}\n\nexport function repairExitCode(report: RepairVerification): number {\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n}\n\nexport function formatRepairSummary(report: RepairVerification): string {\n return [\n \"Repair verification: \" + report.status + \". Baseline: \" + report.baselinePath,\n ...report.findings.map(f => \" [\" + f.status + \"] \" + f.original.type + \" \" + f.original.anchor.doc + \": \" + f.original.message + \"\\n \" + f.reason),\n ...report.newFindings.map(f => \" [new] \" + f.type + \" \" + f.anchor.doc + \": \" + f.message),\n ...report.diagnostics.map(d => \" [unverified] \" + d),\n ...(report.currentAudit?.skippedChecks ?? []).map(s => \" [skipped] \" + s.check + \": \" + s.reason),\n report.scope,\n ].join(\"\\n\");\n}\n","import { runAuditCli } from \"../src/audit/cli.js\";\n\nrunAuditCli(process.argv.slice(2)).then(\n (code) => process.exit(code),\n (err) => {\n process.stderr.write(`mason-audit error: ${err}\\n`);\n process.exit(2);\n }\n);\n"],"mappings":";;;AAAA,OAAOA,YAAU;;;ACAjB,OAAOC,SAAQ;AACf,OAAOC,YAAU;;;ACDjB,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACH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A,YAAY,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EACjC,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,QAAQ;AACP,YAAQ,OAAO,MAAM,sBAAsB,GAAG;AAAA,CAAI;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["path","fs","path","fs","path","execFile","promisify","path","execFile","promisify","path","fs","path","fs","path","path","exec","promisify","execFile","exec","exec","promisify","execFile","exec","fs","path","execFile","promisify","execFile","promisify","exec","exec","promisify","execFile","fs","path","fs","path","fs","path","fg","path","text","fg","path","count","fs","path","fg","fs","path","fg","fs","path","fg","fs","path","fg","path","fs","path","path","z","z","fs","path","path","fs","fs","path","createHash","randomUUID","z","z","createHash","fs","randomUUID","path","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/audit/cli.ts","../src/audit/audit.ts","../src/drift/drift.ts","../src/snapshot/snapshot.ts","../src/utils/files.ts","../src/utils/paths.ts","../src/utils/storage.ts","../src/test-map.ts","../src/audit/docs.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/audit/git.ts","../src/audit/types.ts","../src/audit/checks/deleted-reference.ts","../src/audit/checks/new-module.ts","../src/audit/checks/stale-count.ts","../src/audit/checks/dead-command.ts","../src/audit/release-metadata.ts","../src/audit/checks/deps-changed.ts","../src/decisions/drift.ts","../src/decisions/decisions.ts","../src/context/lexical.ts","../src/decisions/provenance.ts","../src/audit/checks/decision-anchor.ts","../src/audit/checks/index.ts","../src/audit/repair.ts","../bin/mason-audit.ts"],"sourcesContent":["import path from \"node:path\";\nimport { computeAudit } from \"./audit.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport { prepareRepair, verifyRepair, formatRepairSummary, repairExitCode } from \"./repair.js\";\nimport type { AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits the repo's AI context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\nagainst repo reality: referenced paths that no longer exist, undocumented\nmodules, stale counts, dead npm scripts, and manifests newer than the doc.\nDeterministic: no LLM call, no network – safe for CI. Works on any repo with\na context file; no Mason setup required.\n\nOptions:\n --dir <path> Project root to audit (default: current directory)\n --json Print the full audit report as JSON (additive-only schema)\n --fix-prompt When issues exist, print a work order for ANY coding agent\n (Claude, Codex, Gemini, ...) – pipe it to your agent CLI to\n repair the findings. Includes advisories that require review.\n --prepare-repair Save the original audit under .mason/reports/repairs/ before edits\n --verify-repair <path>\n Compare against that saved baseline, using its original checks\n --checks <list> Comma-separated subset of checks to run (default: all):\n ${ALL_CHECKS.join(\", \")}\n --help Show this help\n\nExit codes:\n 0 no issues (advisories may still be present)\n 1 provable issues found\n 2 error (no context file, not a git repository, bad arguments)\n\nWith --verify-repair: 0 verified by the original checks; 1 issues remain;\n2 incomplete (unverified findings, skipped checks, or advisories needing review).\nPreparation writes only a baseline; verification and ordinary audits are read-only.`;\n\nexport interface AuditCliIo {\n out: (line: string) => void;\n err: (line: string) => void;\n}\n\ninterface ParsedArgs {\n dir: string;\n json: boolean;\n fixPrompt: boolean;\n help: boolean;\n checks: CheckName[] | undefined;\n prepareRepair: boolean;\n baseline?: string;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const parsed: ParsedArgs = {\n dir: process.cwd(),\n json: false,\n fixPrompt: false,\n help: false,\n checks: undefined,\n prepareRepair: 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 === \"--fix-prompt\") {\n parsed.fixPrompt = true;\n } else if (arg === \"--prepare-repair\") {\n parsed.prepareRepair = true;\n } else if (arg === \"--verify-repair\") {\n const value = argv[++i];\n if (!value || value.startsWith(\"--\")) throw new Error(\"--verify-repair requires a baseline path\");\n parsed.baseline = value;\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 === \"--checks\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--checks requires a comma-separated list\");\n const names = value.split(\",\").map((n) => n.trim()).filter(Boolean);\n if (!names.length) throw new Error(\"--checks requires at least one check\");\n for (const name of names) {\n if (!ALL_CHECKS.includes(name as CheckName)) {\n throw new Error(\n `Unknown check: ${name} (valid: ${ALL_CHECKS.join(\", \")})`\n );\n }\n }\n parsed.checks = names as CheckName[];\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\nfunction issueLine(issue: AuditIssue): string {\n const where =\n issue.anchor.line !== null ? `line ${issue.anchor.line}` : \"doc-level\";\n const likely = issue.confidence === \"likely\" ? \" (likely)\" : \"\";\n return ` [${issue.type}]${likely} ${where}: ${issue.message}`;\n}\n\nexport function formatAuditSummary(report: AuditReport): string {\n const lines: string[] = [];\n const reviewCount = report.advisories.length + (report.suppressedAdvisories?.length ?? 0);\n\n for (const doc of report.docs) {\n const docIssues = report.issues.filter((i) => i.anchor.doc === doc.path);\n const committed = doc.lastCommit\n ? `last committed ${doc.lastCommit.date.slice(0, 10)}, ${doc.lastCommit.hash.slice(0, 7)}`\n : \"untracked\";\n if (docIssues.length === 0) {\n lines.push(`${doc.path} – clean (${committed})`);\n continue;\n }\n lines.push(\n `${doc.path} – ${docIssues.length} issue${docIssues.length === 1 ? \"\" : \"s\"} (${committed})`\n );\n for (const issue of docIssues) lines.push(issueLine(issue));\n }\n\n // Issues anchored outside the docs list (defensive; new-module anchors to\n // the primary doc, so this should stay empty).\n const docPaths = new Set(report.docs.map((d) => d.path));\n for (const issue of report.issues) {\n if (!docPaths.has(issue.anchor.doc)) lines.push(issueLine(issue));\n }\n\n if (report.advisories.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of report.advisories) {\n lines.push(` [${advisory.type}] ${advisory.anchor.doc}: ${advisory.message}`);\n }\n }\n if (report.skippedChecks.length > 0) {\n for (const skip of report.skippedChecks) {\n lines.push(` [skipped] ${skip.check}: ${skip.reason}`);\n }\n }\n\n for (const advisory of report.suppressedAdvisories ?? []) {\n lines.push(` [suppressed; unresolved] ${advisory.type} ${advisory.anchor.doc}: ${advisory.message}`);\n }\n\n lines.push(\n report.clean\n ? reviewCount || report.skippedChecks.length\n ? `No audit issues detected (${report.docs.length} docs audited); ${reviewCount} advisories remain for review, ${report.skippedChecks.length} checks skipped.`\n : `Context files are clean (${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"} audited).`\n : `${report.issues.length} issue${report.issues.length === 1 ? \"\" : \"s\"} across ${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"}.`\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Provider-neutral work order: any coding agent can execute it. The evidence\n * is deterministic; the agent's job is judgment scoped to exactly these\n * claims – never a free-form doc rewrite.\n */\nexport function formatFixPrompt(report: AuditReport, baselinePath?: string): string {\n const flaggedDocs = [...new Set(report.issues.map((i) => i.anchor.doc))];\n const lines: string[] = [];\n lines.push(\n \"Review the flagged context claims using the evidence below. Make minimal repairs within the user's authorized scope. A setup-only or audit-only request does not authorize rewriting existing documentation.\"\n );\n lines.push(\"\");\n lines.push(\"RULES:\");\n lines.push(baselinePath\n ? `- Preserve the original repair baseline: ${JSON.stringify(baselinePath)}. Do not replace it after editing.`\n : \"- Before the first edit, call mason_repair with action: prepare, or run mason-audit --prepare-repair --json with the same --dir and --checks. Keep the returned baselinePath through verification.\");\n lines.push(\n `- Edit ONLY these files: ${flaggedDocs.join(\", \") || \"none (advisory review only)\"}. Bring the docs into agreement with verified source evidence; do not change source code or configs to silence findings.`\n );\n lines.push(\n \"- Keep diffs minimal: change the smallest span that makes each claim true.\"\n );\n lines.push(\n \"- Never invent content. Every replacement must be grounded in the evidence below or in files you read from this repository.\"\n );\n lines.push(\"- Inspect likely findings before editing: heuristic evidence may describe an intentional omission or an example.\");\n lines.push(\n \"- deleted-reference: if evidence shows renamedTo, update the path; otherwise remove the reference, or rephrase to past tense if the sentence is about history. Deleted paths inside directory trees: delete the tree line.\"\n );\n lines.push(\n \"- stale-count: replace the number with the actual count from the evidence.\"\n );\n lines.push(\n \"- dead-command: replace with the correct script from availableScripts if an obvious rename exists; otherwise remove the command mention.\"\n );\n lines.push(\n \"- new-module: add a one-line factual mention of the directory where sibling modules are described; read the directory's files first and describe only what you verified.\"\n );\n lines.push(\n \"- ADVISORIES require a separate assessment of the cited commits or decision evidence. Report any review you perform and what remains unknown. Their disappearance after edits or a commit does not establish review or approval.\"\n );\n lines.push(\"\");\n lines.push(\"AUDIT REPORT (current context files and repository evidence, including local edits):\");\n lines.push(\n JSON.stringify(\n { root: report.root, checks: report.checksRun, issues: report.issues, advisories: report.advisories,\n suppressedAdvisories: report.suppressedAdvisories, skippedChecks: report.skippedChecks },\n null,\n 2\n )\n );\n lines.push(\"\");\n lines.push(\n \"After edits, call mason_repair with action: verify and the original baselinePath, or mason-audit --verify-repair <baselinePath> --dir <project>. Repeat against the same baseline after any final documentation commit. Summarize resolved, unresolved, review-required, unverified, and new findings with their evidence. Do not report a suppressed or unavailable check as fixed. This audit covers the listed context files; independently discovered README or application issues need their own validation.\"\n );\n return lines.join(\"\\n\");\n}\n\nexport async function runAuditCli(\n argv: string[],\n io: AuditCliIo = {\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 if (args.json && args.fixPrompt) {\n throw new Error(\"--json and --fix-prompt are mutually exclusive\");\n }\n if (args.baseline && (args.prepareRepair || args.checks || args.fixPrompt)) {\n throw new Error(\"--verify-repair cannot be combined with --prepare-repair, --checks, or --fix-prompt; verification uses the original scope\");\n }\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 if (args.baseline || args.prepareRepair) {\n try {\n if (args.baseline) {\n const verification = await verifyRepair(rootDir, args.baseline);\n io.out(args.json ? JSON.stringify(verification, null, 2) : formatRepairSummary(verification));\n return repairExitCode(verification);\n }\n const prepared = await prepareRepair(rootDir, args.checks);\n io.out(args.json ? JSON.stringify({ ...prepared, workOrder: formatFixPrompt(prepared.report, prepared.baselinePath) }, null, 2)\n : args.fixPrompt ? formatFixPrompt(prepared.report, prepared.baselinePath)\n : `Repair baseline: ${prepared.baselinePath}\\n${formatAuditSummary(prepared.report)}`);\n return prepared.report.clean ? 0 : 1;\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n return 2;\n }\n }\n const report = await computeAudit(rootDir, { checks: args.checks });\n\n if (!report) {\n io.err(\n `No CLAUDE.md, .claude/CLAUDE.md, or AGENTS.md found in ${rootDir}.`\n );\n return 2;\n }\n\n if (!report.gitAvailable) {\n io.err(\n `Could not determine git HEAD in ${rootDir} – not a git repository, or git is unavailable.`\n );\n return 2;\n }\n\n if (args.fixPrompt) {\n io.out(\n report.clean && !report.advisories.length && !report.suppressedAdvisories?.length\n ? formatAuditSummary(report) : formatFixPrompt(report)\n );\n return report.clean ? 0 : 1;\n }\n\n if (args.json) {\n io.out(JSON.stringify(report, null, 2));\n } else {\n io.out(formatAuditSummary(report));\n }\n return report.clean ? 0 : 1;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport type { FileChange } from \"../drift/drift.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { discoverDocs } from \"./docs.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { CHECKS } from \"./checks/index.js\";\nimport type { CheckContext, CheckResult } from \"./checks/index.js\";\n\nexport interface AuditOptions {\n /** Subset of checks to run; defaults to all. */\n checks?: CheckName[];\n /** Internal execution boundary used by the automation dependency cache. */\n runCheck?: (name: CheckName, context: CheckContext) => Promise<CheckResult>;\n}\n\n/**\n * Audit the repo's context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\n * against repo reality. Fully deterministic — git, filesystem, and lexical\n * extraction only; no LLM, no network. Returns null when no context file\n * exists.\n */\nexport async function computeAudit(\n rootDir: string,\n options: AuditOptions = {}\n): Promise<AuditReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const [docs, headHash] = await Promise.all([discoverDocs(resolvedRoot), getCurrentGitHash(resolvedRoot)]);\n if (docs.length === 0) return null;\n\n const report: AuditReport = {\n version: 1,\n root: resolvedRoot,\n gitAvailable: headHash !== \"unknown\",\n headHash,\n checksRun: [],\n docs: docs.map((d) => ({\n path: d.path,\n lastCommit: d.lastCommit,\n dirty: d.dirty,\n lineCount: d.lineCount,\n })),\n decisionsChecked: false,\n issues: [],\n advisories: [],\n suppressedAdvisories: [],\n skippedChecks: [],\n clean: true,\n };\n\n // Without git the provability gates cannot run — the caller treats this\n // as an error rather than silently degrading precision.\n if (!report.gitAvailable) return report;\n\n const changesSinceDoc = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n changesSinceDoc.set(\n doc.path,\n doc.lastCommit\n ? await getChangesWithStatus(resolvedRoot, doc.lastCommit.hash)\n : null\n );\n }\n\n let decisionsPresent = false;\n try {\n await fs.access(path.join(resolvedRoot, \".mason\", \"decisions\"));\n decisionsPresent = true;\n } catch {\n // No decision store — the check stays dark (zero-setup path).\n }\n report.decisionsChecked = decisionsPresent;\n\n const ctx: CheckContext = {\n root: resolvedRoot,\n docs,\n headHash,\n changesSinceDoc,\n decisionsPresent,\n };\n\n const selected = options.checks ?? ALL_CHECKS;\n for (const name of ALL_CHECKS) {\n if (!selected.includes(name)) continue;\n const { issues, advisories, suppressedAdvisories, skipped } = await (options.runCheck\n ? options.runCheck(name, ctx) : CHECKS[name](ctx));\n report.checksRun!.push(name);\n report.issues.push(...issues);\n report.advisories.push(...advisories);\n report.suppressedAdvisories!.push(...(suppressedAdvisories ?? []));\n report.skippedChecks.push(...skipped);\n }\n\n report.clean = report.issues.length === 0;\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\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { matchingPaths } from \"../utils/paths.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 WorkingTreeReport {\n available: boolean;\n changedFiles: string[];\n untrackedFiles: string[];\n}\n\nexport interface DriftReport {\n /** Live entry state; committed drift alone continues to drive CLI exit codes. */\n featureFreshness?: Record<string, Freshness>;\n flowFreshness?: Record<string, Freshness>;\n workingTree?: WorkingTreeReport;\n verification?: { neverVerified: number; failed: string[] };\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\nfunction parseChanges(output: string): FileChange[] {\n const fields = output.split(\"\\0\");\n const changes: FileChange[] = [];\n for (let i = 0; i < fields.length && fields[i];) {\n const code = fields[i++];\n const first = fields[i++];\n if (!first) break;\n const second = /^[RC]/.test(code) ? fields[i++] : undefined;\n const change: FileChange = second\n ? code.startsWith(\"R\") ? { status: \"renamed\", path: second, previousPath: first } : { status: \"added\", path: second }\n : { status: code === \"A\" ? \"added\" : code === \"D\" ? \"deleted\" : \"modified\", path: first };\n if (change.path.startsWith(\".mason/\") && (!change.previousPath || change.previousPath.startsWith(\".mason/\"))) continue;\n changes.push(change);\n }\n return changes;\n}\n\nexport function touchedPaths(changes: FileChange[]): string[] {\n return [...new Set(changes.flatMap(c => c.previousPath ? [c.previousPath, c.path] : [c.path]))].sort();\n}\n\nexport async function getChangesWithStatus(resolvedRoot: string, fromHash: string, toHash = \"HEAD\"): Promise<FileChange[] | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\") || !toHash || toHash === \"unknown\" || toHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", fromHash, toHash, \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 });\n return parseChanges(stdout);\n } catch { return null; }\n}\n\nexport async function getWorkingTree(resolvedRoot: string): Promise<WorkingTreeReport> {\n try {\n const [diff, untracked] = await Promise.all([\n exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n exec(\"git\", [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n ]);\n const untrackedFiles = untracked.stdout.split(\"\\0\").filter(f => f && !f.startsWith(\".mason/\"));\n return { available: true, changedFiles: [...new Set([...touchedPaths(parseChanges(diff.stdout)), ...untrackedFiles])].sort(), untrackedFiles };\n } catch { return { available: false, changedFiles: [], untrackedFiles: [] }; }\n}\n\nasync function countCommitsBehind(\n resolvedRoot: string,\n fromHash: string\n): Promise<number | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\")) return 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(rootDir: string): Promise<DriftReport | null> {\n const root = path.resolve(rootDir);\n const snapshot = await loadSnapshot(root);\n if (!snapshot) return null;\n const [headHash, workingTree] = await Promise.all([getCurrentGitHash(root), getWorkingTree(root)]);\n const hashFor = (entry: { refreshedHash?: string }) => entry.refreshedHash ?? snapshot.gitHash;\n const entries = [...Object.values(snapshot.features), ...Object.values(snapshot.flows)];\n const hashes = new Set([snapshot.gitHash, ...entries.map(hashFor)]);\n const changesByHash = new Map<string, FileChange[] | null>();\n await Promise.all([...hashes].map(async hash => {\n changesByHash.set(hash, hash === headHash && headHash !== \"unknown\" ? [] : await getChangesWithStatus(root, hash));\n }));\n const historyAvailable = headHash !== \"unknown\" && [...changesByHash.values()].every(changes => changes !== null);\n const mappedFiles = collectMappedFiles(snapshot);\n const report: DriftReport = {\n stale: !historyAvailable,\n snapshotHash: snapshot.gitHash, headHash,\n commitsBehind: 0, historyAvailable,\n changedFiles: [], staleFeatures: {}, staleFlows: {},\n totalFeatures: Object.keys(snapshot.features).length,\n totalFlows: Object.keys(snapshot.flows).length,\n unmappedFiles: [], ghostFiles: await findGhostFiles(root, mappedFiles), renames: [],\n recommendation: historyAvailable ? \"up-to-date\" : \"full-rebuild\",\n featureFreshness: {}, flowFreshness: {}, workingTree,\n verification: {\n neverVerified: entries.filter(e => !e.verifiedAt).length,\n failed: [...Object.entries(snapshot.features), ...Object.entries(snapshot.flows)].filter(([, e]) => e.verificationFailed).map(([name]) => name),\n },\n };\n const counts = await Promise.all([...hashes].map(hash => hash === headHash ? 0 : countCommitsBehind(root, hash)));\n const knownCounts = counts.filter((n): n is number => n !== null);\n report.commitsBehind = knownCounts.length ? Math.max(...knownCounts) : null;\n\n const check = (name: string, files: string[], hash: string, staleEntries: Record<string, string[]>, freshness: Record<string, Freshness>) => {\n const changes = changesByHash.get(hash);\n const committedHits = changes ? matchingPaths(files, touchedPaths(changes)) : [];\n if (committedHits.length) staleEntries[name] = committedHits;\n const localHits = matchingPaths(files, workingTree.changedFiles);\n freshness[name] = files.length === 0 || changes === null || changes === undefined || !workingTree.available ? \"unknown\"\n : committedHits.length || localHits.length || files.some(f => report.ghostFiles.includes(f)) ? \"changed\" : \"current\";\n };\n for (const [name, feature] of Object.entries(snapshot.features)) {\n check(name, [...feature.files, ...(feature.tests ?? [])], hashFor(feature), report.staleFeatures, report.featureFreshness!);\n }\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n check(name, flow.chain, hashFor(flow), report.staleFlows, report.flowFreshness!);\n }\n\n const allChanges = [...changesByHash.values()].flatMap(changes => changes ?? []);\n report.changedFiles = [...new Set(allChanges.map(c => c.path))].sort();\n // Complete coverage, including omissions from a map saved at HEAD. Untracked\n // files remain in workingTree and never change the committed-drift exit code.\n const sourceFiles = new Set(await listSourceFiles(root));\n let committedFiles: Set<string> = new Set();\n try {\n const { stdout } = await exec(\"git\", [\"ls-tree\", \"-r\", \"--name-only\", \"-z\", \"HEAD\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n committedFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch { report.historyAvailable = false; report.stale = true; }\n report.unmappedFiles = [...sourceFiles].filter(f => committedFiles.has(f) && !mappedFiles.has(f)).sort();\n const renames = new Map<string, { from: string; to: string }>();\n for (const change of allChanges) {\n if (change.status === \"renamed\" && change.previousPath) renames.set(`${change.previousPath}\\0${change.path}`, { from: change.previousPath, to: change.path });\n }\n report.renames = [...renames.values()];\n const changedMapped = new Set([...Object.values(report.staleFeatures).flat(), ...Object.values(report.staleFlows).flat()]);\n // A locally deleted file is a live-edit warning, not committed map drift.\n const committedGhosts = report.ghostFiles.filter(f => !workingTree.changedFiles.includes(f));\n report.stale ||= changedMapped.size > 0 || report.unmappedFiles.length > 0 || committedGhosts.length > 0;\n if (!report.historyAvailable) report.recommendation = \"full-rebuild\";\n else if (!report.stale) report.recommendation = \"up-to-date\";\n else report.recommendation = changedMapped.size >= FULL_REBUILD_MIN_CHANGED_MAPPED_FILES && changedMapped.size / Math.max(1, mappedFiles.size) > FULL_REBUILD_FRACTION ? \"full-rebuild\" : \"incremental\";\n return report;\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess } from \"../utils/files.js\";\nexport { SOURCE_GLOB, SOURCE_IGNORE } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.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) — 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 verifiedHash?: 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 verifiedHash?: 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\nconst repoPath = z.string().refine(value => normalizeRepoPath(value) !== null, \"Expected a relative repository path\");\nconst verificationFields = {\n refreshedHash: z.string().optional(), verifiedAt: z.string().optional(),\n verifiedHash: z.string().optional(), verificationFailed: z.boolean().optional(),\n verificationNote: z.string().optional(),\n};\nexport const featureSchema = z.object({\n description: z.string(), files: z.array(repoPath), tests: z.array(repoPath).optional(),\n type: z.enum([\"capability\", \"infrastructure\"]).optional(), ...verificationFields,\n}).passthrough();\nexport const flowSchema = z.object({ description: z.string(), chain: z.array(repoPath), ...verificationFields }).passthrough();\nconst snapshotSchema = z.object({\n version: z.literal(2), createdAt: z.string(), updatedAt: z.string(), gitHash: z.string(),\n features: z.record(featureSchema), flows: z.record(flowSchema),\n}).passthrough();\n\nexport async function loadSnapshot(rootDir: string): Promise<Snapshot | null> {\n const parsed = await readStoreJson(rootDir, \".mason/snapshot.json\");\n if (parsed === null || (parsed as { version?: number }).version === 1) return null;\n const result = snapshotSchema.safeParse(parsed);\n if (!result.success) throw new Error(`Invalid Mason snapshot: ${result.error.message}`);\n return result.data;\n}\n\n/** Context and onboarding can use decisions even when the optional map is broken. */\nexport async function inspectSnapshot(rootDir: string): Promise<{\n status: \"available\" | \"missing\" | \"invalid\";\n snapshot: Snapshot | null;\n diagnostics: StoreDiagnostic[];\n}> {\n try {\n const raw = await readStoreJson(rootDir, \".mason/snapshot.json\");\n const snapshot = raw === null ? null : snapshotSchema.parse(raw);\n return { status: snapshot ? \"available\" : \"missing\", snapshot, diagnostics: [] };\n } catch (error) {\n return { status: \"invalid\", snapshot: null, diagnostics: [{\n path: \".mason/snapshot.json\", message: error instanceof Error ? error.message : String(error),\n }] };\n }\n}\n\nexport async function saveSnapshot(rootDir: string, snapshot: Snapshot): Promise<void> {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(snapshot));\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 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 return (await createFileAccess(resolvedRoot)).list();\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 const access = await createFileAccess(resolvedRoot);\n let allFiles = await access.list();\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 access.read(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 access.read(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 { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\nconst exec = promisify(execFile);\nexport const SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\", \"vue\", \"svelte\", \"kt\", \"kts\", \"java\", \"py\", \"go\", \"rs\", \"swift\", \"rb\", \"cs\", \"cpp\", \"c\", \"h\", \"hpp\", \"dart\", \"php\"];\nexport const SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(\",\")}}`;\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/.mason/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\", \"**/*.lock\",\n \"**/generated/**\", \"**/*.generated.*\", \"**/R.java\", \"**/BuildConfig.java\",\n \"**/package-lock.json\", \"**/yarn.lock\", \"**/pnpm-lock.yaml\",\n];\nexport const MAX_SOURCE_BYTES = 1024 * 1024;\nexport interface ProjectConfig { patterns?: string[]; alwaysInclude?: string[]; ignore?: string[] }\nexport interface SourceFile { path: string; content: string; totalLines: number }\n\nexport function isSensitiveFile(file: string): boolean {\n return file.split(/[\\\\/]/).some(part =>\n /^(?:\\.env(?:\\..*)?|id_rsa.*|id_ed25519.*)$|\\.(?:pem|key|p12|pfx|jks|keystore)$|credentials\\.|secret|^local\\.properties$/i.test(part)\n );\n}\n\n/** Bound reads even if a file grows after stat. Only read regular files. */\nexport async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {\n // Do not block on a FIFO or follow a symlink substituted after resolution.\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > maxBytes) return null;\n const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));\n let bytes = 0;\n while (bytes < buffer.length) {\n const result = await handle.read(buffer, bytes, buffer.length - bytes, null);\n if (result.bytesRead === 0) break;\n bytes += result.bytesRead;\n }\n return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString(\"utf8\");\n } finally { await handle.close(); }\n}\n\nexport async function loadProjectConfig(root: string): Promise<ProjectConfig> {\n try {\n const canonicalRoot = await fs.realpath(root);\n const configPath = await fs.realpath(path.join(root, \".mason/config.json\"));\n if (!isWithinRoot(canonicalRoot, configPath)) throw new Error(\"Project configuration resolves outside the repository\");\n const raw = await readBoundedFile(configPath, 64 * 1024);\n if (raw === null) throw new Error(\"Project configuration is not a regular file or exceeds 64 KiB\");\n const value = JSON.parse(raw);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Expected a configuration object\");\n const config: ProjectConfig = {};\n for (const key of [\"patterns\", \"alwaysInclude\", \"ignore\"] as const) {\n if (value[key] === undefined) continue;\n if (!Array.isArray(value[key]) || !value[key].every((s: unknown) => typeof s === \"string\")) {\n throw new Error(`Configuration ${key} must be an array of strings`);\n }\n config[key] = value[key];\n }\n return config;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new Error(`Cannot apply project file policy: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/** Scoped to one operation, so a later tool call sees newly edited files/ignores. */\nexport async function createFileAccess(rootDir: string) {\n const root = path.resolve(rootDir);\n const canonicalRoot = await fs.realpath(root).catch(() => root);\n const config = await loadProjectConfig(root);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n let gitFiles: Set<string> | null = null;\n try {\n const { stdout } = await exec(\"git\", [\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n gitFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch {\n // File-system projects are supported. Fail closed if this IS a Git repo.\n let inGit = false;\n try { await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: root }); inGit = true; } catch { /* no Git */ }\n if (inGit) throw new Error(\"Cannot enumerate Git files safely\");\n }\n\n async function resolve(file: string): Promise<string | null> {\n const relative = normalizeRepoPath(file);\n if (!relative || isSensitiveFile(relative) || (gitFiles && !gitFiles.has(relative))) return null;\n const candidate = path.join(root, relative);\n try {\n const real = await fs.realpath(candidate);\n if (!isWithinRoot(canonicalRoot, real) || isSensitiveFile(path.relative(canonicalRoot, real))) return null;\n const stat = await fs.stat(real);\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) return null;\n // A symlink must not bypass the target's ignore policy either.\n if (gitFiles && !gitFiles.has(path.relative(canonicalRoot, real).split(path.sep).join(\"/\"))) return null;\n return real;\n } catch { return null; }\n }\n\n async function list(patterns: string | string[] = SOURCE_GLOB, options: { deep?: number; dot?: boolean } = {}): Promise<string[]> {\n const found = await fg(patterns, { cwd: root, ignore, followSymbolicLinks: false, ...options });\n const safe = await Promise.all(found.map(async f => (await resolve(f)) ? f : null));\n return safe.filter((f): f is string => f !== null).sort();\n }\n\n async function read(file: string): Promise<SourceFile | null> {\n const relative = normalizeRepoPath(file);\n if (!relative) return null;\n const real = await resolve(relative);\n if (!real) return null;\n // Apply the same glob exclusions to explicit reads and symlink targets.\n for (const rel of new Set([relative, path.relative(canonicalRoot, real).split(path.sep).join(\"/\")])) {\n if (!(await fg(fg.escapePath(rel), { cwd: root, ignore, dot: true })).length) return null;\n }\n try {\n const content = await readBoundedFile(real, MAX_SOURCE_BYTES);\n return content === null ? null : { path: relative, content, totalLines: content.split(\"\\n\").length };\n } catch { return null; }\n }\n return { root, config, list, read };\n}\n","import path from \"node:path\";\n\n/** One canonical representation for stored paths and decision anchors. */\nexport function normalizeRepoPath(value: string): string | null {\n const slash = value.replace(/\\\\/g, \"/\");\n if (!slash || slash.includes(\"\\0\") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;\n if (slash.split(\"/\").includes(\"..\")) return null;\n const normalized = path.posix.normalize(slash).replace(/\\/$/, \"\");\n return normalized === \".\" ? null : normalized;\n}\n\nexport function sanitizeRepoPaths(files: string[]): string[] {\n return [...new Set(files.map(normalizeRepoPath).filter((p): p is string => p !== null))];\n}\n\nexport function isWithinRoot(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nexport function anchorMatches(anchor: string, file: string): boolean {\n const a = normalizeRepoPath(anchor);\n const f = normalizeRepoPath(file);\n return a !== null && f !== null && (a === f || f.startsWith(`${a}/`));\n}\n\nexport function matchingPaths(anchors: string[], files: Iterable<string>): string[] {\n return [...new Set(files)].filter(file => anchors.some(anchor => anchorMatches(anchor, file)));\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { normalizeRepoPath } from \"./paths.js\";\nimport { readBoundedFile } from \"./files.js\";\n\nexport interface StoreDiagnostic { path: string; message: string }\n\n/** Metadata paths may not contain symlinks, including their parent directories. */\nexport async function storePath(root: string, relative: string, createParents = false): Promise<string> {\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Invalid store path: ${relative}`);\n let current = await fs.realpath(root);\n const parts = normalized.split(\"/\");\n for (let i = 0; i < parts.length; i++) {\n current = path.join(current, parts[i]);\n let stat;\n try { stat = await fs.lstat(current); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n if (createParents && i < parts.length - 1) {\n try { await fs.mkdir(current); } catch (mkdirError) {\n if ((mkdirError as NodeJS.ErrnoException).code !== \"EEXIST\") throw mkdirError;\n }\n stat = await fs.lstat(current);\n }\n }\n if (stat?.isSymbolicLink()) throw new Error(`Symlink in store path: ${relative}`);\n }\n return current;\n}\n\nexport async function readStoreJson(root: string, relative: string): Promise<unknown | null> {\n try {\n const file = await storePath(root, relative);\n const raw = await readBoundedFile(file, 10 * 1024 * 1024);\n if (raw === null) throw new Error(\"file is not regular or exceeds 10 MiB\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null) throw new Error(\"expected a JSON object, received null\");\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new Error(`Invalid Mason store ${relative}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nexport async function writeStoreJson(root: string, relative: string, value: unknown): Promise<void> {\n const payload = JSON.stringify(value, null, 2) + \"\\n\";\n if (Buffer.byteLength(payload) > 10 * 1024 * 1024) {\n throw new Error(`Mason store ${relative} exceeds 10 MiB`);\n }\n const file = await storePath(root, relative, true);\n const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);\n try {\n const handle = await fs.open(temporary, \"wx\", 0o600);\n try { await handle.writeFile(payload, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n await fs.rename(temporary, file);\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import path from \"node:path\";\nimport { createFileAccess } from \"./utils/files.js\";\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 const access = await createFileAccess(rootDir);\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 access.list(testPatterns);\n\n // Find all source files\n const sourceFiles = await access.list();\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 { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * All context files audited in v1, in the precedence order the setup\n * playbook uses. Every candidate that exists is audited — a repo can\n * legitimately carry both AGENTS.md and CLAUDE.md, and drift can live in\n * either.\n */\nexport const DOC_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".claude/CLAUDE.md\",\n] as const;\n\nexport interface AuditDoc {\n /** Repo-relative posix path. */\n path: string;\n content: string;\n lineCount: number;\n /** Null when the doc is untracked. */\n lastCommit: CommitRef | null;\n /** Uncommitted edits present. */\n dirty: boolean;\n claims: DocClaims;\n}\n\nasync function isDirty(resolvedRoot: string, relPath: string): Promise<boolean> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"status\", \"--porcelain\", \"--\", relPath],\n { cwd: resolvedRoot }\n );\n return stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs = await Promise.all(DOC_CANDIDATES.map(async (candidate): Promise<AuditDoc | null> => {\n let content: string;\n try {\n content = await fs.readFile(path.join(resolvedRoot, candidate), \"utf-8\");\n } catch {\n return null;\n }\n const [lastCommit, dirty] = await Promise.all([lastCommitOf(resolvedRoot, candidate), isDirty(resolvedRoot, candidate)]);\n return {\n path: candidate,\n content,\n lineCount: content.split(\"\\n\").length,\n lastCommit,\n dirty,\n claims: extractClaims(content),\n };\n }));\n return docs.filter((doc): doc is AuditDoc => doc !== null);\n}\n","import type { PathClaim } from \"./types.js\";\n\n/**\n * A fenced block is treated as a directory tree only when it clearly is one —\n * below this many branch-glyph lines it's more likely an ASCII sketch.\n */\nconst MIN_GLYPH_LINES = 3;\n\nconst GLYPHS = [\"├──\", \"└──\"] as const;\n\nfunction glyphIndex(line: string): number {\n for (const glyph of GLYPHS) {\n const idx = line.indexOf(glyph);\n if (idx !== -1) return idx;\n }\n return -1;\n}\n\n/** Tree furniture: blank, or only vertical bars and whitespace. */\nfunction isSpacerLine(line: string): boolean {\n return /^[\\s│|]*$/.test(line);\n}\n\n/**\n * Strip an inline comment/annotation from a tree entry. Entries commonly\n * carry `# comment` or column-aligned notes after two or more spaces.\n */\nfunction entryName(afterGlyph: string): string | null {\n let name = afterGlyph.replace(/^\\s+/, \"\");\n const hash = name.search(/\\s+#/);\n if (hash !== -1) name = name.slice(0, hash);\n const columns = name.search(/\\s{2,}/);\n if (columns !== -1) name = name.slice(0, columns);\n name = name.trim();\n // A name with remaining internal whitespace is not a path — treat the\n // line as malformed rather than guessing.\n if (!name || /\\s/.test(name)) return null;\n return name;\n}\n\n/**\n * Reconstruct full paths from an ASCII directory tree inside a fenced block.\n *\n * The failure mode must always be a missed claim, never an invented path: a\n * line that doesn't parse cleanly aborts reconstruction below it, and every\n * emitted path still passes the deleted-reference provability gate later.\n *\n * `blockLines` are the fence's content lines; `blockStartLine` is the 1-based\n * doc line number of the first content line.\n */\nexport function extractTreeClaims(\n blockLines: string[],\n blockStartLine: number\n): PathClaim[] {\n const glyphLines = blockLines.filter((l) => glyphIndex(l) !== -1).length;\n if (glyphLines < MIN_GLYPH_LINES) return [];\n\n const claims: PathClaim[] = [];\n // Directories on the path from the root to the current entry, keyed by the\n // column their branch glyph appeared at.\n const stack: Array<{ col: number; name: string }> = [];\n let rootPrefix = \"\";\n let started = false;\n\n for (let i = 0; i < blockLines.length; i++) {\n const line = blockLines[i];\n const col = glyphIndex(line);\n\n if (col === -1) {\n if (isSpacerLine(line)) continue;\n if (!started) {\n // A bare `src/` line above the first glyph names the tree's root.\n const candidate = line.trim();\n if (candidate.endsWith(\"/\") && !/\\s/.test(candidate)) {\n rootPrefix = candidate.replace(/\\/+$/, \"\");\n claims.push({\n path: rootPrefix,\n line: blockStartLine + i,\n excerpt: candidate,\n });\n }\n continue;\n }\n // Unparseable line after the tree began: stop here, keep what we have.\n return claims;\n }\n\n started = true;\n const name = entryName(line.slice(col + GLYPHS[0].length));\n if (name === null) return claims;\n\n while (stack.length > 0 && stack[stack.length - 1].col >= col) {\n stack.pop();\n }\n\n const isDir = name.endsWith(\"/\");\n const cleanName = name.replace(/\\/+$/, \"\");\n const segments = [\n ...(rootPrefix ? [rootPrefix] : []),\n ...stack.map((s) => s.name),\n cleanName,\n ];\n claims.push({\n path: segments.join(\"/\"),\n line: blockStartLine + i,\n excerpt: name,\n });\n\n if (isDir) stack.push({ col, name: cleanName });\n }\n\n return claims;\n}\n","import type {\n CommandClaim,\n CountClaim,\n DocClaims,\n PathClaim,\n} from \"./types.js\";\nimport { extractTreeClaims } from \"./tree.js\";\n\n/**\n * Single-segment names that count as path claims without containing a \"/\".\n * Anything else without a slash is prose (\"name your file `config.ts`\"), not\n * a claim about this repo.\n */\nconst ROOT_FILE_NAMES = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-workspace.yaml\",\n \"tsconfig.json\",\n \"tsup.config.ts\",\n \"vitest.config.ts\",\n \"Makefile\",\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"go.sum\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"manifest.json\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\",\n \"CLAUDE.md\",\n \"AGENTS.md\",\n \".gitignore\",\n \".env.example\",\n]);\n\nconst SHELL_FENCE_INFOS = new Set([\"\", \"bash\", \"sh\", \"shell\", \"console\", \"zsh\"]);\n\nconst COMMAND_RE = /\\b(npm|pnpm|yarn)\\s+run\\s+([A-Za-z0-9:_.-]+)/g;\nconst COUNT_RE = /(\\d+)\\s+(modules?|packages?|workspaces?|crates?)\\b/gi;\n/** \"3 package managers\" is not a package count. */\nconst COUNT_DENYLIST_RE = /^\\s*(manager|registr|lock|json)/i;\n\nconst IGNORE_LINE = \"<!-- mason:ignore -->\";\nconst IGNORE_START = \"<!-- mason:ignore-start -->\";\nconst IGNORE_END = \"<!-- mason:ignore-end -->\";\n\n/**\n * Normalize a candidate token into a repo-relative path claim, or return\n * null when the token is not a claim about this repo (URL, glob,\n * placeholder, relative import example, bare word).\n */\nexport function normalizePathToken(token: string): string | null {\n let t = token.trim();\n if (!t) return null;\n if (/\\s/.test(t)) return null;\n if (t.includes(\"://\") || t.includes(\"\\\\\")) return null;\n if (/[*?[\\]{}<>$`]/.test(t)) return null;\n if (t.startsWith(\"/\") || t.startsWith(\"~\") || t.startsWith(\"./\") || t.startsWith(\"../\")) {\n return null;\n }\n // `src/mcp/tools.ts:189` claims the file, not the line.\n t = t.replace(/:\\d+(?:-\\d+)?$/, \"\");\n if (t.includes(\":\")) return null;\n const normalized = t.replace(/\\/+$/, \"\");\n if (!normalized) return null;\n // `server/src/test/kotlin/...` — a dots-only segment is an \"and so on\"\n // placeholder, not a claim.\n if (normalized.split(\"/\").some((seg) => /^\\.+$/.test(seg))) return null;\n if (normalized.includes(\"/\")) return normalized;\n return ROOT_FILE_NAMES.has(normalized) ? normalized : null;\n}\n\n/** A fence line that is exactly one path-shaped token is a file-list claim. */\nfunction exactTokenPath(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed || /\\s/.test(trimmed) || !trimmed.includes(\"/\")) return null;\n return normalizePathToken(trimmed);\n}\n\nfunction computeIgnoredLines(lines: string[]): boolean[] {\n const ignored = new Array<boolean>(lines.length).fill(false);\n let inRegion = false;\n let ignoreNext = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.includes(IGNORE_START)) {\n inRegion = true;\n ignored[i] = true;\n continue;\n }\n if (line.includes(IGNORE_END)) {\n inRegion = false;\n ignored[i] = true;\n continue;\n }\n if (inRegion) {\n ignored[i] = true;\n continue;\n }\n if (ignoreNext) {\n if (line.trim().length === 0) continue; // skip blanks to the next real line\n ignored[i] = true;\n ignoreNext = false;\n continue;\n }\n if (line.includes(IGNORE_LINE)) {\n ignored[i] = true;\n const rest = line.replace(IGNORE_LINE, \"\").trim();\n if (rest.length === 0) ignoreNext = true;\n }\n }\n return ignored;\n}\n\n/**\n * Extract every checkable claim from a context-file's markdown. Deterministic\n * and purely lexical — precision comes from the checks' provability gates,\n * not from clever parsing here.\n */\nexport function extractClaims(content: string): DocClaims {\n const lines = content.split(\"\\n\");\n const ignored = computeIgnoredLines(lines);\n\n const paths = new Map<string, PathClaim>();\n const counts: CountClaim[] = [];\n const commands = new Map<string, CommandClaim>();\n\n const addPath = (claim: PathClaim): void => {\n if (!paths.has(claim.path)) paths.set(claim.path, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n if (!commands.has(claim.scriptName)) commands.set(claim.scriptName, claim);\n };\n\n let inFence = false;\n let fenceInfo = \"\";\n let fenceMarker = \"\";\n let blockLines: string[] = [];\n let blockStartLine = 0;\n\n const processBlock = (): void => {\n for (const claim of extractTreeClaims(blockLines, blockStartLine)) {\n addPath(claim);\n }\n for (let i = 0; i < blockLines.length; i++) {\n const exact = exactTokenPath(blockLines[i]);\n if (exact) {\n addPath({\n path: exact,\n line: blockStartLine + i,\n excerpt: blockLines[i].trim(),\n });\n }\n }\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNo = i + 1;\n const fenceMatch = line.match(/^\\s*(```+|~~~+)(.*)$/);\n\n if (fenceMatch) {\n if (!inFence) {\n inFence = true;\n fenceMarker = fenceMatch[1][0];\n fenceInfo = fenceMatch[2].trim().toLowerCase();\n blockLines = [];\n blockStartLine = lineNo + 1;\n } else if (fenceMatch[1][0] === fenceMarker) {\n inFence = false;\n processBlock();\n }\n continue;\n }\n\n if (inFence) {\n // Ignored lines become spacers so the rest of a tree still parses.\n blockLines.push(ignored[i] ? \"\" : line);\n if (!ignored[i] && SHELL_FENCE_INFOS.has(fenceInfo)) {\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n continue;\n }\n\n if (ignored[i]) continue;\n\n for (const m of line.matchAll(/`([^`]+)`/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(/\"([A-Za-z][\\w.@-]*(?:\\/[\\w.@-]+)+\\/?)\"/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(COUNT_RE)) {\n const rest = line.slice((m.index ?? 0) + m[0].length);\n if (COUNT_DENYLIST_RE.test(rest)) continue;\n counts.push({\n count: Number.parseInt(m[1], 10),\n unit: m[2].toLowerCase(),\n line: lineNo,\n excerpt: m[0],\n });\n }\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n\n // An unclosed fence still gets its block processed — trees at the end of a\n // truncated doc are claims too.\n if (inFence) processBlock();\n\n return {\n paths: [...paths.values()],\n counts,\n commands: [...commands.values()],\n };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CommitRef } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\nconst COMMIT_FORMAT = \"%H%x09%cI%x09%s\";\n\nfunction parseCommitLine(line: string): CommitRef | null {\n const parts = line.split(\"\\t\");\n if (parts.length < 3 || !parts[0]) return null;\n return { hash: parts[0], date: parts[1], subject: parts.slice(2).join(\"\\t\") };\n}\n\n/** Most recent commit touching a path, or null if the path was never tracked. */\nexport async function lastCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** The commit that deleted a path, or null if none did. */\nexport async function deletingCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n relPath,\n ],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** Oldest commit touching a path (used to date a directory's appearance). */\nexport async function firstCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\nexport interface RangeCommits {\n commits: Array<CommitRef & { files: string[] }>;\n total: number;\n}\n\n/**\n * Commits in fromHash..HEAD touching any of the pathspecs, newest first, with\n * the touched files per commit. Rev-range, not --since: immune to rebase date\n * skew and CI checkout mtimes. Returns null when the range is uncomputable\n * (unreachable base commit, shallow clone, no git).\n */\nexport async function commitsTouchingSince(\n resolvedRoot: string,\n fromHash: string,\n pathspecs: string[]\n): Promise<RangeCommits | null> {\n if (!fromHash || fromHash === \"unknown\") return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `${fromHash}..HEAD`,\n `--format=%x01${COMMIT_FORMAT}`,\n \"--name-only\",\n \"--\",\n ...pathspecs,\n ],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n\n const commits: Array<CommitRef & { files: string[] }> = [];\n // \\x01 marks each commit header so name-only file lists can't be\n // mistaken for headers.\n for (const block of stdout.split(\"\\x01\")) {\n if (!block.trim()) continue;\n const lines = block.split(\"\\n\").filter((l) => l.trim().length > 0);\n const ref = parseCommitLine(lines[0]);\n if (!ref) continue;\n commits.push({ ...ref, files: lines.slice(1).map((l) => l.trim()) });\n }\n return { commits, total: commits.length };\n } catch {\n return null;\n }\n}\n","import type { decisionProvenance } from \"../decisions/provenance.js\";\n\nexport type IssueType =\n | \"deleted-reference\"\n | \"new-module\"\n | \"stale-count\"\n | \"dead-command\";\n\nexport type AdvisoryType = \"deps-changed\" | \"decision-anchor-drift\";\n\nexport type CheckName = IssueType | AdvisoryType;\n\nexport const ALL_CHECKS: CheckName[] = [\n \"deleted-reference\",\n \"new-module\",\n \"stale-count\",\n \"dead-command\",\n \"deps-changed\",\n \"decision-anchor-drift\",\n];\n\n/**\n * \"certain\" — the claim is provably false (a tracked path is gone, a computed\n * count differs, a script exists in no manifest). \"likely\" — evidence-backed\n * but heuristic (an unmentioned directory; a never-tracked path whose parent\n * exists). Certain-class issues are safe to auto-fix; likely-class issues\n * deserve a look.\n */\nexport type Confidence = \"certain\" | \"likely\";\n\nexport interface CommitRef {\n hash: string;\n date: string;\n subject: string;\n}\n\nexport interface DocAnchor {\n /** Repo-relative doc path, e.g. \"CLAUDE.md\" or \".claude/CLAUDE.md\". */\n doc: string;\n /** 1-based line of the claim; null for doc-level issues (new-module). */\n line: number | null;\n /** The claim exactly as written, e.g. \"src/utils/logger.ts\". */\n excerpt: string | null;\n}\n\nexport type Evidence =\n | {\n kind: \"missing-path\";\n claimed: string;\n renamedTo: string | null;\n deletedInCommit: CommitRef | null;\n everTracked: boolean;\n parentDirExists: boolean;\n }\n | {\n kind: \"unmentioned-dir\";\n dir: string;\n sourceFileCount: number;\n firstCommit: CommitRef | null;\n checkedDocs: string[];\n }\n | {\n kind: \"count-mismatch\";\n claimed: number;\n actual: number;\n unit: string;\n /** Where the actual count came from, e.g. \"package.json workspaces\". */\n countedFrom: string;\n members: string[];\n }\n | {\n kind: \"missing-script\";\n scriptName: string;\n invocation: string;\n manifestsChecked: string[];\n availableScripts: string[];\n }\n | {\n kind: \"doc-behind-manifests\";\n docLastCommit: CommitRef;\n manifestCommits: Array<CommitRef & { files: string[] }>;\n totalCommits: number;\n }\n | {\n kind: \"decision-anchor\";\n provenance?: ReturnType<typeof decisionProvenance>;\n decisionId: string;\n title: string;\n changedFiles: string[];\n refreshedHash: string;\n };\n\nexport interface AuditIssue {\n type: IssueType;\n message: string;\n anchor: DocAnchor;\n confidence: Confidence;\n evidence: Evidence;\n}\n\n/**\n * Advisories are facts the fixing agent cannot close by editing the doc (a\n * manifest commit after the doc's commit stays true forever; decision records\n * must be re-verified by humans). They NEVER affect the exit code — same\n * precedent as decision staleness in mason-drift.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n}\n\nexport interface AuditDocInfo {\n path: string;\n lastCommit: CommitRef | null;\n /** Uncommitted edits present — deps-changed is suppressed for dirty docs. */\n dirty: boolean;\n lineCount: number;\n}\n\nexport interface AuditReport {\n /** Additive-only schema — this output is a CI contract. */\n version: 1;\n root: string;\n gitAvailable: boolean;\n /** Commit and exact check scope used by this run. */\n headHash?: string;\n checksRun?: CheckName[];\n docs: AuditDocInfo[];\n /** Whether .mason/decisions/ existed and was checked. */\n decisionsChecked: boolean;\n /** Drive exit code 1. */\n issues: AuditIssue[];\n /** Never drive the exit code. */\n advisories: AuditAdvisory[];\n /** Original committed evidence retained while local doc edits suppress reporting. */\n suppressedAdvisories?: AuditAdvisory[];\n skippedChecks: Array<{ check: string; reason: string; doc?: string }>;\n clean: boolean;\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CountClaim {\n count: number;\n unit: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CommandClaim {\n scriptName: string;\n invocation: string;\n line: number;\n excerpt: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport type { AuditIssue } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nasync function exists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A claimed path that is missing on disk is only flagged when the repo can\n * prove it was ever real: a rename since the doc's last commit, or git\n * history for the path, or at least an existing parent directory. Paths with\n * none of those are illustrative examples and are dropped silently.\n */\nexport async function checkDeletedReferences(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map<string, string>();\n for (const change of changes ?? []) {\n if (change.status === \"renamed\" && change.previousPath) {\n renames.set(change.previousPath, change.path);\n }\n }\n\n for (const claim of doc.claims.paths) {\n // Mason's own metadata is optional state, not repo structure — docs\n // legitimately describe .mason/ files that a given repo doesn't have.\n if (claim.path === \".mason\" || claim.path.startsWith(\".mason/\")) {\n continue;\n }\n if (await exists(path.join(ctx.root, claim.path))) continue;\n\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const renamedTo = renames.get(claim.path) ?? null;\n\n if (renamedTo) {\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` was renamed to \\`${renamedTo}\\``,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo,\n deletedInCommit: null,\n everTracked: true,\n parentDirExists: true,\n },\n });\n continue;\n }\n\n const tracked = await lastCommitOf(ctx.root, claim.path);\n if (tracked) {\n const deleted = await deletingCommitOf(ctx.root, claim.path);\n const detail = deleted\n ? ` – deleted in ${deleted.hash.slice(0, 7)} \"${deleted.subject}\" (${deleted.date.slice(0, 10)})`\n : \"\";\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` no longer exists${detail}`,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: deleted,\n everTracked: true,\n parentDirExists: await exists(\n path.join(ctx.root, path.dirname(claim.path))\n ),\n },\n });\n continue;\n }\n\n const parentDirExists = await exists(\n path.join(ctx.root, path.dirname(claim.path))\n );\n if (!parentDirExists) continue;\n\n const issue: AuditIssue = {\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` does not exist (never tracked in git – possible typo or invented path)`,\n anchor,\n confidence: \"likely\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: null,\n everTracked: false,\n parentDirExists: true,\n },\n };\n result.issues.push(issue);\n }\n }\n\n return result;\n}\n","import fg from \"fast-glob\";\nimport path from \"node:path\";\nimport { SOURCE_GLOB, SOURCE_IGNORE } from \"../../snapshot/snapshot.js\";\nimport { firstCommitOf } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Directories that are never \"modules\" worth documenting. */\nconst DIR_DENYLIST = new Set([\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \"coverage\",\n \"target\",\n \"vendor\",\n \"__pycache__\",\n \"venv\",\n \".venv\",\n \".git\",\n \".gradle\",\n \".mason\",\n \".claude\",\n \".github\",\n \".vscode\",\n \".idea\",\n]);\n\n/** Second-level dirs need a bit more substance before they count. */\nconst SECOND_LEVEL_MIN_SOURCE_FILES = 2;\n/**\n * Descend into a top-level dir only when the docs evidently enumerate its\n * children — at least this many of its subdirs already mentioned.\n */\nconst ENUMERATION_THRESHOLD = 2;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Word-boundary mention check across the union of all docs — `app` must not\n * match \"application\", and a dir mentioned only in AGENTS.md must not be\n * flagged against CLAUDE.md.\n */\nfunction isMentioned(combinedDocs: string, name: string): boolean {\n const re = new RegExp(\n `(^|[^A-Za-z0-9_-])${escapeRegExp(name)}(/|[^A-Za-z0-9_-]|$)`,\n \"im\"\n );\n return re.test(combinedDocs);\n}\n\nasync function listSubdirs(absDir: string): Promise<string[]> {\n const dirs = await fg(\"*\", {\n cwd: absDir,\n onlyDirectories: true,\n suppressErrors: true,\n });\n return dirs.filter((d) => !DIR_DENYLIST.has(d)).sort();\n}\n\nasync function countSourceFiles(absDir: string): Promise<number> {\n const files = await fg(SOURCE_GLOB, {\n cwd: absDir,\n ignore: SOURCE_IGNORE,\n suppressErrors: true,\n });\n return files.length;\n}\n\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = ctx.docs.map((d) => d.content).join(\"\\n\");\n const primaryDoc = ctx.docs[0].path;\n const checkedDocs = ctx.docs.map((d) => d.path);\n\n const flag = async (dir: string, sourceFileCount: number): Promise<void> => {\n result.issues.push({\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in any context file`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\n confidence: \"likely\",\n evidence: {\n kind: \"unmentioned-dir\",\n dir,\n sourceFileCount,\n firstCommit: await firstCommitOf(ctx.root, dir),\n checkedDocs,\n },\n });\n };\n\n for (const candidate of await moduleCandidates(ctx.root, combinedDocs)) {\n await flag(candidate.dir, candidate.sourceFileCount);\n }\n\n return result;\n}\n\n/** Shared dependency witness: cache exactly the module candidates the audit observes. */\nexport async function moduleCandidates(root: string, combinedDocs: string) {\n const candidates: Array<{ dir: string; sourceFileCount: number }> = [];\n for (const topDir of await listSubdirs(root)) {\n const absTop = path.join(root, topDir);\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(absTop);\n if (count >= 1) candidates.push({ dir: topDir, sourceFileCount: count });\n continue;\n }\n\n // The docs know this dir. If they enumerate its children (several\n // subdirs already mentioned), an unmentioned sibling is drift — this is\n // how a freshly added module under src/ gets caught.\n const subdirs = await listSubdirs(absTop);\n const mentioned = subdirs.filter((s) => isMentioned(combinedDocs, s));\n if (mentioned.length < ENUMERATION_THRESHOLD) continue;\n\n for (const sub of subdirs) {\n if (isMentioned(combinedDocs, sub)) continue;\n const count = await countSourceFiles(path.join(absTop, sub));\n if (count >= SECOND_LEVEL_MIN_SOURCE_FILES) {\n candidates.push({ dir: `${topDir}/${sub}`, sourceFileCount: count });\n }\n }\n }\n\n return candidates;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CountClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MEMBERS_CAP = 50;\n\ninterface CountSource {\n actual: number;\n countedFrom: string;\n members: string[];\n}\n\nasync function readIfExists(absPath: string): Promise<string | null> {\n try {\n return await fs.readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readIfExists(path.join(root, name));\n if (content === null) continue;\n // include(\":a\", \":b\") — count quoted project strings, not include() calls.\n const members: string[] = [];\n for (const call of content.matchAll(/include\\s*\\(([^)]*)\\)/g)) {\n for (const proj of call[1].matchAll(/[\"']([^\"']+)[\"']/g)) {\n members.push(proj[1]);\n }\n }\n if (members.length === 0) return null;\n return { actual: members.length, countedFrom: name, members };\n }\n return null;\n}\n\nasync function countNpmWorkspaces(root: string): Promise<CountSource | null> {\n const pkgRaw = await readIfExists(path.join(root, \"package.json\"));\n if (pkgRaw !== null) {\n try {\n const pkg = JSON.parse(pkgRaw);\n const globs: string[] = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n } catch {\n // Malformed package.json — nothing provable here.\n }\n }\n\n const pnpmRaw = await readIfExists(path.join(root, \"pnpm-workspace.yaml\"));\n if (pnpmRaw !== null) {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of pnpmRaw.split(\"\\n\")) {\n if (/^packages\\s*:/.test(line)) {\n inPackages = true;\n continue;\n }\n if (inPackages) {\n const entry = line.match(/^\\s*-\\s*[\"']?([^\"'#\\s]+)/);\n if (entry) {\n if (!entry[1].startsWith(\"!\")) globs.push(entry[1]);\n } else if (line.trim().length > 0 && !line.startsWith(\" \")) {\n inPackages = false;\n }\n }\n }\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"pnpm-workspace.yaml\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n return null;\n}\n\nasync function countCargoCrates(root: string): Promise<CountSource | null> {\n const content = await readIfExists(path.join(root, \"Cargo.toml\"));\n if (content === null) return null;\n const membersBlock = content.match(/members\\s*=\\s*\\[([\\s\\S]*?)\\]/);\n if (!membersBlock) return null;\n const entries = [...membersBlock[1].matchAll(/[\"']([^\"']+)[\"']/g)].map(\n (m) => m[1]\n );\n if (entries.length === 0) return null;\n\n // Workspace members may be globs (\"crates/*\") — resolve them against\n // directories that actually contain a Cargo.toml.\n const members = new Set<string>();\n for (const entry of entries) {\n if (/[*?[\\]{}]/.test(entry)) {\n const matched = await fg(`${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n cwd: root,\n ignore: [\"**/target/**\"],\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readIfExists(path.join(root, entry, \"Cargo.toml\"))) !== null\n ) {\n members.add(entry);\n }\n }\n if (members.size === 0) return null;\n return {\n actual: members.size,\n countedFrom: \"Cargo.toml workspace members\",\n members: [...members].sort(),\n };\n}\n\n/**\n * Map a claim's unit to the ecosystem that can prove it. When the mapped\n * ecosystem has no workspace manifest in this repo, the claim is skipped —\n * \"12 packages\" in a Gradle repo proves nothing either way.\n */\nexport async function resolveCountSource(\n root: string,\n claim: CountClaim\n): Promise<CountSource | null> {\n const unit = claim.unit.replace(/s$/, \"\");\n if (unit === \"module\") return countGradleModules(root);\n if (unit === \"workspace\") return countNpmWorkspaces(root);\n if (unit === \"crate\") return countCargoCrates(root);\n // \"packages\" is ecosystem-ambiguous — first manifest that resolves wins.\n return (\n (await countNpmWorkspaces(root)) ??\n (await countCargoCrates(root)) ??\n (await countGradleModules(root))\n );\n}\n\nexport async function checkStaleCounts(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n for (const claim of doc.claims.counts) {\n const source = await resolveCountSource(ctx.root, claim);\n if (source === null) {\n result.skipped.push({ check: \"stale-count\", doc: doc.path,\n reason: `${doc.path}: cannot resolve a workspace manifest for \"${claim.excerpt}\"` });\n continue;\n }\n if (source.actual === claim.count) continue;\n result.issues.push({\n type: \"stale-count\",\n message: `says \"${claim.excerpt}\" but ${source.countedFrom} resolves to ${source.actual}`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"count-mismatch\",\n claimed: claim.count,\n actual: source.actual,\n unit: claim.unit,\n countedFrom: source.countedFrom,\n members: source.members.slice(0, MEMBERS_CAP),\n },\n });\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\n\nasync function scriptsOf(absManifest: string): Promise<string[] | null> {\n try {\n const pkg = JSON.parse(await fs.readFile(absManifest, \"utf-8\"));\n return pkg && typeof pkg.scripts === \"object\" && pkg.scripts !== null\n ? Object.keys(pkg.scripts)\n : [];\n } catch {\n return null;\n }\n}\n\n/**\n * `npm run <script>` claims checked against package.json scripts — the one\n * ecosystem where task discovery is a single JSON parse. A script missing\n * from the root manifest is searched in every workspace manifest before\n * being flagged; docs legitimately say \"in packages/foo run `npm run build`\".\n */\nexport async function checkDeadCommands(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n const commandClaims = ctx.docs.flatMap((doc) =>\n doc.claims.commands.map((claim) => ({ doc, claim }))\n );\n if (commandClaims.length === 0) return result;\n\n const rootScripts = await scriptsOf(path.join(ctx.root, \"package.json\"));\n if (rootScripts === null) {\n result.skipped.push({\n check: \"dead-command\",\n reason: \"no package.json at the repo root\",\n });\n return result;\n }\n const rootSet = new Set(rootScripts);\n\n let workspaceScripts: Set<string> | null = null;\n let manifestsChecked: string[] = [\"package.json\"];\n const loadWorkspaceScripts = async (): Promise<Set<string>> => {\n if (workspaceScripts !== null) return workspaceScripts;\n workspaceScripts = new Set<string>();\n const manifests = await commandManifests(ctx.root);\n manifestsChecked = [\"package.json\", ...manifests.sort()];\n for (const manifest of manifests) {\n const scripts = await scriptsOf(path.join(ctx.root, manifest));\n for (const name of scripts ?? []) workspaceScripts.add(name);\n }\n return workspaceScripts;\n };\n\n for (const { doc, claim } of commandClaims) {\n if (rootSet.has(claim.scriptName)) continue;\n const elsewhere = await loadWorkspaceScripts();\n if (elsewhere.has(claim.scriptName)) continue;\n\n result.issues.push({\n type: \"dead-command\",\n message: `\\`${claim.invocation}\\` refers to script \"${claim.scriptName}\", which exists in no package.json`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"missing-script\",\n scriptName: claim.scriptName,\n invocation: claim.invocation,\n manifestsChecked,\n availableScripts: rootScripts.slice(0, AVAILABLE_SCRIPTS_CAP),\n },\n });\n }\n\n return result;\n}\n\n/** Shared with automation so ignored workspace manifests remain cache dependencies. */\nexport function commandManifests(root: string): Promise<string[]> {\n return fg(\"**/package.json\", { cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \".mason/reports/**\", \"package.json\"] });\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { RangeCommits } from \"./git.js\";\n\nconst exec = promisify(execFile);\nasync function git(root: string, args: string[]) {\n return (await exec(\"git\", args, { cwd: root, timeout: 10000, maxBuffer: 2 * 1024 * 1024 })).stdout;\n}\n\n/** A deliberately narrow recognizer, not a Gradle evaluator. Unknown syntax stays advisory. */\nfunction withoutAndroidReleaseValues(text: string): string | null {\n if (/\\/\\*|\"\"\"|'''/.test(text) || !/id\\s*\\(?\\s*[\"']com\\.android\\.(application|library)[\"']/.test(text)) return null;\n const scopes: string[] = [];\n const normalized: string[] = [];\n let assignments = 0;\n for (const line of text.split(\"\\n\")) {\n // Remove ordinary quoted strings and line comments solely for brace tracking.\n const code = line.replace(/\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|\\/\\/.*$/g, token => token.startsWith(\"//\") ? \"\" : '\"\"');\n const assignment = line.match(/^(\\s*)(versionName|versionCode)(\\s*(?:=\\s*|\\s+))(\"[A-Za-z0-9._+-]+\"|'[A-Za-z0-9._+-]+'|\\d+)(\\s*)$/);\n if (assignment && scopes.join(\"/\") === \"android/defaultConfig\" &&\n (assignment[2] === \"versionCode\" ? /^\\d+$/.test(assignment[4]) : /^[\"']/.test(assignment[4]))) {\n normalized.push(assignment[1] + assignment[2] + assignment[3] + \"<release-value>\" + assignment[5]);\n assignments++;\n } else {\n // References can feed dependency coordinates or other executable configuration.\n if (/\\bversion(?:Name|Code)\\b/.test(line)) return null;\n normalized.push(line);\n }\n const named = code.match(/^\\s*(android|defaultConfig)\\s*\\{\\s*$/)?.[1];\n for (const brace of code.matchAll(/[{}]/g)) {\n if (brace[0] === \"{\") scopes.push(named ?? \"unknown\");\n else if (!scopes.length) return null;\n else scopes.pop();\n }\n }\n return assignments && !scopes.length ? normalized.join(\"\\n\") : null;\n}\n\n/** Only omit single-parent commits whose every touched manifest is proven release metadata. */\nexport async function releaseMetadataOnly(root: string, commit: RangeCommits[\"commits\"][number]): Promise<boolean> {\n if (!commit.files.length || !commit.files.every(file => /(^|\\/)build\\.gradle(?:\\.kts)?$/.test(file))) return false;\n try {\n const parents = (await git(root, [\"rev-list\", \"--parents\", \"-n\", \"1\", commit.hash])).trim().split(/\\s+/);\n if (parents.length !== 2) return false;\n for (const file of commit.files) {\n const raw = await git(root, [\"diff\", \"--raw\", \"-z\", \"--no-renames\", \"--no-ext-diff\", \"--no-textconv\", parents[1], commit.hash, \"--\", file]);\n if (!/^:(100644|100755) \\1 [a-f0-9]+ [a-f0-9]+ M\\0/.test(raw)) return false;\n const [before, after] = await Promise.all([\n git(root, [\"show\", parents[1] + \":\" + file]), git(root, [\"show\", commit.hash + \":\" + file]),\n ]);\n const previous = withoutAndroidReleaseValues(before);\n if (previous === null || previous !== withoutAndroidReleaseValues(after)) return false;\n }\n return true;\n } catch { return false; }\n}\n","import { releaseMetadataOnly } from \"../release-metadata.js\";\nimport { commitsTouchingSince } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MANIFEST_COMMITS_CAP = 10;\n\n/**\n * Tracked manifest files at any depth. Lockfiles are pure churn and are\n * deliberately not matched.\n */\nconst MANIFEST_PATHSPECS = [\n \":(glob)**/package.json\",\n \":(glob)**/build.gradle.kts\",\n \":(glob)**/build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \":(glob)**/Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n];\n\n/**\n * Advisory, never an issue: a manifest commit after the doc's last commit\n * proves recency ordering, not that any specific claim is false — and it can\n * never be closed by editing the doc within the same run.\n */\nexport async function checkDepsChanged(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n result.suppressedAdvisories = [];\n const releaseOnly = new Map<string, boolean>();\n\n for (const doc of ctx.docs) {\n if (!doc.lastCommit) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has no commit history`,\n });\n continue;\n }\n if (doc.dirty) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has uncommitted edits – suppressed while in flight`,\n });\n }\n\n const range = await commitsTouchingSince(\n ctx.root,\n doc.lastCommit.hash,\n MANIFEST_PATHSPECS\n );\n if (range === null) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path}: commit range unreachable (shallow clone?)`,\n });\n continue;\n }\n // Bound extra history reads. Older/ambiguous commits remain advisory.\n const relevant = [];\n for (const commit of range.commits) {\n if (!releaseOnly.has(commit.hash) && releaseOnly.size < 100) {\n releaseOnly.set(commit.hash, await releaseMetadataOnly(ctx.root, commit));\n }\n if (!releaseOnly.get(commit.hash)) relevant.push(commit);\n }\n range.commits = relevant;\n range.total = relevant.length;\n if (range.total === 0) continue;\n\n const latest = range.commits[0];\n (doc.dirty ? result.suppressedAdvisories : result.advisories).push({\n type: \"deps-changed\",\n message: `dependency manifests touched by ${range.total} commit${range.total === 1 ? \"\" : \"s\"} since ${doc.path} was last committed (latest: ${latest.hash.slice(0, 7)} \"${latest.subject}\")`,\n anchor: { doc: doc.path, line: null, excerpt: null },\n evidence: {\n kind: \"doc-behind-manifests\",\n docLastCommit: doc.lastCommit,\n manifestCommits: range.commits.slice(0, MANIFEST_COMMITS_CAP),\n totalCommits: range.total,\n },\n });\n }\n\n return result;\n}\n","import path from \"node:path\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { loadDecisionStore } from \"./decisions.js\";\nimport type { DecisionRecord } from \"./decisions.js\";\nimport { effectiveDecision } from \"./provenance.js\";\n\n/**\n * Deliberately separate from DriftReport: mason-drift's exit codes and\n * --json shape are a CI contract, and `stale` there means MAP staleness.\n * Decision staleness is additive on top.\n */\nexport interface DecisionDriftReport {\n historyAvailable: boolean;\n freshness?: Record<string, Freshness>;\n diagnostics?: StoreDiagnostic[];\n totalDecisions: number;\n /** Decision id → anchor files changed since the record's refreshedHash. */\n staleDecisions: Record<string, string[]>;\n /** Draft anchors have their own freshness; they cannot replace accepted anchors. */\n pendingProposals?: Record<string, { freshness: Freshness; changedFiles: string[] }>;\n}\n\n/**\n * Flag active decisions whose anchor files changed since the record was\n * last verified. Anchorless decisions have unknown freshness and do not\n * contribute to committed drift.\n * Deterministic — git only, no LLM.\n */\nexport async function computeDecisionDrift(\n rootDir: string,\n decisions?: DecisionRecord[]\n): Promise<DecisionDriftReport> {\n const resolvedRoot = path.resolve(rootDir);\n const store = decisions ? { records: decisions, diagnostics: [] } : await loadDecisionStore(resolvedRoot);\n const report: DecisionDriftReport = { historyAvailable: true, totalDecisions: store.records.length, staleDecisions: {}, freshness: {}, diagnostics: store.diagnostics };\n const [head, workingTree] = await Promise.all([getCurrentGitHash(resolvedRoot), getWorkingTree(resolvedRoot)]);\n const changesByHash = new Map<string, string[] | null>();\n const inspect = async (record: DecisionRecord): Promise<{ freshness: Freshness; changedFiles: string[] }> => {\n if (record.files.length === 0) return { freshness: \"unknown\", changedFiles: [] };\n let touched = changesByHash.get(record.refreshedHash);\n if (touched === undefined) {\n const changes = record.refreshedHash === head && head !== \"unknown\" ? [] : await getChangesWithStatus(resolvedRoot, record.refreshedHash);\n touched = changes === null ? null : touchedPaths(changes);\n changesByHash.set(record.refreshedHash, touched);\n }\n if (touched === null) report.historyAvailable = false;\n const hits = touched ? matchingPaths(record.files, touched) : [];\n const localHits = matchingPaths(record.files, workingTree.changedFiles);\n return { freshness: touched === null || !workingTree.available ? \"unknown\" : hits.length || localHits.length ? \"changed\" : \"current\", changedFiles: hits };\n };\n for (const record of store.records) {\n if (record.status !== \"active\") continue;\n const effective = effectiveDecision(record);\n const state = await inspect(effective);\n report.freshness![record.id] = state.freshness;\n if (state.changedFiles.length) report.staleDecisions[record.id] = state.changedFiles;\n if (effective !== record) (report.pendingProposals ??= {})[record.id] = await inspect(record);\n }\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { readStoreJson, writeStoreJson, storePath, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { jaccard, tokenSet } from \"../context/lexical.js\";\nimport { attributionSchema, decisionSchema, decisionContent, decisionApproval, effectiveDecision, importLegacy, type DecisionSource, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nexport type { DecisionRecord } from \"./provenance.js\";\n\nexport type DecisionCategory =\n | \"decision\"\n | \"gotcha\"\n | \"deprecation\"\n | \"convention\";\nexport type DecisionStatus = \"active\" | \"superseded\" | \"retired\";\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\nexport async function loadDecisionStore(rootDir: string): Promise<{ records: DecisionRecord[]; diagnostics: StoreDiagnostic[] }> {\n const records: DecisionRecord[] = [];\n const diagnostics: StoreDiagnostic[] = [];\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, \".mason/decisions\")); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") diagnostics.push({ path: \".mason/decisions\", message: String(error) });\n return { records, diagnostics };\n }\n for (const entry of entries.sort()) {\n if (!entry.endsWith(\".json\")) continue;\n const relative = `.mason/decisions/${entry}`;\n try {\n const record = decisionSchema.parse(await readStoreJson(rootDir, relative));\n if (entry !== `${record.id}.json`) throw new Error(\"Record id does not match its filename\");\n records.push(record);\n } catch (error) { diagnostics.push({ path: relative, message: error instanceof Error ? error.message : String(error) }); }\n }\n return { records, diagnostics };\n}\n\nexport async function loadDecisions(rootDir: string): Promise<DecisionRecord[]> {\n return (await loadDecisionStore(rootDir)).records;\n}\n\nexport async function saveDecisionRecord(rootDir: string, record: DecisionRecord): Promise<void> {\n const validated = decisionSchema.parse(record);\n await writeStoreJson(rootDir, `.mason/decisions/${validated.id}.json`, validated);\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\nexport interface UpsertDecisionInput {\n title: string;\n body: string;\n category: DecisionCategory;\n files?: string[];\n owner?: string | null;\n sources?: DecisionSource[];\n /** Only supply a known identity; never infer authorship from Git configuration. */\n actor?: string;\n /** Existing id to revise. Unchanged content is a no-op; use review_decision to reaffirm. */\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\" | \"unchanged\" | \"superseded_and_created\";\n id: string;\n totalActive: number;\n warnings: string[];\n approval?: \"unreviewed\" | \"proposed\" | \"accepted\";\n hint?: string;\n pruneCandidates?: string[];\n }\n | { status: \"duplicate_suspected\"; existing: DecisionRecord; hint: string }\n | { status: \"error\"; error: string };\n\n/** Serialize tool writes so prepared reviews cannot overwrite another decision edit. */\nexport async function withDecisionWrite<T>(root: string, operation: () => Promise<T>): Promise<T | { status: \"error\"; error: string }> {\n const lockPath = await storePath(root, \".mason/decisions/.write-lock\", true);\n let lock;\n try { lock = await fs.open(lockPath, \"wx\", 0o600); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return { status: \"error\", error: \"Decision store is locked by another write. Retry after it finishes; an abandoned .mason/decisions/.write-lock must be removed only after confirming no writer is running.\" };\n throw error;\n }\n try { return await operation(); }\n finally { await lock.close(); await fs.unlink(lockPath); }\n}\n\nexport async function upsertDecision(rootDir: string, input: UpsertDecisionInput): Promise<UpsertDecisionResult> {\n const title = input.title.trim(), body = input.body.trim();\n if (!title || !body) return { status: \"error\", error: \"title and body must be non-empty\" };\n if (title.length > TITLE_MAX_CHARS) return { status: \"error\", error: `title exceeds ${TITLE_MAX_CHARS} chars — tighten it to a specific headline` };\n if (body.length > BODY_MAX_CHARS) return { status: \"error\", error: `body exceeds ${BODY_MAX_CHARS} chars — record the decision, not the transcript` };\n const attribution = attributionSchema.safeParse(input);\n if (!attribution.success) return { status: \"error\", error: attribution.error.message };\n if (input.id && input.supersedes) return { status: \"error\", error: \"Use either id to revise or supersedes to replace a record, not both.\" };\n return withDecisionWrite(rootDir, async () => {\n const store = await loadDecisionStore(rootDir);\n if (store.diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before saving: \" + store.diagnostics.map(d => d.path).join(\", \") };\n const existing = store.records, byId = new Map(existing.map(r => [r.id, r]));\n const now = new Date().toISOString(), head = await getCurrentGitHash(rootDir);\n const warnings: string[] = [];\n const files = sanitizeRepoPaths(input.files ?? []);\n if (input.files && files.length < input.files.length) warnings.push(\"some anchor paths were outside the repo or duplicated and were dropped\");\n for (const file of files) {\n try { await fs.access(path.join(rootDir, file)); }\n catch { warnings.push(`anchor file does not exist on disk: ${file}`); }\n }\n const hint = \"Saved locally for review and commit. Proposals are not accepted constraints; an existing accepted revision remains operative while its replacement is proposed. Use review_decision to inspect evidence and record an authorized acceptance or reaffirmation.\";\n if (input.id) {\n const original = byId.get(input.id);\n if (!original) return { status: \"error\", error: `no decision with id \"${input.id}\"` };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived records cannot be revised; create a new proposal.\" };\n const record = importLegacy(original, now);\n const content = decisionContent({ ...record, title, body, category: input.category,\n files: input.files !== undefined ? files : record.files,\n owner: attribution.data.owner === undefined ? record.owner : attribution.data.owner ?? undefined,\n sources: attribution.data.sources ?? record.sources,\n });\n if (JSON.stringify(content) === JSON.stringify(decisionContent(record))) {\n return { status: \"unchanged\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: decisionApproval(original), warnings,\n hint: \"Unchanged content; no review or freshness stamp was written. Use review_decision for explicit re-verification.\" };\n }\n const revision = record.revision + 1;\n const updated: ReviewedDecisionRecord = { ...record, ...content, owner: content.owner, updatedAt: now, revision, approval: \"proposed\",\n history: [...record.history, { kind: \"revised\", at: now, actor: attribution.data.actor, revision, content, approval: \"proposed\", status: \"active\", refreshedHash: record.refreshedHash }],\n };\n await saveDecisionRecord(rootDir, updated);\n return { status: \"updated\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: \"proposed\", warnings, hint };\n }\n const old = input.supersedes ? byId.get(input.supersedes) : undefined;\n if (input.supersedes && !old) return { status: \"error\", error: `no decision with id \"${input.supersedes}\" to supersede` };\n if (old && (old.status !== \"active\" || decisionApproval(effectiveDecision(old)) === \"accepted\")) {\n return { status: \"error\", error: \"A proposal cannot supersede an accepted or archived record. Create and review the replacement separately, then explicitly retire the old decision with review_decision.\" };\n }\n if (!input.force) {\n const duplicate = findNearDuplicate({ title, body, files }, existing);\n if (duplicate) return { status: \"duplicate_suspected\", existing: duplicate.record, hint: `A similar decision exists (\"${duplicate.record.title}\"). Call save_decision with id=\"${duplicate.record.id}\" to revise it, or force:true if distinct.` };\n }\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n if (byId.has(id)) return { status: \"error\", error: `Decision id collision: ${id}. Choose a distinct title or revise the existing record.` };\n const content = decisionContent({ title, body, category: input.category, files, owner: attribution.data.owner ?? undefined, sources: attribution.data.sources ?? [] });\n const record: ReviewedDecisionRecord = { ...content, version: 2, id, createdAt: now, updatedAt: now, refreshedHash: head,\n status: \"active\", approval: \"proposed\", revision: 1,\n history: [{ kind: \"created\", at: now, actor: attribution.data.actor, revision: 1, content, approval: \"proposed\", status: \"active\", refreshedHash: head }],\n };\n // Write the replacement first: a failed second write leaves both records\n // available instead of removing the original before its replacement exists.\n await saveDecisionRecord(rootDir, record);\n if (old) {\n const imported = importLegacy(old, now);\n await saveDecisionRecord(rootDir, { ...imported, status: \"superseded\", supersededBy: id, updatedAt: now,\n history: [...imported.history, { kind: \"superseded\", at: now, actor: attribution.data.actor, note: `Replaced by proposal ${id}`,\n revision: imported.revision, content: decisionContent(imported), approval: imported.approval, status: \"superseded\", refreshedHash: imported.refreshedHash }],\n });\n }\n const totalActive = existing.filter(r => r.status === \"active\").length + (old ? 0 : 1);\n const result: UpsertDecisionResult = { status: old ? \"superseded_and_created\" : \"created\", id, totalActive, approval: \"proposed\", warnings, hint };\n if (totalActive > MAX_ACTIVE_DECISIONS) {\n result.pruneCandidates = existing.filter(r => r.status !== \"active\").map(r => r.id).slice(0, 10);\n warnings.push(`${totalActive} active decisions exceeds the soft cap of ${MAX_ACTIVE_DECISIONS} — consider a cleanup PR (archived records first)`);\n }\n return result;\n });\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 { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { assessTrust, type Freshness } from \"../context/trust.js\";\n\nconst text = (max: number) => z.string().trim().min(1).max(max);\nexport const decisionSourceSchema = z.object({\n kind: z.enum([\"pull_request\", \"issue\", \"incident\", \"discussion\", \"document\", \"other\"]),\n reference: text(1000),\n note: text(500).optional(),\n}).strict();\nexport type DecisionSource = z.infer<typeof decisionSourceSchema>;\nexport const attributionSchema = z.object({\n owner: text(200).nullable().optional(),\n sources: z.array(decisionSourceSchema).max(20).optional(),\n actor: text(200).optional(),\n});\nconst contentSchema = z.object({\n title: z.string().min(1), body: z.string().min(1),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z.array(z.string().refine(f => normalizeRepoPath(f) !== null)),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n});\nconst approvalSchema = z.enum([\"unreviewed\", \"proposed\", \"accepted\"]);\nconst statusSchema = z.enum([\"active\", \"superseded\", \"retired\"]);\nexport const reviewEvidenceSchema = z.object({\n baseHash: z.string(), headHash: z.string(), historyAvailable: z.boolean(),\n changedFiles: z.array(z.string()), localChanges: z.array(z.string()),\n});\nconst eventSchema = z.object({\n kind: z.enum([\"imported\", \"created\", \"revised\", \"accepted\", \"reaffirmed\", \"retired\", \"superseded\"]),\n at: z.string().datetime(), actor: text(200).optional(), note: text(1500).optional(),\n revision: z.number().int().positive(), content: contentSchema,\n approval: approvalSchema, status: statusSchema, refreshedHash: z.string(),\n evidence: reviewEvidenceSchema.optional(),\n});\nexport type DecisionEvent = z.infer<typeof eventSchema>;\nexport type DecisionApproval = z.infer<typeof approvalSchema>;\nexport type DecisionContent = z.infer<typeof contentSchema>;\n\nconst legacySchema = z.object({\n version: z.literal(1), id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n title: z.string().min(1), body: z.string().min(1),\n category: contentSchema.shape.category, files: contentSchema.shape.files,\n createdAt: z.string(), updatedAt: z.string(), refreshedHash: z.string(),\n status: z.enum([\"active\", \"superseded\"]), supersededBy: z.string().optional(),\n}).passthrough();\nconst currentSchema = legacySchema.extend({\n version: z.literal(2), status: statusSchema,\n approval: approvalSchema, revision: z.number().int().positive(),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n history: z.array(eventSchema).min(1),\n}).superRefine((record, ctx) => {\n const invalid = (message: string) => ctx.addIssue({ code: \"custom\", message });\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n let previous: DecisionEvent | undefined;\n for (const event of record.history) {\n if (!previous) {\n if (![\"created\", \"imported\"].includes(event.kind) || event.revision !== 1) invalid(\"History must begin with creation or legacy import at revision 1\");\n if (event.approval !== (event.kind === \"created\" ? \"proposed\" : \"unreviewed\")) invalid(\"Initial records cannot claim acceptance\");\n } else {\n if ([\"created\", \"imported\"].includes(event.kind)) invalid(\"History cannot restart\");\n if (previous.status !== \"active\") invalid(\"Archived decisions cannot be changed\");\n if (event.revision !== previous.revision + (event.kind === \"revised\" ? 1 : 0)) invalid(\"Invalid revision sequence\");\n if (event.kind !== \"revised\" && !same(event.content, previous.content)) invalid(\"A review cannot silently revise decision content\");\n if (event.kind === \"reaffirmed\" && previous.approval !== \"accepted\") invalid(\"Only accepted decisions can be reaffirmed\");\n if (event.kind === \"accepted\" && previous.approval === \"accepted\") invalid(\"Use reaffirmation for an accepted decision\");\n const approval = event.kind === \"revised\" ? \"proposed\" : [\"accepted\", \"reaffirmed\"].includes(event.kind) ? \"accepted\" : previous.approval;\n if (event.approval !== approval) invalid(\"Approval disagrees with review history\");\n if (![\"accepted\", \"reaffirmed\"].includes(event.kind) && event.refreshedHash !== previous.refreshedHash) invalid(\"Only a review can refresh the evidence baseline\");\n }\n if (event.kind !== \"imported\" && event.status !== (event.kind === \"retired\" ? \"retired\" : event.kind === \"superseded\" ? \"superseded\" : \"active\")) invalid(\"Lifecycle disagrees with history\");\n if ([\"accepted\", \"reaffirmed\", \"retired\"].includes(event.kind) && (!event.actor || !event.note || !event.evidence)) invalid(\"Reviews require a named reviewer, reason, and code evidence\");\n if ([\"accepted\", \"reaffirmed\"].includes(event.kind)) {\n if (!event.content.owner || !event.content.sources.length) invalid(\"Accepted decisions require an owner and source\");\n if (!event.evidence || !/^[a-f0-9]{40,64}$/.test(event.evidence.headHash) || event.refreshedHash !== event.evidence.headHash || event.evidence.localChanges.length) invalid(\"Acceptance requires a committed evidence baseline\");\n }\n previous = event;\n }\n if (!previous || !same(previous.content, decisionContent(record)) || previous.approval !== record.approval || previous.status !== record.status || previous.revision !== record.revision || previous.refreshedHash !== record.refreshedHash) invalid(\"Decision does not match the final history event\");\n});\n\nexport const decisionSchema = z.union([legacySchema, currentSchema]);\nexport type DecisionRecord = z.infer<typeof decisionSchema>;\nexport type ReviewedDecisionRecord = z.infer<typeof currentSchema>;\n\nexport function decisionContent(record: Pick<DecisionRecord, \"title\" | \"body\" | \"category\" | \"files\"> & { owner?: unknown; sources?: unknown }): DecisionContent {\n return { title: record.title, body: record.body, category: record.category, files: record.files,\n ...(typeof record.owner === \"string\" ? { owner: record.owner } : {}),\n sources: Array.isArray(record.sources) ? record.sources as DecisionSource[] : [],\n };\n}\n\n/** Reading legacy records never upgrades their approval or rewrites their files. */\nexport function decisionApproval(record: DecisionRecord): DecisionApproval {\n return record.version === 1 ? \"unreviewed\" : record.approval;\n}\n\n/** The last accepted revision remains operative while a replacement is drafted.\n * This is a read-only projection; writes and review tokens use the complete record.\n * Archived records never regain authority from their history.\n */\nexport function effectiveDecision(record: DecisionRecord): DecisionRecord {\n if (record.version !== 2 || record.status !== \"active\" || record.approval !== \"proposed\") return record;\n let index = record.history.length - 1;\n while (index >= 0 && ![\"accepted\", \"reaffirmed\"].includes(record.history[index].kind)) index--;\n if (index < 0) return record;\n const event = record.history[index];\n return { ...record, ...event.content, owner: event.content.owner, approval: \"accepted\", revision: event.revision,\n refreshedHash: event.refreshedHash, updatedAt: event.at, history: record.history.slice(0, index + 1) };\n}\n\n/** Anchors relevant to either the operative knowledge or its pending proposal. */\nexport function decisionAnchors(record: DecisionRecord): string[] {\n return [...new Set([...effectiveDecision(record).files, ...record.files])];\n}\n\nexport function importLegacy(record: DecisionRecord, now: string): ReviewedDecisionRecord {\n if (record.version === 2) return record;\n // Ignore unrecognized legacy fields: they are not evidence of authorship or approval.\n const content = decisionContent({ title: record.title, body: record.body, category: record.category, files: record.files });\n return { id: record.id, createdAt: record.createdAt, updatedAt: record.updatedAt, status: record.status, refreshedHash: record.refreshedHash, supersededBy: record.supersededBy, ...content, version: 2, approval: \"unreviewed\", revision: 1,\n history: [{ kind: \"imported\", at: now, revision: 1, content, approval: \"unreviewed\", status: record.status, refreshedHash: record.refreshedHash,\n note: \"Imported a legacy record. Prior authorship and review history are unknown.\" }],\n };\n}\n\nexport function decisionProvenance(record: DecisionRecord, freshness: Freshness = \"unknown\") {\n const approval = decisionApproval(record);\n const review = record.version === 2 ? [...record.history].reverse().find(e => [\"accepted\", \"reaffirmed\"].includes(e.kind) && e.revision === record.revision) : undefined;\n return {\n approval, revision: record.version === 2 ? record.revision : 0,\n owner: record.version === 2 ? record.owner ?? null : null,\n sources: record.version === 2 ? record.sources : [],\n guidance: record.status !== \"active\" ? \"historical\" : approval === \"accepted\" ? \"constraint\" : approval === \"proposed\" ? \"proposal\" : \"unreviewed\",\n reviewRequired: record.status === \"active\" && (approval !== \"accepted\" || freshness !== \"current\"),\n lastReview: review ? { reviewer: review.actor!, at: review.at, note: review.note!, gitHash: review.refreshedHash } : null,\n };\n}\n\nexport function decisionTrust(record: DecisionRecord, freshness: Freshness) {\n const review = decisionProvenance(record, freshness).lastReview;\n return assessTrust(review ? { verifiedAt: review.at, verifiedHash: review.gitHash } : {}, freshness);\n}\n\nfunction revisionKnowledge(record: DecisionRecord, freshness: Freshness) {\n return { ...decisionContent(record), ...decisionProvenance(record, freshness), trust: decisionTrust(record, freshness) };\n}\n\n/** Readers show accepted content first and label the unaccepted draft separately. */\nexport function decisionKnowledge(record: DecisionRecord, freshness: Freshness = \"unknown\", proposalFreshness: Freshness = \"unknown\") {\n const effective = effectiveDecision(record);\n return { ...revisionKnowledge(effective, freshness),\n ...(effective !== record ? { pendingProposal: revisionKnowledge(record, proposalFreshness) } : {}) };\n}\n\nexport function compactDecisionKnowledge(...args: Parameters<typeof decisionKnowledge>) {\n const { body, pendingProposal, ...summary } = decisionKnowledge(...args);\n if (!pendingProposal) return summary;\n const { body: proposalBody, ...proposal } = pendingProposal;\n return { ...summary, pendingProposal: proposal };\n}\n\nexport const DECISION_GUIDANCE = \"Accepted decisions are recorded team constraints, subject to freshness checks. A pendingProposal is an unaccepted replacement; the accepted revision remains operative until explicit acceptance or retirement. Proposals are suggestions; legacy unreviewed records need confirmation. Use review_decision to inspect provenance and record an authorized review; identities and sources are recorded assertions, not authenticated proof.\";\n","import { computeDecisionDrift } from \"../../decisions/drift.js\";\nimport { loadDecisionStore } from \"../../decisions/decisions.js\";\nimport { decisionProvenance, effectiveDecision } from \"../../decisions/provenance.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/**\n * Advisory only, and only when .mason/decisions/ exists (the zero-setup\n * path stays dark on bare repos). Decision records encode human knowledge —\n * they are surfaced for re-verification, never rewritten by the fix agent.\n */\nexport async function checkDecisionAnchors(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n if (!ctx.decisionsPresent) return result;\n\n const store = await loadDecisionStore(ctx.root);\n const records = store.records;\n for (const diagnostic of store.diagnostics) result.skipped.push({ check: \"decision-anchor-drift\", reason: `${diagnostic.path}: ${diagnostic.message}` });\n const drift = await computeDecisionDrift(ctx.root, records);\n if (!drift.historyAvailable) {\n result.skipped.push({\n check: \"decision-anchor-drift\",\n reason: \"some decision base commits are unreachable (shallow clone?)\",\n });\n }\n\n const changed = records.flatMap(record => [\n { record: effectiveDecision(record), changedFiles: drift.staleDecisions[record.id] ?? [], freshness: drift.freshness?.[record.id] ?? \"unknown\" },\n { record, changedFiles: drift.pendingProposals?.[record.id]?.changedFiles ?? [], freshness: drift.pendingProposals?.[record.id]?.freshness ?? \"unknown\" },\n ] as const);\n for (const { record, changedFiles, freshness } of changed) {\n if (!changedFiles.length) continue;\n const id = record.id;\n const provenance = decisionProvenance(record, freshness);\n result.advisories.push({\n type: \"decision-anchor-drift\",\n message: `decision \"${record.title}\" (${provenance.approval}) has anchor files that changed since its evidence baseline – needs human review`,\n anchor: {\n doc: `.mason/decisions/${id}.json`,\n line: null,\n excerpt: record.title,\n },\n evidence: {\n kind: \"decision-anchor\",\n provenance,\n decisionId: id,\n title: record.title,\n changedFiles,\n refreshedHash: record.refreshedHash,\n },\n });\n }\n\n return result;\n}\n","import type { FileChange } from \"../../drift/drift.js\";\nimport type { AuditAdvisory, AuditIssue, CheckName } from \"../types.js\";\nimport type { AuditDoc } from \"../docs.js\";\nimport { checkDeletedReferences } from \"./deleted-reference.js\";\nimport { checkNewModules } from \"./new-module.js\";\nimport { checkStaleCounts } from \"./stale-count.js\";\nimport { checkDeadCommands } from \"./dead-command.js\";\nimport { checkDepsChanged } from \"./deps-changed.js\";\nimport { checkDecisionAnchors } from \"./decision-anchor.js\";\n\nexport interface CheckContext {\n root: string;\n docs: AuditDoc[];\n headHash: string;\n /** Doc path → changes since the doc's last commit; null when uncomputable. */\n changesSinceDoc: Map<string, FileChange[] | null>;\n /** Whether .mason/decisions/ exists. */\n decisionsPresent: boolean;\n}\n\nexport interface CheckResult {\n issues: AuditIssue[];\n advisories: AuditAdvisory[];\n suppressedAdvisories?: AuditAdvisory[];\n skipped: Array<{ check: string; reason: string; doc?: string }>;\n}\n\nexport type CheckFn = (ctx: CheckContext) => Promise<CheckResult>;\n\nexport const CHECKS: Record<CheckName, CheckFn> = {\n \"deleted-reference\": checkDeletedReferences,\n \"new-module\": checkNewModules,\n \"stale-count\": checkStaleCounts,\n \"dead-command\": checkDeadCommands,\n \"deps-changed\": checkDepsChanged,\n \"decision-anchor-drift\": checkDecisionAnchors,\n};\n\nexport function emptyResult(): CheckResult {\n return { issues: [], advisories: [], skipped: [] };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit, type AuditOptions } from \"./audit.js\";\nimport { DOC_CANDIDATES } from \"./docs.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { isWithinRoot } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditAdvisory, AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nconst checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nconst commitSchema = z.object({ hash: z.string().regex(/^[a-f0-9]{40,64}$/), date: z.string(), subject: z.string() });\nconst anchorSchema = z.object({ doc: z.string(), line: z.number().int().positive().nullable(), excerpt: z.string().nullable() });\nconst count = z.number().int().nonnegative();\nconst evidenceSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"missing-path\"), claimed: z.string(), renamedTo: z.string().nullable(),\n deletedInCommit: commitSchema.nullable(), everTracked: z.boolean(), parentDirExists: z.boolean() }),\n z.object({ kind: z.literal(\"unmentioned-dir\"), dir: z.string(), sourceFileCount: count,\n firstCommit: commitSchema.nullable(), checkedDocs: z.array(z.string()) }),\n z.object({ kind: z.literal(\"count-mismatch\"), claimed: count, actual: count, unit: z.string(),\n countedFrom: z.string(), members: z.array(z.string()) }),\n z.object({ kind: z.literal(\"missing-script\"), scriptName: z.string(), invocation: z.string(),\n manifestsChecked: z.array(z.string()), availableScripts: z.array(z.string()) }),\n z.object({ kind: z.literal(\"doc-behind-manifests\"), docLastCommit: commitSchema,\n manifestCommits: z.array(commitSchema.extend({ files: z.array(z.string()) })), totalCommits: count }),\n z.object({ kind: z.literal(\"decision-anchor\"), decisionId: z.string(), title: z.string(),\n changedFiles: z.array(z.string()), refreshedHash: z.string(),\n provenance: z.object({}).passthrough().optional() }),\n]);\nconst findingSchema = z.object({ message: z.string(), anchor: anchorSchema, evidence: evidenceSchema });\nconst issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nconst advisorySchema = findingSchema.extend({ type: z.enum([\"deps-changed\", \"decision-anchor-drift\"]) });\nexport const checkResultSchema = z.object({\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skipped: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst reportSchema = z.object({\n version: z.literal(1), root: z.string(), gitAvailable: z.literal(true),\n headHash: commitSchema.shape.hash, checksRun: z.array(checkSchema).nonempty(),\n docs: z.array(z.object({ path: z.enum(DOC_CANDIDATES), lastCommit: commitSchema.nullable(),\n dirty: z.boolean(), lineCount: count })).nonempty(),\n decisionsChecked: z.boolean(), clean: z.boolean(),\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skippedChecks: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst baselineSchema = z.object({\n kind: z.literal(\"mason-audit-repair\"), version: z.literal(1),\n createdAt: z.string().datetime(), report: reportSchema, digest: z.string().regex(/^[a-f0-9]{64}$/),\n});\nconst digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\ntype Finding = AuditIssue | AuditAdvisory;\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n}\nexport interface RepairVerification {\n version: 1;\n action: \"verify\";\n baselinePath: string;\n baselineHead: string;\n currentHead: string | null;\n status: \"verified\" | \"issues-remain\" | \"incomplete\";\n findings: RepairFinding[];\n newFindings: Finding[];\n diagnostics: string[];\n currentAudit: AuditReport | null;\n counts: Record<RepairStatus, number>;\n scope: string;\n}\n\n/** Lines and wording can change without changing the underlying claim. */\nexport function findingId(finding: Finding): string {\n const e = finding.evidence;\n let key: unknown;\n switch (e.kind) {\n case \"missing-path\": key = e.claimed; break;\n case \"unmentioned-dir\": key = e.dir; break;\n case \"count-mismatch\": key = [e.unit.replace(/s$/, \"\"), e.countedFrom]; break;\n case \"missing-script\": key = e.scriptName; break;\n case \"doc-behind-manifests\": key = null; break;\n case \"decision-anchor\": key = [e.decisionId, e.provenance?.revision, e.provenance?.approval]; break;\n }\n return digest([finding.type, finding.anchor.doc, key]);\n}\nfunction allFindings(report: AuditReport): Finding[] {\n return [...report.issues, ...report.advisories, ...(report.suppressedAdvisories ?? [])];\n}\n\nasync function docState(root: string): Promise<string> {\n const docs = [];\n for (const doc of DOC_CANDIDATES) {\n try {\n const content = await readBoundedFile(await storePath(root, doc), 10 * 1024 * 1024);\n if (content === null) throw new Error(\"Context file is not regular or exceeds 10 MiB: \" + doc);\n docs.push([doc, digest(content)]);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n docs.push([doc, null]);\n }\n }\n return digest(docs);\n}\n\n/** Refuse a verification assembled across a commit or instruction-file edit. */\nasync function stableAudit(root: string, checks: CheckName[], options: AuditOptions = {}) {\n const head = await getCurrentGitHash(root);\n const before = await docState(root);\n const report = await computeAudit(root, { ...options, checks });\n if (head !== await getCurrentGitHash(root) || before !== await docState(root) ||\n (report && report.headHash !== head)) {\n throw new Error(\"HEAD or context files changed during the audit; retry against a stable checkout.\");\n }\n return report;\n}\n\nexport async function prepareRepair(rootDir: string, checks: CheckName[] = ALL_CHECKS, options: AuditOptions = {}) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await stableAudit(root, selected, options);\n if (!report) throw new Error(\"No context files found to prepare a repair.\");\n if (!report.gitAvailable) throw new Error(\"Readable Git history is required to prepare a repair.\");\n // Canonicalize before hashing; validation on read must yield the same bytes.\n const storedReport = reportSchema.parse(report);\n const payload = { kind: \"mason-audit-repair\" as const, version: 1 as const,\n createdAt: new Date().toISOString(), report: storedReport };\n const baselinePath = \".mason/reports/repairs/\" + randomUUID() + \".json\";\n await writeStoreJson(root, baselinePath, { ...payload, digest: digest(payload) });\n return { version: 1 as const, action: \"prepare\" as const, baselinePath, report };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string, options: AuditOptions = {}): Promise<RepairVerification> {\n const root = await fs.realpath(rootDir);\n const declaredRoot = path.resolve(rootDir);\n const relative = path.isAbsolute(baselinePath)\n ? path.relative(isWithinRoot(declaredRoot, baselinePath) ? declaredRoot : root, baselinePath)\n : baselinePath;\n const stored = baselineSchema.parse(await readStoreJson(root, relative));\n const { digest: savedDigest, ...payload } = stored;\n if (digest(payload) !== savedDigest) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n if (stored.report.root !== root) throw new Error(\"Repair baseline belongs to a different repository.\");\n const original = stored.report as AuditReport;\n const diagnostics: string[] = [];\n let current: AuditReport | null = null;\n try {\n current = await stableAudit(root, original.checksRun!, options);\n if (!current) diagnostics.push(\"No context files remain available to audit.\");\n else if (!current.gitAvailable) diagnostics.push(\"Git history is unavailable.\");\n for (const doc of original.docs) {\n if (!original.issues.some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await readBoundedFile(await storePath(root, doc.path), 10 * 1024 * 1024);\n if (content === null || !content.trim()) {\n diagnostics.push(\"Original context file \" + doc.path + \" is empty or unreadable; losing its claims does not verify a repair.\");\n }\n }\n if (await getChangesWithStatus(root, original.headHash!) === null) {\n diagnostics.push(\"The original audit commit is unavailable; repair history cannot be verified.\");\n }\n } catch (error) {\n diagnostics.push(error instanceof Error ? error.message : String(error));\n }\n const currentById = new Map((current ? allFindings(current) : []).map(f => [findingId(f), f]));\n const originalFindings = allFindings(original);\n const originalIds = new Set(originalFindings.map(findingId));\n const missingDocs = original.docs.filter(doc => !current?.docs.some(d => d.path === doc.path));\n for (const doc of missingDocs) diagnostics.push(\"Original context file \" + doc.path + \" is unavailable; removing it does not verify a repair.\");\n const findings = originalFindings.map((finding): RepairFinding => {\n const id = findingId(finding);\n const now = currentById.get(id);\n const base = { id, original: finding, ...(now ? { current: now } : {}) };\n if (diagnostics.length || !current) {\n return { ...base, status: \"unverified\", reason: \"The original audit scope could not be verified. See diagnostics.\" };\n }\n if (\"confidence\" in finding && now) {\n return { ...base, status: \"unresolved\", reason: \"The original check still reports this claim.\" };\n }\n const skipped = current.skippedChecks.filter(s => s.check === finding.type && (!s.doc || s.doc === finding.anchor.doc));\n if (!current.checksRun?.includes(finding.type) || skipped.length) {\n return { ...base, status: \"unverified\", reason: skipped.map(s => s.reason).join(\"; \") || \"The original check did not run.\" };\n }\n if (!(\"confidence\" in finding)) {\n return { ...base, status: \"review-required\",\n reason: \"An audit cannot establish that this advisory was reviewed. Retain its original evidence and report a separate assessment; editing or committing the doc is not approval.\" };\n }\n return { ...base, status: \"resolved\", reason: \"The original check ran and no longer reports this claim. Inspect the edit for semantic correctness.\" };\n });\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const counts: Record<RepairStatus, number> = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const f of findings) counts[f.status]++;\n const incomplete = diagnostics.length > 0 || counts.unverified > 0 || counts[\"review-required\"] > 0 ||\n (current?.skippedChecks.length ?? 0) > 0 || newFindings.some(f => !(\"confidence\" in f));\n const issuesRemain = counts.unresolved > 0 || newFindings.some(f => \"confidence\" in f);\n return {\n version: 1, action: \"verify\", baselinePath: relative, baselineHead: original.headHash!,\n currentHead: current?.gitAvailable ? current.headHash! : null,\n status: incomplete ? \"incomplete\" : issuesRemain ? \"issues-remain\" : \"verified\",\n findings, newFindings, diagnostics, currentAudit: current, counts,\n scope: \"Original audit checks over current context files and repository evidence. Resolved means no longer detected by that check. Advisories require separate review; this is not a certification of documentation or application correctness.\",\n };\n}\n\nexport function repairExitCode(report: RepairVerification): number {\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n}\n\nexport function formatRepairSummary(report: RepairVerification): string {\n return [\n \"Repair verification: \" + report.status + \". Baseline: \" + report.baselinePath,\n ...report.findings.map(f => \" [\" + f.status + \"] \" + f.original.type + \" \" + f.original.anchor.doc + \": \" + f.original.message + \"\\n \" + f.reason),\n ...report.newFindings.map(f => \" [new] \" + f.type + \" \" + f.anchor.doc + \": \" + f.message),\n ...report.diagnostics.map(d => \" [unverified] \" + d),\n ...(report.currentAudit?.skippedChecks ?? []).map(s => \" [skipped] \" + s.check + \": \" + s.reason),\n report.scope,\n ].join(\"\\n\");\n}\n","import { runAuditCli } from \"../src/audit/cli.js\";\n\nrunAuditCli(process.argv.slice(2)).then(\n (code) => process.exit(code),\n (err) => {\n process.stderr.write(`mason-audit error: ${err}\\n`);\n process.exit(2);\n }\n);\n"],"mappings":";;;AAAA,OAAOA,YAAU;;;ACAjB,OAAOC,SAAQ;AACf,OAAOC,YAAU;;;ACDjB,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACH1B,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACF1B,OAAO,QAAQ;AACf,SAAS,iBAAiB;AAC1B,OAAOC,WAAU;AACjB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,OAAO,QAAQ;;;ACLf,OAAO,UAAU;AAGV,SAAS,kBAAkB,OAA8B;AAC9D,QAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG;AACtC,MAAI,CAAC,SAAS,MAAM,SAAS,IAAI,KAAK,KAAK,MAAM,WAAW,KAAK,KAAK,aAAa,KAAK,KAAK,EAAG,QAAO;AACvG,MAAI,MAAM,MAAM,GAAG,EAAE,SAAS,IAAI,EAAG,QAAO;AAC5C,QAAM,aAAa,KAAK,MAAM,UAAU,KAAK,EAAE,QAAQ,OAAO,EAAE;AAChE,SAAO,eAAe,MAAM,OAAO;AACrC;AAMO,SAAS,aAAa,MAAc,WAA4B;AACrE,QAAM,WAAW,KAAK,SAAS,MAAM,SAAS;AAC9C,SAAO,aAAa,QAAQ,CAAC,SAAS,WAAW,KAAK,KAAK,GAAG,EAAE,KAAK,CAAC,KAAK,WAAW,QAAQ;AAChG;AAEO,SAAS,cAAc,QAAgB,MAAuB;AACnE,QAAM,IAAI,kBAAkB,MAAM;AAClC,QAAM,IAAI,kBAAkB,IAAI;AAChC,SAAO,MAAM,QAAQ,MAAM,SAAS,MAAM,KAAK,EAAE,WAAW,GAAG,CAAC,GAAG;AACrE;AAEO,SAAS,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AAY,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EACjC,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,QAAQ;AACP,YAAQ,OAAO,MAAM,sBAAsB,GAAG;AAAA,CAAI;AAClD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["path","fs","path","fs","path","execFile","promisify","path","execFile","promisify","path","fs","path","fs","path","path","exec","promisify","execFile","exec","exec","promisify","execFile","exec","fs","path","execFile","promisify","execFile","promisify","exec","exec","promisify","execFile","fs","path","fs","path","fs","path","fg","path","text","fg","path","count","fs","path","fg","fs","path","fg","fs","path","fg","fs","path","fg","execFile","promisify","exec","text","path","fs","path","path","z","z","fs","path","path","fs","fs","path","createHash","randomUUID","z","z","createHash","fs","randomUUID","path","path"]}
|