mason-context 0.18.0 → 0.19.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/profile.ts","../src/utils/git-read.ts","../src/audit/commands.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/utils/paths.ts","../src/utils/files.ts","../src/audit/inspection.ts","../src/audit/git.ts","../src/utils/storage.ts","../src/audit/inputs.ts","../src/audit/docs.ts","../src/audit/scope.ts","../src/utils/store-lock.ts","../src/snapshot/lock.ts","../src/test-map.ts","../src/snapshot/snapshot.ts","../src/drift/drift.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/context/lexical.ts","../src/context/trust.ts","../src/decisions/provenance.ts","../src/decisions/decisions.ts","../src/decisions/drift.ts","../src/audit/checks/decision-anchor.ts","../src/audit/checks/index.ts","../src/audit/findings.ts","../src/automation/store.ts","../src/audit/advisory-review.ts","../src/audit/audit.ts","../src/audit/repair.ts","../src/automation/evidence.ts","../src/setup/model.ts","../src/setup/launcher.ts","../src/snapshot/review.ts","../src/snapshot/trust.ts","../src/setup/files.ts","../src/automation/execution.ts","../src/automation/runtime.ts","../src/automation/hook-root.ts","../src/automation/adapters.ts","../src/setup/ownership.ts","../src/automation/install.ts","../src/setup/config.ts","../src/mcp/init.ts","../src/review/cochange.ts","../src/review/evidence/paths.ts","../src/review/evidence/types.ts","../src/review/evidence/vitest.ts","../src/review/evidence/sarif.ts","../src/review/evidence/check.ts","../src/review/evidence.ts","../src/review/review.ts","../src/mcp/onboarding.ts","../src/impact/references.ts","../src/impact/impact.ts","../src/context/assemble.ts","../src/setup/observations.ts","../src/setup/status.ts","../src/setup/setup.ts","../src/confluence/client.ts","../src/llm/config.ts","../src/confluence/url.ts","../src/confluence/renderer.ts","../src/confluence/diff.ts","../src/llm/providers.ts","../src/confluence/rewrite.ts","../src/confluence/sync.ts","../src/mcp/server.ts","../src/mcp/tools.ts","../src/audit/cli.ts","../src/audit/advisory-cli.ts","../src/analyzers/git-history.ts","../src/analyzers/base.ts","../src/analyzers/index.ts","../src/utils/git.ts","../src/mcp/sampler.ts","../src/decisions/review.ts","../src/snapshot/prompt.ts","../src/snapshot/partials.ts","../bin/mason-mcp.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype Timing = { calls: number; totalMs: number };\nconst profiles = new AsyncLocalStorage<Record<string, Timing>>();\n\n/** Opt-in, invocation-local timings. Labels are fixed in source; no repository data. */\nexport async function profilePhase<T>(label: string, run: () => Promise<T>): Promise<T> {\n const phases = profiles.getStore();\n if (!phases) return run();\n const start = performance.now();\n try { return await run(); }\n finally {\n const timing = phases[label] ??= { calls: 0, totalMs: 0 };\n timing.calls++;\n timing.totalMs += performance.now() - start;\n }\n}\n\nexport async function withProfile<T>(run: () => Promise<T>, emit: (json: string) => void): Promise<T> {\n const phases: Record<string, Timing> = {};\n const start = performance.now();\n return profiles.run(phases, async () => {\n try { return await run(); }\n finally {\n emit(JSON.stringify({ kind: \"mason-profile\", version: 1, totalMs: performance.now() - start, phases }));\n }\n });\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { profilePhase } from \"./profile.js\";\n\nconst execute = promisify(execFile);\nconst commands = new Set([\"rev-parse\", \"symbolic-ref\", \"for-each-ref\", \"ls-files\", \"check-ignore\", \"status\", \"log\", \"diff\", \"ls-tree\", \"show\", \"merge-base\"]);\nexport interface GitReadOptions { cwd: string; maxBuffer?: number; timeout?: number; input?: string }\n\n/** Fixed command labels only: profiling never includes arguments or repository paths. */\nexport function execGit(args: string[], options: GitReadOptions) {\n const command = args.find(arg => !arg.startsWith(\"-\")) ?? \"other\";\n return profilePhase(\"git.\" + (commands.has(command) ? command : \"other\"), async () => {\n const { input, ...processOptions } = options;\n const operation = execute(\"git\", args, processOptions);\n if (input !== undefined) {\n operation.child.stdin!.on(\"error\", () => { /* The child exit reports a failed query. */ });\n operation.child.stdin!.end(input);\n }\n return operation;\n });\n}\n","import path from \"node:path\";\nimport type { CommandClaim } from \"./types.js\";\n\nconst TOKEN = `(?:\"[^\"\\\\n]*\"|'[^'\\\\n]*'|[^\\\\s\\x60;&|]+)`;\nconst COMMAND = new RegExp(`\\\\b(npm|pnpm|yarn)((?:[ \\\\t]+${TOKEN})*?)[ \\\\t]+run[ \\\\t]+([A-Za-z0-9:_.-]+)`, \"g\");\nconst literal = (value: string) => {\n const unquoted = value.replace(/^([\"'])(.*)\\1$/, \"$2\");\n return /[$`*?\\[\\]{}~\\\\\\x00-\\x1f]/.test(unquoted) || path.posix.isAbsolute(unquoted) ? null : unquoted;\n};\n\nfunction splitCommands(line: string): string[] {\n const parts: string[] = [];\n let quote = \"\", start = 0;\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n if (char === \"\\\\\") { i++; continue; }\n if (quote) { if (char === quote) quote = \"\"; continue; }\n if (char === \"'\" || char === '\"') { quote = char; continue; }\n if (char === \";\" || line.slice(i, i + 2) === \"&&\") {\n parts.push(line.slice(start, i));\n if (char === \"&\") i++;\n start = i + 1;\n }\n }\n parts.push(line.slice(start));\n return parts;\n}\n\n/** Deliberately small shell subset: literal cd and npm-family run invocations. */\nexport function commandClaims(line: string, lineNo: number, cwd?: string | null, shell = false): { claims: CommandClaim[]; cwd: string | null | undefined } {\n const claims: CommandClaim[] = [];\n const segments = splitCommands(line);\n for (const segment of segments) {\n const text = segment.trim().replace(/^\\$\\s+/, \"\");\n if (text.startsWith(\"#\") || /^(?:echo|printf)\\b/.test(text)) continue;\n const cd = text.match(/^cd\\s+(.+)$/);\n if (cd) {\n const directory = literal(cd[1]);\n cwd = directory === null || cwd === null || /\\s/.test(directory) && !/^[\"']/.test(cd[1])\n ? null : path.posix.join(cwd ?? \".\", directory);\n continue;\n }\n for (const match of text.matchAll(COMMAND)) {\n const flags = match[2].trim();\n const selector = flags.match(/^(?:--prefix|--dir|-C)(?:\\s+|=)(.+)$/);\n let directory = cwd;\n let scopeUnknown: string | undefined;\n if ((shell && match.index !== 0) || match[3].startsWith(\"-\")) scopeUnknown = \"Unsupported shell wrapper or options before the script.\";\n if (selector) {\n const selected = literal(selector[1]);\n directory = selected === null || cwd === null ? null : path.posix.join(cwd ?? \".\", selected);\n } else if (flags) scopeUnknown = \"Unsupported package-manager options before run: \" + flags;\n const tail = text.slice(match.index! + match[0].length).split(/\\s--(?:\\s|$)/)[0];\n if (/(?:^|\\s)(?:--workspace(?:s)?|-w|--filter|-F|--prefix|--dir|-C|--if-present)(?:\\s|=|$)/.test(tail)) {\n scopeUnknown = \"Package selection or conditional options after the script need review.\";\n }\n if (/[|()]/.test(text) || /\\b(?:pushd|popd|if|for|while)\\b/.test(text) || directory === null) {\n scopeUnknown = \"The command's working directory or shell control flow could not be resolved.\";\n }\n claims.push({ scriptName: match[3], invocation: match[0], excerpt: match[0], line: lineNo,\n ...(directory !== undefined && directory !== null ? { directory } : {}), ...(scopeUnknown ? { scopeUnknown } : {}) });\n }\n // An unresolved directory change must not leave later commands apparently scoped.\n if (/\\b(?:cd|pushd|popd)\\b/.test(text)) cwd = null;\n }\n return { claims, cwd };\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 MarkdownIt from \"markdown-it\";\nimport { commandClaims } from \"./commands.js\";\nimport 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 markdown = new MarkdownIt(\"commonmark\", { html: false });\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 const key = [claim.relativeTo ?? \"scope\", claim.path].join(\":\");\n if (!paths.has(key)) paths.set(key, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n const key = JSON.stringify([claim.scriptName, claim.directory, claim.scopeUnknown]);\n if (!commands.has(key)) commands.set(key, claim);\n };\n\n // A real Markdown parser distinguishes reference links, images and escaped\n // destinations from code examples. Ignore markers preserve source line offsets.\n const parsed = markdown.parse(lines.map((line, i) => ignored[i] ? \"\" : line).join(\"\\n\"), {});\n for (const token of parsed) {\n if (token.type !== \"inline\" || !token.map) continue;\n let line = token.map[0] + 1;\n for (const child of token.children ?? []) {\n const target = child.type === \"link_open\" ? child.attrGet(\"href\") : child.type === \"image\" ? child.attrGet(\"src\") : null;\n if (target && !/^(?:[a-z][a-z0-9+.-]*:|[\\/#~])/i.test(target)) {\n let pathname: string | null = null;\n try { pathname = decodeURIComponent(target.split(/[?#]/)[0]); } catch { /* Unsupported URL encoding. */ }\n if (pathname && !/[$*?{}<>\\\\\\x00-\\x1f]/.test(pathname)) {\n addPath({ path: pathname, line, excerpt: target, relativeTo: \"document\" });\n }\n }\n if (child.type === \"softbreak\" || child.type === \"hardbreak\") line++;\n else line += child.content.split(\"\\n\").length - 1;\n }\n }\n\n let shellCwd: string | null | undefined;\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 shellCwd = undefined;\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 const scanned = commandClaims(line, lineNo, shellCwd, true);\n shellCwd = scanned.cwd;\n for (const claim of scanned.claims) addCommand(claim);\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 match of line.matchAll(/`([^`]+)`/g)) {\n for (const claim of commandClaims(match[1], lineNo, undefined, true).claims) addCommand(claim);\n }\n for (const claim of commandClaims(line.replace(/`[^`]+`/g, \"\"), lineNo).claims) addCommand(claim);\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 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 { execGit } from \"./git-read.js\";\nimport fs from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\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 execGit([\"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 execGit([\"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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport path from \"node:path\";\nimport { execGit, type GitReadOptions } from \"../utils/git-read.js\";\nimport { SOURCE_EXTENSIONS } from \"../utils/files.js\";\n\ninterface Inspection { root: string; reads: Map<string, Promise<unknown>> }\nconst inspections = new AsyncLocalStorage<Inspection>();\n\n/** Always start fresh. In particular, final validation must not reuse initial reads. */\nexport function withRepositoryInspection<T>(root: string, run: () => Promise<T>): Promise<T> {\n return inspections.run({ root: path.resolve(root), reads: new Map() }, run);\n}\n\n/** Read observations are shared only inside an explicit inspection, never across hooks. */\nexport function inspectionRead<T>(root: string, key: string, read: () => Promise<T>): Promise<T> {\n const inspection = inspections.getStore();\n if (!inspection || inspection.root !== path.resolve(root)) return read();\n if (!inspection.reads.has(key)) {\n const pending = read();\n inspection.reads.set(key, pending);\n // A failed query must be retried, not turned into a reusable unavailable result.\n void pending.catch(() => { if (inspection.reads.get(key) === pending) inspection.reads.delete(key); });\n }\n return inspection.reads.get(key)! as Promise<T>;\n}\n\n/** Exact arguments and limits preserve each history query's semantics. */\nexport function inspectionGit(args: string[], options: GitReadOptions) {\n return inspectionRead(options.cwd, \"git:\" + JSON.stringify([args, options]), () => execGit(args, options));\n}\n\nconst sourceSpecs = SOURCE_EXTENSIONS.map(extension => `:(glob)**/*.${extension}`);\nconst docSpecs = [\":(icase,glob)**/readme.md\", \":(icase,glob)**/agents.md\", \":(icase,glob)**/claude.md\"];\nconst sourceSuffixes = new Set(SOURCE_EXTENSIONS.map(extension => \".\" + extension));\n\n/** Git still prunes ignored trees; unrelated generated files are never inventoried. */\nexport async function auditGitPaths(root: string, kind: \"documents\" | \"sources\"): Promise<string[]> {\n const shared = inspections.getStore()?.root === path.resolve(root);\n const specs = shared ? [...docSpecs, ...sourceSpecs] : kind === \"documents\" ? docSpecs : sourceSpecs;\n const limit = kind === \"documents\" ? 16 * 1024 * 1024 : 32 * 1024 * 1024;\n const { stdout } = await inspectionGit([\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\", \"--\", ...specs],\n { cwd: root, maxBuffer: shared ? 48 * 1024 * 1024 : limit, timeout: 10000 });\n const paths = [...new Set(stdout.split(\"\\0\").filter(Boolean))].filter(file => kind === \"documents\"\n ? /^(readme|agents|claude)\\.md$/i.test(path.posix.basename(file))\n // Git's *.ts also matches a file named .ts, unlike path.extname().\n : sourceSuffixes.has(file.slice(file.lastIndexOf(\".\"))));\n if (Buffer.byteLength(paths.join(\"\\0\")) > limit) throw new Error(\"Git \" + kind + \" inventory exceeds its bounded read limit.\");\n return paths.sort();\n}\n","import { inspectionGit } from \"./inspection.js\";\nimport type { CommitRef } from \"./types.js\";\n\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 inspectionGit(\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", `:(literal)${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 inspectionGit(\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n `:(literal)${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 inspectionGit(\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", `:(literal)${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 inspectionGit(\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 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 fs from \"node:fs/promises\";\nimport * as nativeFs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport fg from \"fast-glob\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { storePath } from \"../utils/storage.js\";\nimport { execGit } from \"../utils/git-read.js\";\nimport { auditGitPaths } from \"./inspection.js\";\n\nconst MAX_INPUTS = 100_000;\n\n/** Check the paths a particular audit actually reads, including their parents. */\nexport async function auditInputPath(root: string, file: string): Promise<string> {\n if (file === \".\") return fs.realpath(root);\n try { return await storePath(root, file); }\n catch (error) {\n if (error instanceof Error && error.message.startsWith(\"Symlink\")) {\n throw new Error(`Audit input contains a symbolic link: ${file}. Its evidence could not be verified.`, { cause: error });\n }\n throw error;\n }\n}\n\nexport async function readAuditInput(root: string, file: string): Promise<string | null> {\n try {\n const value = await readBoundedFile(await auditInputPath(root, file), 10 * 1024 * 1024);\n if (value === null) throw new Error(`Unreadable or oversized audit input: ${file}`);\n return value;\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return null;\n throw error;\n }\n}\n\n/** Bound relevant results and directory traversal, without counting unrelated files. */\nexport async function auditGlob(root: string, patterns: string | string[], options: {\n ignore?: string[]; onlyDirectories?: boolean; followSymbolicLinks?: boolean; label: string; select?: (file: string) => boolean;\n}): Promise<string[]> {\n if (Array.isArray(patterns) && !patterns.length) return [];\n const directories = new Set<string>();\n // fast-glob may stat a link, but must never enumerate a linked directory.\n // Validate each traversal and each selected result instead of scanning the\n // entire repository just to reject unrelated symlinks.\n const readdir = ((directory: string, opts: unknown, callback: (error: unknown, entries?: unknown) => void) => {\n const relative = path.relative(root, directory).split(path.sep).join(\"/\") || \".\";\n directories.add(relative);\n if (directories.size > MAX_INPUTS) {\n callback(new Error(`${options.label} exceeds ${MAX_INPUTS.toLocaleString(\"en-US\")} directories while inspecting ${relative}. Narrow this check's inputs.`));\n return;\n }\n auditInputPath(root, relative).then(() => {\n nativeFs.readdir(directory, opts as { withFileTypes: true }, callback as (error: NodeJS.ErrnoException | null, entries: nativeFs.Dirent[]) => void);\n }, callback);\n }) as typeof nativeFs.readdir;\n // Literal workspace patterns use lstat instead of readdir. Validate them\n // before fast-glob can silently discard a dangling link as a missing file.\n const lstat = ((file: string, callback: (error: unknown, stat?: nativeFs.Stats) => void) => {\n const relative = path.relative(root, file).split(path.sep).join(\"/\") || \".\";\n auditInputPath(root, relative).then(() => nativeFs.lstat(file, callback), callback);\n }) as typeof nativeFs.lstat;\n const stream = fg.stream(patterns, { cwd: root, ignore: options.ignore,\n onlyFiles: false, onlyDirectories: options.onlyDirectories, objectMode: true,\n followSymbolicLinks: options.followSymbolicLinks ?? true, fs: { readdir, lstat }, concurrency: 16 }) as Readable;\n const matches: string[] = [];\n try {\n for await (const value of stream) {\n const entry = value as fg.Entry;\n const file = entry.path;\n if (options.select && !options.select(file)) continue;\n await auditInputPath(root, file);\n if (!options.onlyDirectories && !entry.dirent.isFile()) continue;\n matches.push(file);\n if (matches.length > MAX_INPUTS) {\n const largest = [...matches.reduce((counts, item) => {\n const dir = item.split(\"/\")[0]; counts.set(dir, (counts.get(dir) ?? 0) + 1); return counts;\n }, new Map<string, number>())].sort((a, b) => b[1] - a[1]).slice(0, 3);\n throw new Error(`${options.label} exceeds ${MAX_INPUTS.toLocaleString(\"en-US\")} relevant paths. Largest directories: ${largest.map(([dir, count]) => `${dir} (${count})`).join(\", \")}. Narrow this check's inputs.`);\n }\n }\n } finally { stream.destroy(); }\n return matches.sort();\n}\n\n/** Git prunes ignored trees before discovery; tracked source remains visible. */\nexport async function gitSourcePaths(root: string): Promise<string[]> {\n return auditGitPaths(root, \"sources\");\n}\n\n/** Small directory batches, never a repository-wide inventory of ignored files. */\nexport async function gitIgnoredPaths(root: string, files: string[]): Promise<Set<string>> {\n if (!files.length) return new Set();\n const ignored = new Set<string>();\n for (let offset = 0; offset < files.length; offset += 1000) {\n try {\n const { stdout } = await execGit([\"check-ignore\", \"-z\", \"--stdin\"], {\n cwd: root, maxBuffer: 4 * 1024 * 1024, timeout: 10_000, input: files.slice(offset, offset + 1000).join(\"\\0\") + \"\\0\",\n });\n for (const file of stdout.split(\"\\0\").filter(Boolean)) ignored.add(file);\n } catch (error) {\n if ((error as { code?: number }).code !== 1) throw error;\n }\n }\n return ignored;\n}\n","import { execGit } from \"../utils/git-read.js\";\nimport { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport fg from \"fast-glob\";\nimport { auditGlob, auditInputPath, readAuditInput } from \"./inputs.js\";\nimport { loadProjectConfig } from \"../utils/files.js\";\nimport { auditGitPaths } from \"./inspection.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\n\n/**\n * Instruction entry points written by setup. Audit discovery is broader and\n * preserves actual filename casing; setup/teardown must not edit every README.\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 /** Directory whose instructions this document describes, not a proven shell cwd. */\n scope: string;\n kind: \"instructions\" | \"readme\";\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 dirtyDocs(resolvedRoot: string, files: string[]): Promise<Set<string>> {\n if (!files.length) return new Set();\n try {\n const dirty = new Set<string>();\n for (let offset = 0; offset < files.length; offset += 256) {\n const { stdout } = await execGit(\n [\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...files.slice(offset, offset + 256).map(file => `:(literal)${file}`)],\n { cwd: resolvedRoot, maxBuffer: 16 * 1024 * 1024, timeout: 10000 }\n );\n const entries = stdout.split(\"\\0\");\n for (let i = 0; i < entries.length; i++) {\n if (!entries[i]) continue;\n const status = entries[i].slice(0, 2);\n dirty.add(entries[i].slice(3));\n // Porcelain -z emits destination first, then the original rename/copy path.\n if (/[RC]/.test(status) && entries[i + 1]) dirty.add(entries[++i]);\n }\n }\n return dirty;\n } catch {\n return new Set(files);\n }\n}\n\n/** Readme/instruction discovery shares the exact inventory used by automation. */\nexport async function discoverDocPaths(root: string): Promise<string[]> {\n let candidates: string[] = [];\n try {\n candidates = await auditGitPaths(root, \"documents\");\n } catch (error) {\n // Outside Git we still discover documents so the audit can report Git unavailable.\n try { await execGit([\"rev-parse\", \"--git-dir\"], { cwd: root }); }\n catch { return localDocPaths(root); }\n throw error;\n }\n candidates.push(...await localDocPaths(root));\n const config = await loadProjectConfig(root);\n const excluded = [\"**/node_modules/**\", \"**/vendor/**\", \"**/dist/**\", \"**/build/**\", \"**/target/**\",\n \"**/.git/**\", \"**/.venv/**\", \"**/venv/**\", \".mason/**\", ...(config.ignore ?? [])];\n // Static patterns preserve literal metacharacters and reject selected symlinks.\n const paths: string[] = [];\n const unique = [...new Set(candidates)].sort();\n for (let offset = 0; offset < unique.length; offset += 256) {\n paths.push(...await auditGlob(root, unique.slice(offset, offset + 256).map(p => fg.escapePath(p)), {\n ignore: excluded, followSymbolicLinks: false, label: \"Documentation discovery\",\n }));\n if (paths.length > 10000) throw new Error(\"Documentation discovery exceeds 10,000 relevant files; narrow .mason/config.json ignore patterns.\");\n }\n const priority = (file: string) => {\n const index = (DOC_CANDIDATES as readonly string[]).findIndex(p => p.toLowerCase() === file.toLowerCase());\n return index < 0 ? DOC_CANDIDATES.length : index;\n };\n return paths.sort((a, b) => priority(a) - priority(b) || a.localeCompare(b));\n}\n\n/** Explicit local entry points may be ignored; preserve their real spelling. */\nasync function localDocPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n for (const dir of [\".\", \".claude\"]) {\n let entries;\n try { entries = await fs.readdir(await auditInputPath(root, dir), { withFileTypes: true }); }\n catch (error) { if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue; throw error; }\n for (const entry of entries) if (/^(?:agents|claude|readme)\\.md$/i.test(entry.name)) {\n paths.push(path.posix.join(dir, entry.name));\n }\n }\n return paths;\n}\n\nexport function documentScope(file: string): string {\n const parent = path.posix.dirname(file);\n return path.posix.basename(parent).toLowerCase() === \".claude\" ? path.posix.dirname(parent) : parent;\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n return profilePhase(\"audit.documents\", () => readDocs(resolvedRoot));\n}\n\nasync function readDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs: AuditDoc[] = [];\n const files = await discoverDocPaths(resolvedRoot);\n const dirty = await dirtyDocs(resolvedRoot, files);\n // Bound concurrent Git processes even when discovery reaches thousands of docs.\n for (let offset = 0; offset < files.length; offset += 4) {\n docs.push(...await Promise.all(files.slice(offset, offset + 4).map(async (candidate): Promise<AuditDoc> => {\n const [content, lastCommit] = await Promise.all([readAuditInput(resolvedRoot, candidate),\n profilePhase(\"audit.document-history\", () => lastCommitOf(resolvedRoot, candidate))]);\n if (content === null) throw new Error(\"Document disappeared during discovery: \" + candidate);\n return { path: candidate, content, scope: documentScope(candidate),\n kind: /^readme\\.md$/i.test(path.posix.basename(candidate)) ? \"readme\" : \"instructions\",\n lineCount: content.split(\"\\n\").length, lastCommit, dirty: dirty.has(candidate), claims: extractClaims(content) };\n })));\n }\n return docs;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { auditInputPath } from \"./inputs.js\";\nimport { documentScope } from \"./docs.js\";\nimport type { ClaimScope, PathClaim } from \"./types.js\";\n\n/** Lexical containment, before inspecting any path from documentation. */\nexport function scopedPath(directory: string, value: string): string | null {\n if (path.posix.isAbsolute(value) || value.includes(\"\\\\\") || /[\\x00-\\x1f]/.test(value)) return null;\n const resolved = path.posix.normalize(path.posix.join(directory, value));\n return resolved === \"..\" || resolved.startsWith(\"../\") ? null : resolved;\n}\n\nexport function pathClaimScope(doc: string, claim: PathClaim): ClaimScope | null {\n const directory = claim.relativeTo === \"document\" ? path.posix.dirname(doc) : documentScope(doc);\n const local = scopedPath(directory, claim.path);\n if (!local) return null;\n const candidates = claim.relativeTo === \"document\" || directory === \".\" ? [local]\n : [...new Set([local, scopedPath(\".\", claim.path)].filter((p): p is string => p !== null))];\n return { basis: claim.relativeTo === \"document\" ? \"document-link\" : directory === \".\" ? \"repository\" : \"document\",\n directory, candidates };\n}\n\n/** Missing is distinct from unreadable/unsafe; cache and checks use the same observation. */\nexport async function pathExists(root: string, file: string): Promise<boolean> {\n try { await fs.access(await auditInputPath(root, file)); return true; }\n catch (error) {\n // A child of a regular file cannot exist either. Keep symlink and access\n // failures distinct: neither establishes that a reference is missing.\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return false;\n throw error;\n }\n}\n\nexport function gitMetadataPath(file: string): boolean {\n return file.split(\"/\").includes(\".git\");\n}\n\nexport function optionalMasonPath(file: string): boolean {\n return file.split(\"/\").includes(\".mason\");\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { storePath } from \"./storage.js\";\n\nasync function lockDiagnostic(file: string): Promise<string> {\n let reason: string;\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (!owner || typeof owner.host !== \"string\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n reason = \"Lock owner data is incomplete or malformed.\";\n } else if (owner.host !== os.hostname()) {\n reason = \"The lock belongs to another host; its process cannot be checked locally.\";\n } else {\n try { process.kill(owner.pid, 0); reason = `Local owner PID ${owner.pid} is still running.`; }\n catch (error) {\n reason = (error as NodeJS.ErrnoException).code === \"ESRCH\"\n ? `Local owner PID ${owner.pid} has exited, but lock recovery has not completed.`\n : `Local owner PID ${owner.pid} could not be checked.`;\n }\n }\n } catch (error) {\n reason = error instanceof SyntaxError ? \"Lock owner data is incomplete or malformed.\" : \"Lock owner data could not be read; the lock may have changed.\";\n }\n if (await fs.lstat(file + \".reclaim\").then(() => true, () => false)) {\n reason += \" A recovery guard also needs inspection: \" + file + \".reclaim.\";\n }\n return reason + \" Retry if a writer is active. For manual recovery, stop all Mason writers for this checkout, confirm they have exited (including other hosts), then remove only confirmed abandoned lock and lock.reclaim files. See docs/reference.md#snapshot-repairs-and-verification.\";\n}\n\n/** Cross-process lock: a killed writer's lock is reclaimed only after its local PID is gone. */\nexport async function withStoreLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000, label = \"Mason store\"): Promise<T> {\n const file = await storePath(root, directory + \"/lock\", true);\n const deadline = Date.now() + waitMs;\n let handle;\n while (!handle) {\n try {\n handle = await fs.open(file, \"wx\", 0o600);\n try { await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname() })); }\n catch (error) {\n await handle.close().catch(() => {});\n handle = undefined;\n await fs.rm(file, { force: true }).catch(() => {});\n throw error;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n // Do not steal malformed, remote, or live locks on a time-based guess.\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (owner.host === os.hostname() && Number.isInteger(owner.pid) && owner.pid > 0) {\n try { process.kill(owner.pid, 0); }\n catch (probe) {\n if ((probe as NodeJS.ErrnoException).code === \"ESRCH\") {\n // A separate guard arbitrates reclamation; recheck the owner before unlinking.\n const reclaim = file + \".reclaim\";\n let guard;\n try {\n guard = await fs.open(reclaim, \"wx\", 0o600);\n const current = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (current.pid === owner.pid && current.host === owner.host) await fs.unlink(file);\n } finally { if (guard) { await guard.close(); await fs.rm(reclaim, { force: true }); } }\n }\n }\n }\n } catch { /* Another writer may be creating/releasing/reclaiming it. */ }\n if (Date.now() >= deadline) throw new Error(label + \" is busy or its lock needs inspection: \" + file + \". \" + await lockDiagnostic(file));\n await new Promise(resolve => setTimeout(resolve, 40));\n }\n }\n try { return await run(); }\n finally { await handle.close(); await fs.unlink(file); }\n}\n","import { withStoreLock } from \"../utils/store-lock.js\";\n\n/** Each checkout has its own snapshot and partials, shared by all MCP processes. */\nexport function withSnapshotWrite<T>(root: string, run: () => Promise<T>, waitMs = 5000): Promise<T> {\n return withStoreLock(root, \".mason/local/snapshot-write\", run, waitMs, \"Snapshot store\");\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 { execGit } from \"../utils/git-read.js\";\nimport path from \"node:path\";\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 { withSnapshotWrite } from \"./lock.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { buildTestMap } from \"../test-map.js\";\n\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 /** Digest of the entry and bounded source evidence reviewed for this verdict. */\n verificationToken?: 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 /** Digest of the entry and bounded source evidence reviewed for this verdict. */\n verificationToken?: 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(), verificationToken: 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\n/** Read and commit under one cross-process lock; a null snapshot means no write. */\nexport async function updateSnapshot<T>(rootDir: string, update: (current: Snapshot | null) => Promise<{\n snapshot: Snapshot | null;\n result: T;\n afterSave?: () => Promise<void>;\n}>): Promise<T> {\n return withSnapshotWrite(rootDir, async () => {\n const change = await update(await loadSnapshot(rootDir));\n if (change.snapshot) {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(change.snapshot));\n await change.afterSave?.();\n }\n return change.result;\n });\n}\n\nexport async function getCurrentGitHash(rootDir: string): Promise<string> {\n try {\n const { stdout } = await execGit([\"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 { execGit } from \"../utils/git-read.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\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\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 execGit([\"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 execGit([\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n execGit([\"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 execGit(\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 execGit([\"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 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\" | IssueType;\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 is absent from a resolved manifest). \"likely\" is\n * retained for older reports. Inferred scope and speculative omissions are\n * advisory; even a certain mismatch needs semantic review before repair.\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 interface ClaimScope {\n basis: \"repository\" | \"document\" | \"document-link\" | \"explicit\";\n directory: string;\n /** Exact repository-relative paths/manifests considered by the check. */\n candidates: string[];\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 resolvedPath?: string;\n scope?: ClaimScope;\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 scope?: ClaimScope;\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 require judgment and never drive the ordinary audit exit code.\n * Historical advisories require a separate review. Explicitly recheckable\n * candidates can cease to be detected without asserting semantic approval.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n resolution?: \"recheck\";\n}\n\nexport interface AuditDocInfo {\n path: string;\n scope?: string;\n kind?: \"instructions\" | \"readme\";\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 /** Additive assessment status; original advisory evidence remains intact. */\n advisoryReviews?: import(\"./advisory-review.js\").AdvisoryReviewSummary[];\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n /** Markdown links resolve against the physical document directory. */\n relativeTo?: \"document\";\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 /** A literal cd/directory flag, relative to the document's assumed cwd. */\n directory?: string;\n scopeUnknown?: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport { gitMetadataPath, optionalMasonPath, pathClaimScope, pathExists } from \"../scope.js\";\nimport type { Evidence } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Prove removed references only when their scope is resolved. */\nexport async function checkDeletedReferences(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map((changes ?? []).filter(c => c.status === \"renamed\" && c.previousPath)\n .map(c => [c.previousPath!, c.path]));\n for (const claim of doc.claims.paths) {\n const scope = pathClaimScope(doc.path, claim);\n if (!scope) {\n result.skipped.push({ check: \"deleted-reference\", doc: doc.path,\n reason: `Reference ${claim.excerpt} is outside the repository or has an unsupported path.` });\n continue;\n }\n if (scope.candidates.some(optionalMasonPath)) continue;\n if (scope.candidates.some(gitMetadataPath)) {\n result.skipped.push({ check: \"deleted-reference\", doc: doc.path,\n reason: `Reference ${claim.path} names Git metadata, whose layout varies between checkouts; it was not verified as a repository file.` });\n continue;\n }\n if ((await Promise.all(scope.candidates.map(file => pathExists(ctx.root, file)))).some(Boolean)) continue;\n\n const candidates = await Promise.all(scope.candidates.map(async file => ({ file,\n tracked: await lastCommitOf(ctx.root, file), parent: await pathExists(ctx.root, path.posix.dirname(file)) })));\n const candidate = candidates.find(c => c.tracked || renames.has(c.file)) ?? candidates.find(c => c.parent);\n // No history/parent for a bare path is usually an illustrative example.\n if (!candidate && claim.relativeTo !== \"document\") continue;\n const resolvedPath = candidate?.file ?? scope.candidates[0];\n const renamedTo = renames.get(resolvedPath) ?? null;\n const deletedInCommit = candidate?.tracked && !renamedTo ? await deletingCommitOf(ctx.root, resolvedPath) : null;\n const evidence: Evidence = { kind: \"missing-path\", claimed: claim.path, resolvedPath, scope,\n renamedTo, deletedInCommit, everTracked: !!candidate?.tracked || !!renamedTo, parentDirExists: candidate?.parent ?? false };\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const message = renamedTo ? `\\`${resolvedPath}\\` was renamed to \\`${renamedTo}\\``\n : `\\`${resolvedPath}\\` does not exist` + (deletedInCommit\n ? ` – deleted in ${deletedInCommit.hash.slice(0, 7)} \"${deletedInCommit.subject}\" (${deletedInCommit.date.slice(0, 10)})` : \"\");\n if (scope.basis !== \"document\" && (renamedTo || candidate?.tracked)) {\n result.issues.push({ type: \"deleted-reference\", message, anchor, confidence: \"certain\", evidence });\n } else {\n result.advisories.push({ resolution: \"recheck\", type: \"deleted-reference\", message: message + (scope.basis === \"document\"\n ? \"; the bare path's document/repository scope needs review.\"\n : \"; no tracked history establishes it as a required file. Review for a typo, generated output, or example.\"), anchor, evidence });\n }\n }\n }\n return result;\n}\n","import { inspectionRead } from \"../inspection.js\";\nimport fg from \"fast-glob\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { loadProjectConfig, SOURCE_IGNORE } from \"../../utils/files.js\";\nimport { auditGlob, auditInputPath, gitIgnoredPaths, gitSourcePaths } from \"../inputs.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\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = moduleDocumentation(ctx.docs);\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.advisories.push({\n resolution: \"recheck\",\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in the discovered documentation; review whether it needs documenting`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\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/** Nested documentation establishes a directory is documented without requiring\n * every package README to repeat its full repository path. */\nexport function moduleDocumentation(docs: Array<{ path: string; content: string }>): string {\n return docs.map(doc => doc.content + \"\\n\" + (path.posix.dirname(doc.path) === \".\" ? \"\" : path.posix.dirname(doc.path) + \"/\")).join(\"\\n\");\n}\n\n/** Shared dependency witness: cache exactly the module candidates the audit observes. */\nexport function moduleCandidates(root: string, combinedDocs: string) {\n return inspectionRead(root, \"modules:\" + combinedDocs, () => collectModuleCandidates(root, combinedDocs));\n}\n\nasync function collectModuleCandidates(root: string, combinedDocs: string) {\n const [config, sourcePaths] = await Promise.all([loadProjectConfig(root), gitSourcePaths(root)]);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n const sources = sourcePaths.filter(file => !file.split(\"/\").some(part => part.startsWith(\".\")));\n const listSubdirs = async (parents: string[]): Promise<Map<string, string[]>> => {\n const byParent = new Map<string, string[]>();\n // Gather one level before asking Git about ignores, with bounded directory reads.\n for (let offset = 0; offset < parents.length; offset += 16) {\n await Promise.all(parents.slice(offset, offset + 16).map(async dir => {\n const entries = await fs.readdir(await auditInputPath(root, dir), { withFileTypes: true });\n // An unrelated directory alias is not a source module. Selected links\n // still pass through auditGlob's path and parent validation.\n const dirs = entries.filter(entry => (entry.isDirectory() || entry.isSymbolicLink()\n && sources.some(file => file.startsWith(path.posix.join(dir, entry.name) + \"/\")))\n && !entry.name.startsWith(\".\") && !DIR_DENYLIST.has(entry.name))\n .map(entry => path.posix.join(dir, entry.name));\n byParent.set(dir, dirs);\n }));\n }\n const ignored = await gitIgnoredPaths(root, [...byParent.values()].flat());\n const result = new Map<string, string[]>();\n for (const dir of parents) {\n // An ignore rule does not remove already tracked source from the audit.\n const visible = new Set(byParent.get(dir)!.filter(candidate => !ignored.has(candidate)\n || sources.some(file => file.startsWith(candidate + \"/\"))));\n result.set(dir, (await auditGlob(root, dir === \".\" ? \"*\" : `${fg.escapePath(dir)}/*`, {\n ignore, onlyDirectories: true, label: \"Module directory discovery\", select: file => visible.has(file),\n })).map(file => path.posix.basename(file)));\n }\n return result;\n };\n const countSourceFiles = async (dir: string): Promise<number> => {\n const files = sources.filter(file => file.startsWith(dir + \"/\"));\n let count = 0;\n // Literal path batches avoid compiling one enormous glob pattern set in a\n // genuinely large source module. Apply exclusions before counting results.\n for (let offset = 0; offset < files.length; offset += 256) {\n count += (await auditGlob(root, files.slice(offset, offset + 256).map(file => fg.escapePath(file)), {\n ignore, followSymbolicLinks: false, label: `Source discovery in ${dir}`,\n })).length;\n if (count > 100000) throw new Error(`Source discovery in ${dir} exceeds 100,000 relevant files. Exclude generated source with .mason/config.json ignore patterns or narrow this audit's checks.`);\n }\n return count;\n };\n const candidates: Array<{ dir: string; sourceFileCount: number }> = [];\n const topDirs = (await listSubdirs([\".\"])).get(\".\")!;\n const nested = await listSubdirs(topDirs.filter(dir => isMentioned(combinedDocs, dir)));\n for (const topDir of topDirs) {\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(topDir);\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 = nested.get(topDir)!;\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(`${topDir}/${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 path from \"node:path\";\nimport { documentScope } from \"../docs.js\";\nimport { auditGlob, readAuditInput } from \"../inputs.js\";\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 countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readAuditInput(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 readAuditInput(root, \"package.json\");\n if (pkgRaw !== null) {\n let globs: string[] = [];\n try {\n const pkg = JSON.parse(pkgRaw);\n globs = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n } catch {\n // Malformed package.json — nothing provable here.\n }\n if (globs.length > 0) {\n const matched = await auditGlob(root,\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { ignore: [\"**/node_modules/**\"], label: \"npm workspace discovery\" }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n\n const pnpmRaw = await readAuditInput(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 auditGlob(root,\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { ignore: [\"**/node_modules/**\"], label: \"pnpm workspace discovery\" }\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 readAuditInput(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 auditGlob(root, `${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n ignore: [\"**/target/**\"],\n label: \"Cargo workspace discovery\",\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readAuditInput(root, path.posix.join(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\n/** Nested documents cannot assert the root workspace's count implicitly. */\nexport async function resolveDocCountSource(root: string, doc: string, claim: CountClaim): Promise<CountSource | null> {\n const scope = documentScope(doc);\n const source = await resolveCountSource(path.join(root, scope), claim);\n if (!source || scope === \".\") return source;\n return { ...source, countedFrom: scope + \"/\" + source.countedFrom,\n members: source.members.map(member => scope + \"/\" + member) };\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 resolveDocCountSource(ctx.root, doc.path, 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 path from \"node:path\";\nimport { auditGlob, readAuditInput } from \"../inputs.js\";\nimport { documentScope } from \"../docs.js\";\nimport { scopedPath } from \"../scope.js\";\nimport type { ClaimScope, CommandClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\nfunction scriptsOf(raw: string): string[] | null {\n try {\n const pkg = JSON.parse(raw);\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) return null;\n if (pkg.scripts === undefined) return [];\n return pkg.scripts && typeof pkg.scripts === \"object\" && !Array.isArray(pkg.scripts)\n && Object.values(pkg.scripts).every(value => typeof value === \"string\") ? Object.keys(pkg.scripts) : null;\n } catch { return null; }\n}\n\ninterface Resolution {\n doc: string; claim: CommandClaim; scope: ClaimScope; manifest: string | null;\n scripts: string[]; elsewhere: string[]; problem?: string;\n}\n\n/** Shared dependency resolver: the cache records every manifest actually consulted. */\nexport async function commandInputs(root: string, docs: Array<{ path: string; claims: { commands: CommandClaim[] } }>) {\n const contents = new Map<string, string | null>();\n const read = async (file: string) => {\n if (!contents.has(file)) contents.set(file, await readAuditInput(root, file));\n return contents.get(file)!;\n };\n await read(\"package.json\");\n let inventory: string[] | undefined;\n const resolutions: Resolution[] = [];\n for (const doc of docs) for (const claim of doc.claims.commands) {\n const base = documentScope(doc.path);\n const directory = scopedPath(base, claim.directory ?? \".\");\n const scope: ClaimScope = { basis: claim.directory === undefined ? \"document\" : \"explicit\",\n directory: directory ?? base, candidates: [] };\n const resolution: Resolution = { doc: doc.path, claim, scope, manifest: null, scripts: [], elsewhere: [] };\n resolutions.push(resolution);\n if (claim.scopeUnknown || directory === null) {\n resolution.problem = claim.scopeUnknown ?? \"The command's directory leaves the repository.\";\n continue;\n }\n let cursor = directory;\n while (true) {\n const manifest = path.posix.join(cursor, \"package.json\");\n scope.candidates.push(manifest);\n const raw = await read(manifest);\n if (raw !== null) {\n resolution.manifest = manifest;\n const scripts = scriptsOf(raw);\n if (scripts === null) resolution.problem = \"Invalid package manifest: \" + manifest;\n else resolution.scripts = scripts;\n break;\n }\n // An explicit directory is a declared execution scope, never silently use a sibling.\n if (claim.directory !== undefined || cursor === \".\") break;\n cursor = path.posix.dirname(cursor);\n }\n if (!resolution.manifest && !resolution.problem) {\n resolution.problem = `No package.json for the command's scope (${directory}).`;\n }\n if (resolution.problem || resolution.scripts.includes(claim.scriptName) || claim.directory !== undefined) continue;\n inventory ??= await commandManifests(root);\n for (const manifest of [...new Set([\"package.json\", ...inventory])].sort()) {\n if (scope.candidates.includes(manifest)) continue;\n scope.candidates.push(manifest);\n const raw = await read(manifest);\n if (raw === null) continue;\n const scripts = scriptsOf(raw);\n if (scripts === null) resolution.problem = \"Cannot establish script availability: invalid manifest \" + manifest;\n else if (scripts.includes(claim.scriptName)) resolution.elsewhere.push(manifest);\n }\n }\n return { manifests: [...contents].sort(([a], [b]) => a.localeCompare(b)), resolutions };\n}\n\nexport async function checkDeadCommands(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n const { resolutions } = await commandInputs(ctx.root, ctx.docs);\n for (const { doc, claim, scope, scripts, elsewhere, problem, manifest } of resolutions) {\n if (problem) {\n result.skipped.push({ check: \"dead-command\", doc, reason: problem });\n continue;\n }\n if (scripts.includes(claim.scriptName)) continue;\n const evidence = { kind: \"missing-script\" as const, scriptName: claim.scriptName, invocation: claim.invocation,\n manifestsChecked: scope.candidates, availableScripts: scripts.slice(0, AVAILABLE_SCRIPTS_CAP), scope };\n const anchor = { doc, line: claim.line, excerpt: claim.excerpt };\n const message = `\\`${claim.invocation}\\` names script \"${claim.scriptName}\", which is absent from ${manifest}`;\n // Nested docs imply a package, but may describe commands run from another cwd.\n const certain = documentScope(doc) === \".\" && (scope.basis === \"explicit\" || !elsewhere.length);\n if (certain) result.issues.push({ type: \"dead-command\", message, anchor, confidence: \"certain\", evidence });\n else result.advisories.push({ resolution: \"recheck\", type: \"dead-command\", message: message + (elsewhere.length\n ? `; it exists in ${elsewhere.join(\", \")}. Clarify the intended working directory.`\n : \"; the intended working directory needs review.\"), anchor, evidence });\n }\n return result;\n}\n\n/** Ignored workspace manifests may still be explicit command dependencies. */\nexport function commandManifests(root: string): Promise<string[]> {\n return auditGlob(root, \"**/package.json\", {\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \".mason/reports/**\", \"package.json\"],\n label: \"Command manifest discovery\",\n });\n}\n","import { execGit } from \"../utils/git-read.js\";\nimport type { RangeCommits } from \"./git.js\";\n\nasync function git(root: string, args: string[]) {\n return (await execGit(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 { documentScope } from \"../docs.js\";\nimport { 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/** Share exact dependency scope with persisted advisory assessments. */\nexport function manifestPathspecs(doc: string): string[] {\n const scope = documentScope(doc);\n if (scope === \".\") return MANIFEST_PATHSPECS;\n const escaped = scope.replace(/[\\\\*?\\[\\]]/g, \"\\\\$&\");\n return MANIFEST_PATHSPECS.map(spec => spec.startsWith(\":(glob)\")\n ? \":(glob)\" + escaped + \"/\" + spec.slice(\":(glob)\".length) : \":(literal)\" + scope + \"/\" + spec);\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 manifestPathspecs(doc.path)\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\";\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","export type Freshness = \"current\" | \"changed\" | \"unknown\";\nexport interface TrustState {\n freshness: Freshness;\n verification: \"unverified\" | \"passed\" | \"failed\" | \"stale\" | \"unknown\";\n /** Historical map verdict, retained even when its evidence no longer applies. */\n recordedVerdict?: \"passed\" | \"failed\";\n verifiedAt?: string;\n verifiedHash?: string;\n reasons: string[];\n}\n\nexport function assessTrust(entry: { verifiedAt?: string; verifiedHash?: string; verificationFailed?: boolean; verificationNote?: string }, freshness: Freshness): TrustState {\n const verification = entry.verificationFailed ? \"failed\" : entry.verifiedAt ? \"passed\" : \"unverified\";\n const reasons: string[] = [];\n if (freshness === \"unknown\") reasons.push(\"Anchors, history, or working-tree evidence are unavailable; verify before relying on this entry.\");\n if (freshness === \"changed\") reasons.push(\"Anchored files changed; verify against current code before relying on this entry.\");\n if (verification === \"failed\") reasons.push(`Verification failed: ${entry.verificationNote ?? \"re-map this entry before relying on it\"}`);\n if (verification === \"unverified\") reasons.push(\"No correctness verification has been recorded.\");\n return { freshness, verification, verifiedAt: entry.verifiedAt, verifiedHash: entry.verifiedHash, reasons };\n}\n\nexport function trustHint(states: TrustState[]): string {\n const parts: string[] = [];\n if (states.some(s => s.verification === \"failed\" || s.recordedVerdict === \"failed\")) parts.push(\"Verification failed for returned entries; do not rely on those descriptions until corrected.\");\n if (states.some(s => s.verification === \"stale\")) parts.push(\"Recorded verification evidence changed; use verify_snapshot and review the current evidence before reusing those verdicts.\");\n if (states.some(s => s.verification === \"unknown\")) parts.push(\"Recorded verification evidence cannot be confirmed; inspect the files and obtain a fresh review before relying on those verdicts.\");\n if (states.some(s => s.freshness === \"unknown\")) parts.push(\"Freshness is unknown for some returned entries; inspect their files before relying on them.\");\n if (states.some(s => s.freshness === \"changed\")) parts.push(\"Some returned entries have changed files, including possible local edits; verify against the current code.\");\n if (!parts.length) parts.push(\"No changes detected in the returned anchors. This does not prove the descriptions are correct.\");\n if (states.some(s => s.verification === \"unverified\")) parts.push(\"Some entries have never been verified; read their evidence or use verify_snapshot for map descriptions.\");\n return parts.join(\" \");\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 fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\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_RECOMMENDED_CHARS = 1500;\nexport const BODY_MAX_CHARS = 2500;\nexport const MAX_ACTIVE_DECISIONS = 150;\n\n// Share validation with MCP so rejected tool calls include the actual length.\nconst boundedText = (field: string, max: number, hint: string) => z.string({\n errorMap: (issue, ctx) => ({ message: issue.code === \"too_big\"\n ? `${field} has ${ctx.data.length} characters; maximum is ${max} (${ctx.data.length - max} over). ${hint}`\n : ctx.defaultError }),\n}).trim().min(1, `${field} must be non-empty`).max(max);\n\nexport const decisionTitleSchema = boundedText(\"title\", TITLE_MAX_CHARS, \"Tighten it to a specific headline.\");\nexport const decisionBodySchema = boundedText(\"body\", BODY_MAX_CHARS,\n `Aim for ${BODY_RECOMMENDED_CHARS} characters or fewer. Preserve the rule, reason, and exceptions; put supporting references in sources.`);\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: base slug ≤60 chars, ending at a word\n * boundary when possible. A single longer word is cut to fit.\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 fullSlug = title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n let slug = fullSlug.slice(0, 60);\n if (fullSlug.length > 60 && fullSlug[60] !== \"-\") {\n const boundary = slug.lastIndexOf(\"-\");\n if (boundary > 0) slug = slug.slice(0, boundary);\n }\n slug = slug.replace(/-+$/, \"\") || \"decision\";\n if (!existingIds.has(slug)) return slug;\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 parsedTitle = decisionTitleSchema.safeParse(input.title), parsedBody = decisionBodySchema.safeParse(input.body);\n if (!parsedTitle.success) return { status: \"error\", error: parsedTitle.error.issues[0].message };\n if (!parsedBody.success) return { status: \"error\", error: parsedBody.error.issues[0].message };\n const title = parsedTitle.data, body = parsedBody.data;\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 if (body.length > BODY_RECOMMENDED_CHARS) warnings.push(`body has ${body.length} characters, above the recommended ${BODY_RECOMMENDED_CHARS}; matching context and hooks include it in full. Keep the rule, reason, and exceptions concise; use sources for supporting references.`);\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\";\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 { 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 { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { AuditIssue, AuditAdvisory } from \"./types.js\";\nexport type Finding = AuditIssue | AuditAdvisory;\nexport const digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\nexport const checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nexport const 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 scopeSchema = z.object({ basis: z.enum([\"repository\", \"document\", \"document-link\", \"explicit\"]),\n directory: z.string(), candidates: z.array(z.string()) });\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(), resolvedPath: z.string().optional(), scope: scopeSchema.optional() }),\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()), scope: scopeSchema.optional() }),\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 });\nexport const issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nexport const advisorySchema = findingSchema.extend({ type: checkSchema, resolution: z.literal(\"recheck\").optional() });\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});\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.resolvedPath && e.resolvedPath !== e.claimed ? [e.claimed, e.resolvedPath] : 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.scope && e.scope.directory !== \".\" ? [e.scriptName, e.scope.directory] : 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}\n","import { z } from \"zod\";\nimport { withStoreLock } from \"../utils/store-lock.js\";\n\nexport const hostSchema = z.enum([\"claude\", \"codex\"]);\nexport type Host = z.infer<typeof hostSchema>;\nexport const events = [\"session_start\", \"turn_start\", \"before_tool\", \"after_tool\", \"task_end\"] as const;\nexport type Event = typeof events[number];\nexport const stateSchema = z.object({\n version: z.literal(1), root: z.string(), gitDir: z.string(), branch: z.string(),\n baselines: z.array(z.object({ path: z.string(), at: z.string(), event: z.string(), fingerprint: z.string() })).max(128),\n sessions: z.record(z.object({\n host: hostSchema, seen: z.string().nullable(), continued: z.boolean(),\n initialIssues: z.array(z.string()), initialDocs: z.record(z.string().nullable()),\n lastUsed: z.string(), mutationObserved: z.boolean(),\n pending: z.record(z.string()), coverageGaps: z.array(z.string()),\n events: z.record(z.object({ at: z.string(), count: z.number().int().positive() })),\n })),\n updatedAt: z.string(), fingerprint: z.string().nullable(),\n latest: z.string().nullable(),\n analysis: z.object({ id: z.string(), fingerprint: z.string(), completedAt: z.number(), path: z.string() }).optional(),\n});\nexport type State = z.infer<typeof stateSchema>;\nexport function parseState(raw: unknown): State {\n try { return stateSchema.parse(raw); }\n catch (error) { throw new Error(\"Invalid automation state; original evidence was retained.\", { cause: error }); }\n}\n\n/** Preserve the automation lock location and diagnostics for existing callers. */\nexport function withLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000): Promise<T> {\n return withStoreLock(root, directory, run, waitMs, \"Automation\");\n}\n","import { inspectionGit } from \"./inspection.js\";\nimport { execGit } from \"../utils/git-read.js\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { advisorySchema, digest, findingId, type Finding } from \"./findings.js\";\nimport { manifestPathspecs } from \"./checks/deps-changed.js\";\nimport { readAuditInput } from \"./inputs.js\";\nimport { pathExists } from \"./scope.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { withLock } from \"../automation/store.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst git = async (root: string, ...args: string[]) => (await (\n [\"log\", \"ls-tree\", \"ls-files\", \"merge-base\"].includes(args[0]) ? inspectionGit : execGit\n)(args, { cwd: root, timeout: 10_000, maxBuffer: 8 * 1024 * 1024 })).stdout;\nconst hashSchema = z.string().regex(/^[a-f0-9]{64}$/);\nconst commitSchema = z.string().regex(/^[a-f0-9]{40,64}$/);\nconst evidenceSchema = z.object({\n head: commitSchema, fingerprint: hashSchema, scope: z.array(z.string()).min(1).max(1000),\n tree: z.string().max(2 * 1024 * 1024), lastScopeCommit: commitSchema,\n paths: z.array(z.object({ path: z.string(), exists: z.boolean() })).max(1000),\n});\nconst eventSchema = z.object({\n at: z.string().datetime(), reviewer: z.string().trim().min(1).max(200), note: z.string().trim().min(1).max(2500),\n outcome: z.enum([\"addressed\", \"inapplicable\", \"deferred\"]),\n finding: advisorySchema.refine(finding => finding.evidence.kind !== \"decision-anchor\", \"Decision findings use decision reviews\"), evidence: evidenceSchema,\n});\nconst recordSchema = z.object({ version: z.literal(1), id: hashSchema, events: z.array(eventSchema).min(1).max(200), digest: hashSchema });\ntype ReviewRecord = z.infer<typeof recordSchema>;\nexport const reviewSummarySchema = z.object({\n id: hashSchema, status: z.enum([\"current\", \"reopened\", \"deferred\", \"unverified\"]), reason: z.string(),\n recordPath: z.string().optional(), reviewer: z.string().optional(), note: z.string().optional(),\n outcome: z.enum([\"addressed\", \"inapplicable\", \"deferred\", \"accepted\", \"reaffirmed\", \"retired\"]).optional(),\n reviewedHead: z.string().optional(),\n});\nexport type AdvisoryReviewSummary = z.infer<typeof reviewSummarySchema>;\nexport const advisoryReviewRequest = z.object({\n baselinePath: z.string().min(1), findingId: hashSchema,\n action: z.enum([\"prepare\", \"addressed\", \"inapplicable\", \"deferred\"]).default(\"prepare\"),\n reviewer: eventSchema.shape.reviewer.optional(), note: eventSchema.shape.note.optional(), reviewToken: hashSchema.optional(),\n});\nexport type AdvisoryReviewInput = z.input<typeof advisoryReviewRequest>;\nconst recordPath = (id: string) => `.mason/reviews/advisories/${hashSchema.parse(id)}.json`;\n\nasync function readRecord(root: string, id: string): Promise<ReviewRecord | null> {\n const raw = await readStoreJson(root, recordPath(id));\n if (raw === null) return null;\n const record = recordSchema.parse(raw);\n const { digest: stored, ...payload } = record;\n if (record.id !== id || digest(payload) !== stored || record.events.some(event => findingId(event.finding as Finding) !== id\n || event.evidence.fingerprint !== digest([event.evidence.scope, event.evidence.tree, event.evidence.lastScopeCommit, event.evidence.paths]))) {\n throw new Error(\"Advisory review record is inconsistent or modified; inspect its history.\");\n }\n return record;\n}\n\nfunction scopes(finding: Finding): string[] {\n const files = [finding.anchor.doc], e = finding.evidence;\n if (e.kind === \"decision-anchor\") throw new Error(\"Use review_decision for decision acceptance, reaffirmation or retirement.\");\n if (e.kind === \"doc-behind-manifests\") return [`:(literal)${finding.anchor.doc}`, ...manifestPathspecs(finding.anchor.doc)];\n if (e.kind === \"missing-path\") files.push(...(e.scope?.candidates ?? [e.resolvedPath ?? e.claimed]));\n else if (e.kind === \"missing-script\") files.push(...e.manifestsChecked, ...(e.scope?.candidates ?? []));\n else if (e.kind === \"unmentioned-dir\") files.push(e.dir, ...e.checkedDocs);\n else throw new Error(\"This advisory has no supported review scope.\");\n return [...new Set(files)].map(file => {\n if (normalizeRepoPath(file) !== file) throw new Error(\"Advisory contains an invalid scoped path: \" + file);\n return `:(literal)${file}`;\n }).sort();\n}\n\n/** Committed, scoped Git evidence survives unrelated and review-record-only commits. */\nasync function reviewEvidence(root: string, finding: Finding) {\n if (normalizeRepoPath(finding.anchor.doc) !== finding.anchor.doc) throw new Error(\"Invalid advisory document path.\");\n const scope = scopes(finding);\n const head = (await git(root, \"rev-parse\", \"HEAD\")).trim();\n const tracked = (await git(root, \"ls-files\", \"--cached\", \"-z\", \"--\", ...scope)).split(\"\\0\").filter(Boolean);\n if (tracked.length > 20_000) throw new Error(\"Advisory scope exceeds 20,000 tracked files.\");\n const [tree, status, lastScopeCommit, document] = await Promise.all([\n tracked.length ? git(root, \"ls-tree\", \"-r\", \"-z\", \"HEAD\", \"--\", ...tracked.map(file => `:(literal)${file}`)) : \"\",\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...scope),\n git(root, \"log\", \"-1\", \"--format=%H\", \"HEAD\", \"--\", ...scope).then(value => value.trim()),\n readAuditInput(root, finding.anchor.doc),\n ]);\n if (!document?.trim()) throw new Error(\"Original advisory document is missing, empty or unreadable.\");\n if (tree.length > 2 * 1024 * 1024 || tree.split(\"\\0\").length > 20_000) throw new Error(\"Advisory scope is too large for a complete review; narrow the documentation scope.\");\n // Reject symlinks rather than trusting a blob that describes an external target.\n for (const entry of tree.split(\"\\0\").filter(Boolean)) {\n const tab = entry.indexOf(\"\\t\"), file = entry.slice(tab + 1);\n if (entry.startsWith(\"120000 \") || entry.startsWith(\"160000 \")) throw new Error(\"Symlink or submodule in advisory review scope: \" + file);\n await storePath(root, file);\n }\n // Path checks observe presence even for explicitly documented ignored\n // outputs. Git alone cannot detect those appearing or disappearing.\n const paths = finding.evidence.kind === \"missing-path\" ? await Promise.all(\n (finding.evidence.scope?.candidates ?? [finding.evidence.resolvedPath ?? finding.evidence.claimed])\n .map(async file => ({ path: file, exists: await pathExists(root, file) }))) : [];\n let dirty = status.length > 0;\n if (finding.evidence.kind === \"missing-script\") {\n for (const file of [...finding.evidence.manifestsChecked, ...(finding.evidence.scope?.candidates ?? [])]) {\n if (!tracked.includes(file) && await pathExists(root, file)) dirty = true;\n }\n }\n const fingerprint = digest([scope, tree, lastScopeCommit, paths]);\n if ((await git(root, \"rev-parse\", \"HEAD\")).trim() !== head) throw new Error(\"HEAD changed while collecting review evidence.\");\n return { ...evidenceSchema.parse({ head, scope, tree, lastScopeCommit, paths, fingerprint }), dirty,\n documentDigest: digest(document) };\n}\n\nasync function decisionAssessment(root: string, finding: Finding, baselineHead: string): Promise<AdvisoryReviewSummary | null> {\n const evidence = finding.evidence;\n if (evidence.kind !== \"decision-anchor\") return null;\n const id = findingId(finding);\n const store = await loadDecisionStore(root);\n if (store.diagnostics.length) throw new Error(\"Decision records have unavailable or malformed evidence; review cannot be confirmed.\");\n const record = store.records.find(record => record.id === evidence.decisionId);\n if (!record || record.version !== 2) return null;\n const events = record.history.filter(event => [\"accepted\", \"reaffirmed\", \"retired\"].includes(event.kind));\n const event = events.at(-1);\n if (!event?.evidence || !event.actor || !event.note || !event.evidence.historyAvailable || event.evidence.localChanges.length) return null;\n try { await git(root, \"merge-base\", \"--is-ancestor\", baselineHead, event.evidence.headHash); }\n catch { return null; }\n const drift = await computeDecisionDrift(root, [record]);\n if (!drift.historyAvailable) throw new Error(\"Decision review history is unavailable.\");\n const retired = record.status === \"retired\" && event.kind === \"retired\";\n const current = retired || record.status === \"active\" && record.approval === \"accepted\"\n && drift.freshness?.[record.id] === \"current\" && !drift.pendingProposals?.[record.id];\n return { id, status: current ? \"current\" : \"reopened\", outcome: event.kind as \"accepted\" | \"reaffirmed\" | \"retired\",\n reviewer: event.actor, note: event.note, reviewedHead: event.evidence.headHash,\n recordPath: `.mason/decisions/${record.id}.json`, reason: current\n ? \"The existing decision review records acceptance, reaffirmation or retirement covering the original finding.\"\n : \"Decision content or anchor evidence changed after its review; review the decision again.\" };\n}\n\nexport async function assessAdvisory(root: string, finding: Finding, baselineHead: string): Promise<AdvisoryReviewSummary | null> {\n if (\"confidence\" in finding) return null;\n const id = findingId(finding);\n try {\n if (finding.evidence.kind === \"decision-anchor\") return await decisionAssessment(root, finding, baselineHead);\n const record = await readRecord(root, id);\n if (!record) return null;\n const event = record.events.at(-1)!;\n // Use the reviewed scope, not a newly shortened finding's preview of that scope.\n const current = await reviewEvidence(root, event.finding as Finding);\n await git(root, \"merge-base\", \"--is-ancestor\", event.evidence.head, current.head);\n const base = { id, recordPath: recordPath(id), reviewer: event.reviewer, note: event.note,\n outcome: event.outcome, reviewedHead: event.evidence.head };\n if (current.dirty || current.fingerprint !== event.evidence.fingerprint || digest(scopes(finding)) !== digest(event.evidence.scope)) return { ...base, status: \"reopened\", reason: \"Relevant document or repository evidence changed after the assessment; prepare a new review.\" };\n return { ...base, status: event.outcome === \"deferred\" ? \"deferred\" : \"current\", reason: event.outcome === \"deferred\"\n ? \"The review was deferred and remains outstanding.\" : \"An explicit assessment covers the current committed scope. This does not approve an engineering decision or certify correctness.\" };\n } catch (error) { return { id, status: \"unverified\", reason: error instanceof Error ? error.message : String(error) }; }\n}\n\n/** Fingerprint receipt content so concurrent automation cannot publish an older assessment. */\nexport async function advisoryReviewInventory(root: string) {\n let names: string[];\n try { names = await fs.readdir(await storePath(root, \".mason/reviews/advisories\")); }\n catch (error) { if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return []; throw error; }\n if (names.length > 5000) throw new Error(\"Advisory review inventory exceeds 5,000 records.\");\n return Promise.all(names.filter(name => name.endsWith(\".json\")).sort().map(async name => [name, await readAuditInput(root, \".mason/reviews/advisories/\" + name)]));\n}\n\nexport async function reviewAdvisory(rootDir: string, input: AdvisoryReviewInput) {\n const root = await fs.realpath(rootDir), request = advisoryReviewRequest.parse(input);\n const { loadRepairBaseline } = await import(\"./repair.js\");\n const baseline = await loadRepairBaseline(root, request.baselinePath);\n const finding = [...baseline.original.advisories, ...(baseline.original.suppressedAdvisories ?? [])].find(f => findingId(f) === request.findingId);\n if (!finding) throw new Error(\"No advisory with this findingId in the original baseline. Provable issues must be repaired and rechecked.\");\n if (finding.evidence.kind === \"decision-anchor\") return { status: \"decision-review-required\", decisionId: finding.evidence.decisionId,\n hint: \"Use review_decision to prepare evidence and record authorized acceptance, reaffirmation or retirement, then verify this original repair baseline. An advisory assessment cannot approve a decision.\" };\n const prepare = async () => {\n const record = await readRecord(root, request.findingId);\n const evidence = await reviewEvidence(root, finding);\n await git(root, \"merge-base\", \"--is-ancestor\", baseline.original.headHash!, evidence.head);\n const token = digest({ baseline: baseline.original, finding, evidence, record });\n return { record, evidence, token };\n };\n if (request.action === \"prepare\") {\n const state = await prepare();\n let diff: string | null = null, diffNote: string | undefined;\n const from = finding.evidence.kind === \"doc-behind-manifests\" ? finding.evidence.docLastCommit.hash : baseline.original.headHash!;\n try {\n const full = await git(root, \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", from, state.evidence.head, \"--\", ...state.evidence.scope);\n diff = full.slice(0, 16000); if (full.length > diff.length) diffNote = \"Diff preview truncated; inspect the full scoped diff before reviewing.\";\n } catch { diffNote = \"Diff preview unavailable; inspect the original cited evidence directly before reviewing.\"; }\n if ((await prepare()).token !== state.token) throw new Error(\"Review evidence changed during preparation; retry.\");\n return { status: \"prepared\", findingId: request.findingId, finding, evidence: state.evidence,\n history: state.record?.events ?? [], reviewToken: state.token, diff, diffNote,\n hint: \"Inspect the original finding, scoped document and relevant code changes. Record addressed, inapplicable or deferred only when the user or cited project review authorizes that assessment. Supply the actual reviewer, reason in note and reviewToken. Relevant edits must be committed first. Deferral remains outstanding. Review identities are recorded assertions, not authenticated approvals.\" };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) throw new Error(\"Prepare first; recording an assessment requires reviewToken, reviewer and note.\");\n return withLock(root, \".mason/reports/advisory-review-locks/\" + request.findingId, async () => {\n const state = await prepare();\n if (state.token !== request.reviewToken) throw new Error(\"Review conflict: evidence or review history changed since preparation. Prepare and inspect a new review.\");\n if (state.evidence.dirty) throw new Error(\"Commit relevant document and repository edits before recording the assessment. Unrelated local work may remain.\");\n if ((state.record?.events.length ?? 0) >= 200) throw new Error(\"Review history limit reached; existing events were retained.\");\n const { dirty, documentDigest, ...evidence } = state.evidence;\n const event = eventSchema.parse({ at: new Date().toISOString(), reviewer: request.reviewer, note: request.note,\n outcome: request.action, finding, evidence });\n const payload = { version: 1 as const, id: request.findingId, events: [...(state.record?.events ?? []), event] };\n if ((await prepare()).token !== state.token) throw new Error(\"Review conflict: evidence changed while recording the assessment.\");\n await writeStoreJson(root, recordPath(request.findingId), { ...payload, digest: digest(payload) });\n return { status: \"recorded\", recordPath: recordPath(request.findingId), event,\n hint: \"Review and commit this assessment record through the normal project workflow, then verify the original repair baseline. Relevant changes reopen the assessment; deferral remains outstanding.\" };\n });\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport 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 { assessAdvisory } from \"./advisory-review.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 discovered instruction files and READMEs\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 return profilePhase(\"audit.current\", () => auditCurrent(rootDir, options));\n}\n\nasync function auditCurrent(rootDir: string, options: AuditOptions): 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 scope: d.scope,\n kind: d.kind,\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 const changesByCommit = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n const hash = doc.lastCommit?.hash;\n if (hash && !changesByCommit.has(hash)) changesByCommit.set(hash, await getChangesWithStatus(resolvedRoot, hash));\n changesSinceDoc.set(doc.path, hash ? changesByCommit.get(hash)! : null);\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 const reviews = (await Promise.all([...report.advisories, ...report.suppressedAdvisories!]\n .map(finding => assessAdvisory(resolvedRoot, finding, headHash)))).filter(review => review !== null);\n if (reviews.length) report.advisoryReviews = reviews;\n return report;\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit, type AuditOptions } from \"./audit.js\";\nimport { discoverDocPaths } 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, normalizeRepoPath } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { checkSchema, commitSchema, issueSchema, advisorySchema, digest, findingId, type Finding } from \"./findings.js\";\nimport { assessAdvisory, advisoryReviewInventory, reviewSummarySchema, type AdvisoryReviewSummary } from \"./advisory-review.js\";\nexport { checkResultSchema, findingId } from \"./findings.js\";\nconst count = z.number().int().nonnegative();\n\nexport const 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.string().refine(value => normalizeRepoPath(value) === value), scope: z.string().optional(),\n kind: z.enum([\"instructions\", \"readme\"]).optional(), 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});\n\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\n\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n review?: AdvisoryReviewSummary;\n}\nexport const repairFindingSchema = z.object({\n id: z.string(), original: z.union([issueSchema, advisorySchema]),\n status: z.enum([\"resolved\", \"unresolved\", \"review-required\", \"unverified\"]), reason: z.string(),\n current: z.union([issueSchema, advisorySchema]).optional(),\n review: reviewSummarySchema.optional(),\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\nfunction recheckable(finding: Finding): boolean {\n return !(\"confidence\" in finding) && finding.resolution === \"recheck\"\n && [\"deleted-reference\", \"dead-command\", \"new-module\"].includes(finding.type)\n && [\"missing-path\", \"missing-script\", \"unmentioned-dir\"].includes(finding.evidence.kind);\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 await discoverDocPaths(root)) {\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 = {}): Promise<AuditReport | null> {\n return profilePhase(\"repair.audit\", () => readStableAudit(root, checks, options));\n}\n\nasync function readStableAudit(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 return prepareOriginal(rootDir, checks, options);\n}\n\ninterface RepairSession {\n audit: (checks: CheckName[]) => Promise<AuditReport | null>;\n document: (file: string) => Promise<string | null>;\n history: (head: string) => ReturnType<typeof getChangesWithStatus>;\n assessment: typeof assessAdvisory;\n}\n\n/** Automation shares one inspection across its audit and original baselines.\n * Its required validator re-reads the full input inventory before this returns.\n * Standalone prepare/verify retain their own stability guards below.\n */\nexport async function withRepairSession<T>(root: string, options: AuditOptions, run: (session: {\n prepare: () => ReturnType<typeof prepareRepair>;\n verify: (baselinePath: string) => Promise<RepairVerification>;\n currentAudit: () => Promise<AuditReport | null>;\n}) => Promise<T>, validate: () => Promise<void>, cachedAudit?: AuditReport): Promise<T> {\n const head = await getCurrentGitHash(root);\n const audits = new Map<string, Promise<AuditReport | null>>();\n const documents = new Map<string, Promise<string | null>>();\n const history = new Map<string, ReturnType<typeof getChangesWithStatus>>();\n const assessments = new Map<string, ReturnType<typeof assessAdvisory>>();\n const memo = <T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> => {\n if (!cache.has(key)) cache.set(key, read());\n return cache.get(key)!;\n };\n const session: RepairSession = {\n audit: checks => memo(audits, [...checks].sort().join(\",\"), async () => {\n if (cachedAudit && cachedAudit.headHash === head && cachedAudit.root === root &&\n digest([...checks].sort()) === digest([...(cachedAudit.checksRun ?? [])].sort())) {\n // Raw audit results are cached, never their approval assessments. Original\n // baselines may refer to scopes no longer mentioned in the current docs.\n const current = structuredClone(cachedAudit);\n const reviews = (await Promise.all(allFindings(current).map(f => assessAdvisory(root, f, head)))).filter(r => r !== null);\n delete current.advisoryReviews;\n if (reviews.length) current.advisoryReviews = reviews;\n return current;\n }\n return computeAudit(root, { ...options, checks });\n }),\n document: file => memo(documents, file, async () => readBoundedFile(await storePath(root, file), 10 * 1024 * 1024)),\n history: head => memo(history, head, () => getChangesWithStatus(root, head)),\n assessment: (dir, finding, head) => memo(assessments, digest([dir, finding, head]), () => assessAdvisory(dir, finding, head)),\n };\n const result = await run({\n prepare: () => prepareOriginal(root, ALL_CHECKS, options, session),\n verify: baseline => profilePhase(\"repair.verify\", () => verifyOriginal(root, baseline, options, session)),\n currentAudit: () => session.audit(ALL_CHECKS),\n });\n await validate();\n return result;\n}\n\nasync function prepareOriginal(rootDir: string, checks: CheckName[], options: AuditOptions, session?: RepairSession) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await (session ? session.audit(selected) : 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 loadRepairBaseline(rootDir: string, baselinePath: string) {\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 return { root, relative, original };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string, options: AuditOptions = {}): Promise<RepairVerification> {\n return profilePhase(\"repair.verify\", () => verifyOriginal(rootDir, baselinePath, options));\n}\n\nasync function verifyOriginal(rootDir: string, baselinePath: string, options: AuditOptions, session?: RepairSession): Promise<RepairVerification> {\n const { root, relative, original } = await loadRepairBaseline(rootDir, baselinePath);\n const diagnostics: string[] = [];\n let reviewDigest: string | undefined;\n let current: AuditReport | null = null;\n try {\n if (!session) reviewDigest = digest(await advisoryReviewInventory(root));\n current = await (session ? session.audit(original.checksRun!) : 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 (!allFindings(original).some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await (session ? session.document(doc.path) : 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 (session ? session.history(original.headHash!) : 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 = await Promise.all(originalFindings.map(async (finding): Promise<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 (now && (\"confidence\" in finding || \"confidence\" in 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 const review = await (session?.assessment ?? assessAdvisory)(root, now ?? finding, original.headHash!);\n if (review) {\n if (review.status === \"unverified\") return { ...base, review, status: \"unverified\", reason: review.reason };\n if (review.status === \"current\") return { ...base, review, status: \"resolved\", reason: review.reason };\n return { ...base, review, status: \"review-required\", reason: review.reason };\n }\n if (!(\"confidence\" in finding) && (!recheckable(finding) || now)) {\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 if (!session) try {\n if (reviewDigest !== digest(await advisoryReviewInventory(root)) || current?.headHash !== await getCurrentGitHash(root)) {\n diagnostics.push(\"HEAD or advisory review records changed during verification; repeat against stable evidence.\");\n for (const finding of findings) { finding.status = \"unverified\"; finding.reason = diagnostics.at(-1)!; }\n }\n } catch (error) {\n diagnostics.push(String(error));\n for (const finding of findings) { finding.status = \"unverified\"; finding.reason = \"Advisory review evidence became unavailable during verification.\"; }\n }\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const reviewedIds = new Set(current?.advisoryReviews?.filter(review => review.status === \"current\").map(review => review.id));\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) && !reviewedIds.has(findingId(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 the check or covered by an explicit assessment of current evidence; inspect each finding's reason and 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 findingId: \" + f.id),\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 { execGit } from \"../utils/git-read.js\";\nimport { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport fg from \"fast-glob\";\nimport { z } from \"zod\";\nimport { discoverDocPaths } from \"../audit/docs.js\";\nimport { pathClaimScope, pathExists, optionalMasonPath, gitMetadataPath } from \"../audit/scope.js\";\nimport { extractClaims } from \"../audit/claims.js\";\nimport { checkResultSchema } from \"../audit/repair.js\";\nimport { CHECKS, type CheckResult } from \"../audit/checks/index.js\";\nimport type { AuditOptions } from \"../audit/audit.js\";\nimport type { CheckName } from \"../audit/types.js\";\nimport { readAuditInput } from \"../audit/inputs.js\";\nimport { moduleCandidates, moduleDocumentation } from \"../audit/checks/new-module.js\";\nimport { resolveDocCountSource } from \"../audit/checks/stale-count.js\";\nimport { commandInputs } from \"../audit/checks/dead-command.js\";\nimport { storePath } from \"../utils/storage.js\";\nimport { advisoryReviewInventory } from \"../audit/advisory-review.js\";\n\ndeclare const PKG_VERSION: string;\nconst engineVersion = typeof PKG_VERSION === \"string\" ? PKG_VERSION : \"development\";\nexport const hash = (value: unknown): string => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\nexport async function git(root: string, ...args: string[]): Promise<string> {\n return profilePhase(\"automation.git\", async () => (await execGit(args, { cwd: root, maxBuffer: 16 * 1024 * 1024, timeout: 10000 })).stdout);\n}\n\nexport async function workspace(dir: string) {\n const root = await fs.realpath((await git(dir, \"rev-parse\", \"--show-toplevel\")).trim());\n const [gitDir, branch] = await Promise.all([\n git(root, \"rev-parse\", \"--absolute-git-dir\").then(value => fs.realpath(value.trim())),\n git(root, \"symbolic-ref\", \"--quiet\", \"HEAD\").then(value => value.trim(), () => \"detached\"),\n ]);\n return { root, gitDir, branch, directory: \".mason/reports/automation/\" + hash([root, gitDir, branch]).slice(0, 24) };\n}\n\nconst content = readAuditInput;\n\nexport interface Inputs {\n fingerprint: string;\n head: string;\n docs: Record<string, string | null>;\n keys: Record<CheckName, string>;\n}\n\nexport async function readInputs(root: string): Promise<Inputs> {\n return profilePhase(\"automation.inputs\", () => collectInputs(root));\n}\n\nasync function collectInputs(root: string): Promise<Inputs> {\n const docPaths = await discoverDocPaths(root);\n const [headText, docStatus, shallowPath, replacements] = await Promise.all([\n git(root, \"rev-parse\", \"HEAD\"),\n docPaths.length ? git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...docPaths.map(p => `:(literal)${p}`)) : \"\",\n git(root, \"rev-parse\", \"--git-path\", \"shallow\"),\n git(root, \"for-each-ref\", \"--format=%(refname) %(objectname)\", \"refs/replace\"),\n ]);\n const head = headText.trim();\n let shallow: string | null = null;\n try { shallow = await fs.readFile(path.resolve(root, shallowPath.trim()), \"utf8\"); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n const docs: Record<string, string | null> = {};\n const docContents: Array<[string, string | null]> = [];\n const parsedDocs = [];\n const claims: Array<[string, boolean, boolean]> = [];\n const presence = new Map<string, Promise<boolean>>();\n const exists = (file: string) => {\n if (!presence.has(file)) presence.set(file, pathExists(root, file));\n return presence.get(file)!;\n };\n for (const file of docPaths) {\n const text = await content(root, file);\n docs[file] = text === null ? null : hash(text);\n docContents.push([file, text]);\n const parsed = { path: file, content: text ?? \"\", claims: extractClaims(text ?? \"\") };\n parsedDocs.push(parsed);\n for (const claim of parsed.claims.paths) {\n const scope = pathClaimScope(file, claim);\n if (scope?.candidates.some(gitMetadataPath)) continue;\n for (const candidate of scope?.candidates ?? []) {\n if (optionalMasonPath(candidate)) continue;\n const [filePresent, parentPresent] = await Promise.all([exists(candidate), exists(path.posix.dirname(candidate))]);\n claims.push([candidate, filePresent, parentPresent]);\n }\n }\n }\n const combinedDocs = moduleDocumentation(parsedDocs);\n const countClaims = parsedDocs.flatMap(doc => doc.claims.counts.map(claim => ({ doc: doc.path, claim })));\n const decisionDirectory = await storePath(root, \".mason/decisions\");\n const decisionPresence = await fs.lstat(decisionDirectory).then(stat => stat.isDirectory() ? \"directory\" : \"file\", error => {\n if (error.code === \"ENOENT\") return \"absent\";\n throw error;\n });\n const [modules, counts, commands, decisionFiles] = await Promise.all([\n combinedDocs ? moduleCandidates(root, combinedDocs) : [],\n Promise.all(countClaims.map(({ doc, claim }) => resolveDocCountSource(root, doc, claim))),\n commandInputs(root, parsedDocs),\n fg(\".mason/decisions/*.json\", { cwd: root, dot: true, onlyFiles: false, followSymbolicLinks: false }),\n ]);\n const decisions = await Promise.all(decisionFiles.sort().map(async file => {\n await storePath(root, file);\n return [file, await content(root, file)];\n }));\n // Decision freshness observes tracked and local anchor changes; other checks\n // do not need a repository-wide status or index scan.\n const [status, index] = decisions.length ? await Promise.all([\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", \".\", \":(exclude).mason/reports\"),\n git(root, \"ls-files\", \"--stage\", \"-z\", \"--\", \".\", \":(exclude).mason/reports\"),\n ]) : [\"\", \"\"];\n const common = [5, engineVersion, head, shallow, replacements, docContents];\n const keys: Record<CheckName, string> = {\n \"deleted-reference\": hash([common, claims, docStatus]),\n \"new-module\": hash([common, modules]),\n \"stale-count\": hash([common, counts]),\n \"dead-command\": hash([common, commands]),\n \"deps-changed\": hash([common, docStatus]),\n \"decision-anchor-drift\": hash([common, decisionPresence, decisions, status, index]),\n };\n return { fingerprint: hash([keys, await advisoryReviewInventory(root)]), head, docs, keys };\n}\n\nconst cacheSchema = z.object({ version: z.literal(1), entries: z.record(z.object({ key: z.string(), result: checkResultSchema })), digest: z.string() });\nexport function checkCache(raw: unknown, inputs: Inputs) {\n let entries: Record<string, { key: string; result: CheckResult }> = {};\n let diagnostic: string | null = null;\n if (raw !== null) {\n const parsed = cacheSchema.safeParse(raw);\n if (parsed.success && parsed.data.digest === hash(parsed.data.entries)) entries = parsed.data.entries as Record<string, { key: string; result: CheckResult }>;\n else diagnostic = \"Discarded an invalid automation cache; checks are being recomputed.\";\n }\n const ran = new Set<CheckName>(), reused = new Set<CheckName>();\n const options: AuditOptions = { runCheck: async (name, ctx) => {\n if (entries[name]?.key === inputs.keys[name]) {\n reused.add(name);\n return structuredClone(entries[name].result);\n }\n const result = await profilePhase(\"check.\" + name, () => CHECKS[name](ctx));\n ran.add(name);\n // An unavailable check must be retried even if the file inputs match.\n if (!result.skipped.length) entries[name] = { key: inputs.keys[name], result };\n else delete entries[name];\n return result;\n } };\n return { options, ran, reused, diagnostic,\n has: (name: CheckName) => entries[name]?.key === inputs.keys[name] && !entries[name].result.skipped.length,\n serialize: () => {\n const canonical = cacheSchema.shape.entries.parse(entries);\n return { version: 1, entries: canonical, digest: hash(canonical) };\n } };\n}\n","import { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\n\nexport const setupHostSchema = z.object({\n configuredVersion: z.string(), revision: z.string().uuid(), fingerprint: z.string(), mcpFingerprint: z.string(),\n instructions: z.array(z.string()),\n});\nexport const setupSchema = z.object({ version: z.literal(2), hosts: z.object({\n codex: setupHostSchema.optional(), claude: setupHostSchema.optional(),\n}) });\nexport const SETUP_PATH = \".mason/local/setup.json\";\nexport type SetupConfig = z.infer<typeof setupSchema>;\nexport async function loadSetup(root: string): Promise<SetupConfig | null> {\n const raw = await readStoreJson(root, SETUP_PATH);\n if (raw === null) return null;\n return setupSchema.parse(raw);\n}\n\nconst receiptSchema = z.object({ version: z.literal(1), host: z.enum([\"codex\", \"claude\"]),\n status: z.enum([\"installing\", \"configured\"]), initialReportPath: z.string(), initialBaselinePaths: z.array(z.string()),\n root: z.string(), revision: z.string().uuid(), configuredAt: z.string().optional() });\nexport async function loadSetupReceipt(root: string, directory: string, host: \"codex\" | \"claude\") {\n const raw = await readStoreJson(root, directory + \"/setup-\" + host + \".json\");\n if (raw === null) return null;\n const receipt = receiptSchema.parse(raw);\n if (receipt.root !== root || receipt.host !== host) throw new Error(\"Setup receipt belongs to another installation.\");\n return receipt;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fs from \"node:fs/promises\";\nimport type { Host } from \"../automation/store.js\";\nimport { git } from \"../automation/evidence.js\";\nimport { loadSetup } from \"./model.js\";\n\ndeclare const PKG_VERSION: string;\nexport const executingVersion = () => typeof PKG_VERSION === \"string\" ? PKG_VERSION : \"development\";\n\n// Windows needs cmd to launch both npm's and the standalone installer's .cmd shim.\nexport function globalCommand(args: string[], platform = process.platform) {\n return platform === \"win32\" ? { command: \"cmd.exe\", args: [\"/d\", \"/s\", \"/c\", \"mason\", ...args] }\n : { command: \"mason\", args };\n}\nexport const mcpCommand = (host: Host) => globalCommand([\"--setup-host\", host, \"mcp\"]);\nexport const hookCommand = (host: Host) => `mason --setup-host ${host} auto`;\n\n/** Probe the same PATH command the host will use; never download during setup. */\nexport async function installedCommand() {\n const invocation = globalCommand([\"internal-integration-version\"]);\n try {\n const { stdout } = await promisify(execFile)(invocation.command, invocation.args,\n { timeout: 5000, maxBuffer: 8192, windowsHide: true });\n const result = JSON.parse(stdout);\n if (result.protocol !== 1 || typeof result.version !== \"string\") throw new Error(\"Unsupported Mason integration protocol.\");\n return { available: true, version: result.version as string, message: null };\n } catch {\n return { available: false, version: null, message: \"An up-to-date mason command is not available on this process's PATH. Install or upgrade Mason, then reopen your terminal or desktop assistant and rerun mason setup.\" };\n }\n}\n\n/** Replaces the environment previously supplied by generated project launchers. */\nexport async function prepareLaunch(host: Host, options: { dir?: string; allowInactive?: boolean } = {}) {\n const root = await fs.realpath((await git(options.dir ?? process.cwd(), \"rev-parse\", \"--show-toplevel\")).trim());\n const entry = (await loadSetup(root))?.hosts[host];\n process.env.MASON_SETUP_ROOT = root;\n process.env.MASON_SETUP_HOST = host;\n delete process.env.MASON_SETUP_REVISION;\n if (!entry) {\n if (options.allowInactive) return false;\n throw new Error(`Mason is not configured locally for ${host}. Run mason setup --host ${host} in this checkout.`);\n }\n process.env.MASON_SETUP_REVISION = entry.revision;\n return true;\n}\n\nexport function inactiveSetupMessage(): string | null {\n const host = process.env.MASON_SETUP_HOST;\n if (!process.env.MASON_SETUP_ROOT || process.env.MASON_SETUP_REVISION || (host !== \"claude\" && host !== \"codex\")) return null;\n return `Mason MCP is available, but automatic hooks are inactive in ${process.env.MASON_SETUP_ROOT}. Run mason setup --host ${host} in that checkout, review the host configuration, then restart the assistant. Setup has not been performed automatically.`;\n}\n","import { createHash } from \"node:crypto\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { normalizeFeatureType, type FeatureEntry, type FlowEntry } from \"./snapshot.js\";\n\nexport type SnapshotEntryKind = \"feature\" | \"flow\";\nexport interface SnapshotVerdict {\n ok: boolean;\n note?: string;\n // Optional at the input boundary so older clients receive actionable feedback.\n kind?: SnapshotEntryKind;\n reviewToken?: string;\n}\n\nexport const VERIFY_MAX_FILES_PER_ENTRY = 8;\nconst VERIFY_SKELETON_CHARS = 500;\ntype FileAccess = Awaited<ReturnType<typeof createFileAccess>>;\n\n/** Verification metadata and refresh timestamps do not change an entry's meaning. */\nexport function snapshotEntryContent(entry: FeatureEntry | FlowEntry) {\n return {\n description: entry.description,\n files: \"files\" in entry ? entry.files : undefined,\n chain: \"chain\" in entry ? entry.chain : undefined,\n tests: \"files\" in entry ? entry.tests : undefined,\n type: \"files\" in entry ? normalizeFeatureType(entry.type) : undefined,\n };\n}\n\ntype SourceEvidence = Array<{ path: string; hash: string | null }>;\nconst sourceHash = (content: string) => createHash(\"sha256\").update(content).digest(\"hex\");\n\nfunction reviewToken(kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry, evidence: SourceEvidence) {\n return createHash(\"sha256\").update(JSON.stringify({\n version: 1, kind, name, entry: snapshotEntryContent(entry), evidence,\n })).digest(\"hex\");\n}\n\n/** Bind the token to the exact bounded source reads used to produce the previews. */\nexport async function prepareSnapshotReview(\n access: FileAccess,\n kind: SnapshotEntryKind,\n name: string,\n entry: FeatureEntry | FlowEntry,\n) {\n const files = \"files\" in entry ? entry.files : entry.chain;\n const evidence: SourceEvidence = [];\n const skeletons: Array<{ path: string; content: string } | { path: string; missing: true }> = [];\n for (const file of files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n const full = await access.read(file);\n evidence.push({ path: file, hash: full ? sourceHash(full.content) : null });\n skeletons.push(full ? { path: full.path, content: full.content.slice(0, VERIFY_SKELETON_CHARS) } : { path: file, missing: true });\n }\n return { reviewToken: reviewToken(kind, name, entry, evidence), skeletons, truncated: files.length > VERIFY_MAX_FILES_PER_ENTRY };\n}\n\n/** Cache only hashes/availability for one trust response, never source strings or previews. */\nexport function createSnapshotEvidenceReader(access: FileAccess) {\n const hashes = new Map<string, Promise<string | null>>();\n return async (kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry) => {\n const files = \"files\" in entry ? entry.files : entry.chain;\n const evidence: SourceEvidence = [];\n for (const file of files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n let hash = hashes.get(file);\n if (!hash) {\n hash = access.read(file).then(full => full ? sourceHash(full.content) : null);\n hashes.set(file, hash);\n }\n evidence.push({ path: file, hash: await hash });\n }\n return {\n reviewToken: reviewToken(kind, name, entry, evidence),\n evidenceAvailable: evidence.length > 0 && evidence.every(file => file.hash !== null),\n };\n };\n}\n","import { assessTrust, type Freshness, type TrustState } from \"../context/trust.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { createSnapshotEvidenceReader, type SnapshotEntryKind } from \"./review.js\";\nimport type { FeatureEntry, FlowEntry, Snapshot } from \"./snapshot.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\n\n/** Recheck reviewed evidence for one retrieval; never persist or reuse it across calls. */\nexport function createSnapshotTrustReader(root: string) {\n // Share the file policy/inventory, and initialize only for token-bearing verdicts.\n let reader: Promise<ReturnType<typeof createSnapshotEvidenceReader> | null> | undefined;\n return async (kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry, freshness: Freshness): Promise<TrustState> => {\n const trust = assessTrust(entry, freshness);\n const verdict = entry.verificationFailed ? \"failed\" : entry.verifiedAt ? \"passed\" : undefined;\n if (!verdict) return trust;\n trust.recordedVerdict = verdict;\n const unknown = (reason: string) => {\n trust.verification = \"unknown\";\n trust.reasons.push(reason);\n return trust;\n };\n if (!entry.verificationToken || !/^[a-f0-9]{64}$/.test(entry.verificationToken)) return unknown(\"The recorded verdict has no supported evidence token; obtain a fresh verify_snapshot review.\");\n try {\n reader ??= createFileAccess(root).then(createSnapshotEvidenceReader).catch(() => null);\n const readReview = await reader;\n if (!readReview) return unknown(\"Verification source evidence could not be read under the current file policy.\");\n const review = await readReview(kind, name, entry);\n if (!review.evidenceAvailable) {\n return unknown(\"Verification source evidence is missing, excluded, unreadable, or empty; the recorded verdict cannot be confirmed.\");\n }\n if (review.reviewToken !== entry.verificationToken) {\n trust.verification = \"stale\";\n trust.reasons.push(\"The entry or sampled source contents differ from the recorded verification evidence; obtain a fresh review.\");\n }\n return trust;\n } catch {\n return unknown(\"Verification source evidence could not be read under the current file policy.\");\n }\n };\n}\n\n/** Walk the catalog sequentially to keep source reads bounded on large maps. */\nexport async function readSnapshotTrustIndex(readTrust: ReturnType<typeof createSnapshotTrustReader>, snapshot: Snapshot, drift: DriftReport | null) {\n const features: Record<string, TrustState> = Object.create(null), flows: Record<string, TrustState> = Object.create(null);\n for (const [name, entry] of Object.entries(snapshot.features)) {\n features[name] = await readTrust(\"feature\", name, entry, drift?.featureFreshness?.[name] ?? \"unknown\");\n }\n for (const [name, entry] of Object.entries(snapshot.flows)) {\n flows[name] = await readTrust(\"flow\", name, entry, drift?.flowFreshness?.[name] ?? \"unknown\");\n }\n return { features, flows };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { storePath } from \"../utils/storage.js\";\n\nexport interface FileEdit { path: string; before: string | null; after: string }\nexport interface RemovalEdit { path: string; before: string | null; after: null }\nexport async function readText(root: string, file: string): Promise<string | null> {\n try {\n const text = await readBoundedFile(await storePath(root, file), 2 * 1024 * 1024);\n if (text === null) throw new Error(\"Setup input is not a regular file or exceeds 2 MiB: \" + file);\n return text;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\n/** Preserve all bytes outside one unambiguous managed block. */\nexport function managedBlock(text: string, start: string, end: string, body: string): string {\n const starts = text.split(start).length - 1, ends = text.split(end).length - 1;\n if (starts !== ends || starts > 1 || starts === 1 && text.indexOf(end) < text.indexOf(start)) {\n throw new Error(\"Ambiguous Mason instruction/configuration markers; repair the marked block before setup.\");\n }\n const eol = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const block = [start, body.replace(/\\r?\\n/g, eol), end].join(eol);\n if (starts) return text.slice(0, text.indexOf(start)) + block + text.slice(text.indexOf(end) + end.length);\n return text + (text.length && !text.endsWith(\"\\n\") ? eol : \"\") + (text.length ? eol : \"\") + block + eol;\n}\n\n/** Compare before replacing or removing: retain a user's concurrent edit. */\nexport async function applyEdit(root: string, edit: FileEdit | RemovalEdit): Promise<boolean> {\n const current = await readText(root, edit.path);\n if (current === edit.after) return false;\n if (current !== edit.before) throw new Error(\"Integration input changed during update: \" + edit.path + \". Rerun the requested command to resume.\");\n if (edit.after === null) {\n const file = await storePath(root, edit.path);\n if (await readText(root, edit.path) !== edit.before) throw new Error(\"Input changed during removal: \" + edit.path);\n await fs.unlink(file);\n return true;\n }\n const file = await storePath(root, edit.path, true);\n const temporary = path.join(path.dirname(file), \".mason-setup-\" + randomUUID() + \".tmp\");\n try {\n const mode = await fs.stat(file).then(s => s.mode & 0o777, () => 0o600);\n const handle = await fs.open(temporary, \"wx\", mode);\n try { await handle.writeFile(edit.after, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n if (await readText(root, edit.path) !== edit.before) throw new Error(\"Integration input changed during update: \" + edit.path);\n await fs.rename(temporary, file);\n return true;\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import os from \"node:os\";\nimport fs from \"node:fs/promises\";\nimport { withLock } from \"./store.js\";\nimport { hash, workspace } from \"./evidence.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\n\nconst failureSchema = z.object({\n code: z.enum([\"inputs-changed\", \"storage-full\", \"busy\", \"invalid-input\", \"history-unavailable\", \"invalid-evidence\", \"io-error\", \"internal\"]),\n message: z.string(), retryable: z.boolean(), receiptRecorded: z.boolean(),\n});\nexport type AutomationFailure = z.infer<typeof failureSchema>;\nconst attemptSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/), lease: z.literal(true).optional(), event: z.string(), startedAt: z.string(), finishedAt: z.string().optional(),\n durationMs: z.number().nonnegative().optional(),\n pid: z.number().int().positive(), host: z.string(),\n status: z.enum([\"running\", \"completed\", \"failed\", \"unknown\"]),\n verificationStatus: z.string().optional(), reportPath: z.string().optional(), failure: failureSchema.optional(),\n});\nconst executionSchema = z.object({ version: z.literal(1), attempts: z.array(attemptSchema).max(160), discardedAttempts: z.number().int().nonnegative().default(0) });\nfunction parseExecution(raw: unknown) {\n try { return executionSchema.parse(raw); }\n catch (error) { throw new Error(\"Invalid automation execution store; receipt history was retained.\", { cause: error }); }\n}\n\n/** Classify failures without interpreting the advisory hook's exit code as evidence. */\nexport function automationFailure(error: unknown): AutomationFailure {\n const recorded = failureSchema.safeParse((error as { failure?: unknown } | null)?.failure);\n if (recorded.success) return recorded.data;\n const message = (error instanceof Error ? error.message : String(error)).replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \" \").slice(0, 700);\n const codes = new Set<string>();\n let cause: unknown = error;\n for (let i = 0; cause && i < 8; i++) {\n codes.add(String((cause as NodeJS.ErrnoException).code));\n cause = (cause as Error).cause;\n }\n const code: AutomationFailure[\"code\"] = codes.has(\"ENOSPC\") || codes.has(\"EDQUOT\") ? \"storage-full\"\n : /changed during|changed while|changed between/.test(message) ? \"inputs-changed\"\n : /Automation is busy/.test(message) ? \"busy\"\n : /not a git repository|unknown revision|bad revision|different history|unreachable/.test(message) ? \"history-unavailable\"\n : error instanceof z.ZodError || error instanceof SyntaxError || /Hook input|Expected one command|Unknown automation command|--host/.test(message) ? \"invalid-input\"\n : /store|baseline|modified|symbolic link|Symlink|automation state|state belongs/.test(message) ? \"invalid-evidence\"\n : [...codes].some(c => /^E[A-Z]+$/.test(c)) ? \"io-error\" : \"internal\";\n return { code, message, retryable: [\"inputs-changed\", \"storage-full\", \"busy\", \"io-error\"].includes(code), receiptRecorded: false };\n}\n\nexport function failureMessage(error: unknown): string {\n const failure = automationFailure(error);\n return `Mason automation unavailable [${failure.code}]; evidence capture/verification was not established. ${failure.message}` +\n (failure.receiptRecorded ? \"\" : \" No durable failure receipt was recorded.\");\n}\n\nconst notificationsSchema = z.object({ version: z.literal(1), sessions: z.record(z.object({\n signature: z.string(), code: failureSchema.shape.code, message: z.string(), count: z.number().int().positive(), lastAt: z.string(),\n})) });\n\nexport async function failureNotifications(root: string, directory: string) {\n const raw = await readStoreJson(root, directory + \"/notifications.json\");\n return raw === null ? { version: 1 as const, sessions: {} } : notificationsSchema.parse(raw);\n}\n\n/** Suppress repeats only after the failure itself has a durable execution receipt. */\nexport async function hookFailureMessage(dir: string, host: string, sessionId: string, error: unknown): Promise<string | null> {\n const failure = automationFailure(error);\n if (!failure.receiptRecorded) return failureMessage(error);\n try {\n const ws = await workspace(dir);\n return await withLock(ws.root, ws.directory + \"/notifications\", async () => {\n const notices = await failureNotifications(ws.root, ws.directory);\n const key = hash([host, sessionId]), signature = hash([failure.code, failure.message]);\n const previous = notices.sessions[key];\n const execution = await executionStatus(ws.root, ws.directory);\n const recovered = previous && execution.attempts.some(a => a.status === \"completed\" && a.startedAt > previous.lastAt);\n const repeat = previous?.signature === signature && !recovered;\n notices.sessions[key] = { signature, code: failure.code, message: failure.message,\n count: repeat ? previous.count + 1 : 1, lastAt: new Date().toISOString() };\n notices.sessions = Object.fromEntries(Object.entries(notices.sessions).sort(([, a], [, b]) => b.lastAt.localeCompare(a.lastAt)).slice(0, 32));\n await writeStoreJson(ws.root, ws.directory + \"/notifications.json\", notices);\n return repeat ? null : failureMessage(error) + \" Repeated failures in this session are recorded in mason status --json.\";\n });\n } catch { return failureMessage(error); }\n}\n\n/** Each invocation owns a receipt while only brief log updates are serialized. */\nconst leasePath = (directory: string, id: string) => `${directory}/executions/${id}.json`;\n\nasync function refreshRunning(root: string, directory: string, attempts: z.infer<typeof attemptSchema>[]) {\n for (const attempt of attempts) {\n if (attempt.status !== \"running\") continue;\n let alive = false;\n try {\n const owner = await readStoreJson(root, attempt.lease ? leasePath(directory, attempt.id) : directory + \"/lock\") as { pid?: unknown; host?: unknown } | null;\n if (attempt.host === os.hostname() && owner?.pid === attempt.pid && owner.host === attempt.host) {\n try { process.kill(attempt.pid, 0); alive = true; }\n catch (error) { alive = (error as NodeJS.ErrnoException).code === \"EPERM\"; }\n }\n } catch { /* Missing ownership never establishes a running check. */ }\n if (!alive) attempt.status = \"unknown\";\n }\n}\n\nasync function editExecution(root: string, directory: string, edit: (log: z.infer<typeof executionSchema>) => void) {\n return withLock(root, directory + \"/execution-lock\", async () => {\n const file = directory + \"/execution.json\";\n const raw = await readStoreJson(root, file);\n const log = raw === null ? { version: 1 as const, attempts: [], discardedAttempts: 0 } : parseExecution(raw);\n await refreshRunning(root, directory, log.attempts);\n edit(log);\n // Keep every live invocation plus the latest 32 finished attempts.\n const finished = log.attempts.filter(a => a.status !== \"running\");\n const discard = new Set(finished.slice(0, Math.max(0, finished.length - 32)).map(a => a.id));\n log.discardedAttempts += discard.size;\n log.attempts = log.attempts.filter(a => !discard.has(a.id));\n await writeStoreJson(root, file, log);\n });\n}\n\nexport async function recordExecution<T extends { report: { status: string; reportPath: string } }>(\n root: string, directory: string, event: string, run: () => Promise<T>,\n): Promise<T> {\n const started = performance.now();\n const attempt: z.infer<typeof attemptSchema> = {\n id: randomUUID(), event, startedAt: new Date().toISOString(), pid: process.pid, host: os.hostname(), status: \"running\", lease: true,\n };\n const owner = leasePath(directory, attempt.id);\n const finish = async (changes: Partial<z.infer<typeof attemptSchema>>) => editExecution(root, directory, log => {\n const current = log.attempts.find(a => a.id === attempt.id);\n if (!current) throw new Error(\"Automation execution receipt disappeared; completion could not be recorded.\");\n Object.assign(current, changes, { finishedAt: new Date().toISOString(), durationMs: performance.now() - started });\n });\n await writeStoreJson(root, owner, { pid: attempt.pid, host: attempt.host });\n try {\n await editExecution(root, directory, log => {\n if (log.attempts.filter(a => a.status === \"running\").length >= 128) throw new Error(\"Too many active automation executions; existing receipts were retained.\");\n log.attempts.push(attempt);\n });\n try {\n const result = await run();\n await finish({ status: \"completed\", verificationStatus: result.report.status, reportPath: result.report.reportPath });\n return result;\n } catch (error) {\n const failure = automationFailure(error);\n try { await finish({ status: \"failed\", failure: { ...failure, receiptRecorded: true } }); failure.receiptRecorded = true; }\n catch { /* Storage failures may also prevent their own completion receipt. */ }\n throw Object.assign(new Error(failure.message, { cause: error }), { failure });\n }\n } finally { await fs.rm(await storePath(root, owner), { force: true }).catch(() => {}); }\n}\n\nexport async function executionStatus(root: string, directory: string) {\n const raw = await readStoreJson(root, directory + \"/execution.json\");\n if (raw === null) return { status: \"not-observed\" as const, attempts: [] };\n const log = parseExecution(raw);\n await refreshRunning(root, directory, log.attempts);\n const completed = [...log.attempts].reverse().find(a => a.status === \"completed\");\n // A success that began before another call failed cannot establish recovery.\n const outstanding = [...log.attempts].reverse().find(a => [\"failed\", \"unknown\"].includes(a.status) &&\n (!completed || (a.finishedAt ?? a.startedAt) >= completed.startedAt));\n const status = log.attempts.some(a => a.status === \"running\") ? \"running\" : outstanding?.status ?? log.attempts.at(-1)?.status ?? \"not-observed\";\n return { status, attempts: log.attempts, discardedAttempts: log.discardedAttempts };\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport { withRepositoryInspection } from \"../audit/inspection.js\";\nimport { recordExecution, executionStatus, failureNotifications } from \"./execution.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { withRepairSession, reportSchema, findingId, repairFindingSchema, type RepairFinding, type RepairVerification } from \"../audit/repair.js\";\nimport { ALL_CHECKS, type AuditReport } from \"../audit/types.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { checkCache, git, hash, readInputs, workspace, type Inputs } from \"./evidence.js\";\nimport { parseState, withLock, type Event, type Host, type State } from \"./store.js\";\n\nexport interface AutomationEvent {\n event: Event;\n host?: Host;\n sessionId?: string;\n toolId?: string;\n mutating?: boolean;\n stopHookActive?: boolean;\n}\nexport interface AutomationReport {\n version: 1;\n status: \"verified\" | \"issues-remain\" | \"incomplete\" | \"unavailable\";\n root: string;\n branch: string;\n head: string;\n baselinePaths: string[];\n reportPath: string;\n findings: RepairFinding[];\n diagnostics: string[];\n checks: { ran: string[]; reused: string[]; skipped: NonNullable<AuditReport>[\"skippedChecks\"]; shared?: boolean; auditReused?: boolean };\n counts: RepairVerification[\"counts\"];\n capture: \"observed\" | \"unknown\";\n scope: string;\n}\n\nconst SCOPE = \"Documentation audit evidence only. Hook receipts show observed events, not complete interception. Resolved findings no longer fail their checks or have a recorded assessment covering current evidence. Repair and review only within the user's task authorization.\";\nconst priority = { resolved: 0, \"review-required\": 1, unresolved: 2, unverified: 3 };\nconst cleanText = (text: string) => text.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \" \").slice(0, 250);\n\n/** Read tools cannot create repair evidence. Observe their lifecycle without rescanning the checkout. */\nexport async function observeReadOnlyTool(dir: string, event: AutomationEvent) {\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n await withLock(ws.root, ws.directory, async () => {\n const statePath = ws.directory + \"/state.json\";\n const raw = await readStoreJson(ws.root, statePath);\n if (raw === null) return;\n const state = parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) {\n throw new Error(\"Automation state belongs to another branch or worktree; original evidence was retained.\");\n }\n const session = event.host && event.sessionId ? state.sessions[hash([event.host, event.sessionId])] : null;\n if (!session) return;\n const now = new Date().toISOString();\n session.lastUsed = now;\n session.events[event.event] = { at: now, count: (session.events[event.event]?.count ?? 0) + 1 };\n // Do not advance the audit fingerprint, report, or execution verdict: no check ran.\n await writeStoreJson(ws.root, statePath, state);\n });\n return { root: ws.root, directory: ws.directory };\n}\n\nexport function summarize(report: AutomationReport): string {\n const open = report.findings.filter(f => f.status !== \"resolved\");\n return [\n `Mason: ${report.status}; ${report.counts.unresolved} unresolved, ${report.counts[\"review-required\"]} need review, ${report.counts.unverified} unverified.`,\n ...open.slice(0, 4).map(f => `[${f.status}] ${cleanText(f.original.anchor.doc)}: ${cleanText(f.original.message)}`),\n ...(open.length > 4 ? [`${open.length - 4} more findings in the report.`] : []),\n ...report.diagnostics.slice(0, 2).map(cleanText),\n `Evidence: ${report.reportPath}. Resume/check with mason_automation(action: \"check\") or mason-auto check.`,\n \"Keep original evidence. Address findings relevant to the authorized task; report unrelated findings and unresolved advisories without approving them.\",\n ].join(\"\\n\");\n}\n\ntype Workspace = Awaited<ReturnType<typeof workspace>>;\n\nasync function loadState(ws: Workspace): Promise<State> {\n const raw = await readStoreJson(ws.root, ws.directory + \"/state.json\");\n const state = raw === null ? {\n version: 1 as const, root: ws.root, gitDir: ws.gitDir, branch: ws.branch, baselines: [], sessions: {},\n updatedAt: new Date().toISOString(), fingerprint: null, latest: null,\n } : parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) {\n throw new Error(\"Automation state belongs to another branch or worktree; original evidence was retained.\");\n }\n return state;\n}\n\nconst analysisSchema = z.object({\n id: z.string(), fingerprint: z.string(), completedAt: z.number(), baselineDigest: z.string(),\n currentAudit: reportSchema.nullable().optional(),\n report: z.object({\n version: z.literal(1), status: z.enum([\"verified\", \"issues-remain\", \"incomplete\", \"unavailable\"]),\n root: z.string(), branch: z.string(), head: z.string(), baselinePaths: z.array(z.string()), reportPath: z.string(),\n findings: z.array(repairFindingSchema), diagnostics: z.array(z.string()),\n checks: z.object({ ran: z.array(z.string()), reused: z.array(z.string()),\n skipped: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })), auditReused: z.boolean().optional() }),\n counts: z.object({ resolved: z.number(), unresolved: z.number(), \"review-required\": z.number(), unverified: z.number() }),\n capture: z.enum([\"observed\", \"unknown\"]), scope: z.string(),\n }),\n});\nconst sharedSchema = z.object({ analysis: analysisSchema, digest: z.string() });\ntype Analysis = z.infer<typeof analysisSchema>;\nconst baselineDigest = async (ws: Workspace, state: State) => profilePhase(\"automation.baselines\", async () => hash(await Promise.all(\n state.baselines.map(async b => [b.path, await readStoreJson(ws.root, b.path)]),\n)));\n\nasync function matchingAnalysis(ws: Workspace, state: State, inputs: Inputs): Promise<{ analysis: Analysis | null; diagnostic?: string }> {\n const pointer = state.analysis;\n if (!pointer || pointer.fingerprint !== inputs.fingerprint) return { analysis: null };\n if (pointer.path !== ws.directory + \"/checks/analysis-\" + inputs.fingerprint + \".json\") {\n throw new Error(\"Invalid automation analysis cache path; inspect the retained state.\");\n }\n // This is a derived cache, not original repair evidence. Missing or malformed\n // data can be rebuilt, but storage/permission failures and unsafe paths remain\n // errors. Never discard or replace an original baseline to recover a cache.\n const invalid = { analysis: null, diagnostic: \"Discarded an invalid current-audit cache; audit preparation and original verification were repeated.\" };\n let raw: unknown;\n try { raw = await readStoreJson(ws.root, pointer.path); }\n catch (error) {\n const cause = (error as Error).cause;\n if (cause instanceof SyntaxError || cause instanceof Error && cause.message === \"expected a JSON object, received null\") return invalid;\n throw error;\n }\n if (raw === null) return { analysis: null };\n const parsed = sharedSchema.safeParse(raw);\n if (!parsed.success) return invalid;\n const stored = parsed.data;\n const a = stored.analysis;\n if (stored.digest !== hash(a) || a.id !== pointer.id || a.fingerprint !== inputs.fingerprint ||\n a.completedAt !== pointer.completedAt || a.report.root !== ws.root || a.report.branch !== ws.branch ||\n a.report.head !== inputs.head || hash(a.report.baselinePaths) !== hash(state.baselines.map(b => b.path))) {\n return invalid;\n }\n if (a.baselineDigest !== await baselineDigest(ws, state)) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n return { analysis: a };\n}\n\nasync function verifyInputs(ws: Workspace, inputs: Inputs) {\n return profilePhase(\"automation.revalidate\", () => withRepositoryInspection(ws.root, async () => {\n const [after, currentWs] = await Promise.all([readInputs(ws.root), workspace(ws.root)]);\n if (after.fingerprint !== inputs.fingerprint || currentWs.directory !== ws.directory) {\n throw new Error(\"Repository inputs or branch changed during automation; no current verification was recorded. Retry on a stable checkout.\");\n }\n }));\n}\n\n/** Expensive reads and checks never hold the shared state lock. */\nasync function computeAnalysis(ws: Workspace, state: State, inputs: Inputs, event: AutomationEvent, previousAudit?: AuditReport | null, cacheDiagnostic?: string) {\n const baselines = [...state.baselines];\n const now = new Date().toISOString();\n const empty: AutomationReport = { version: 1, status: \"unavailable\", root: ws.root, branch: ws.branch, head: inputs.head,\n baselinePaths: [], reportPath: \"\", findings: [],\n diagnostics: [\"No README.md or agent instruction files were discovered. Documentation capture is unavailable; other Mason tools remain usable.\"],\n checks: { ran: [], reused: [], skipped: [] }, counts: { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 },\n capture: \"unknown\", scope: SCOPE };\n if (!baselines.length && Object.values(inputs.docs).every(value => value === null)) {\n await verifyInputs(ws, inputs);\n return { baselines, report: empty, cache: null };\n }\n if (ws.branch === \"detached\" && state.latest) {\n const previous = await readStoreJson(ws.root, state.latest) as AutomationReport | null;\n if (!previous?.head || !/^[a-f0-9]{40,64}$/.test(previous.head)) throw new Error(\"The previous detached checkout evidence is unavailable.\");\n try { await git(ws.root, \"merge-base\", \"--is-ancestor\", previous.head, inputs.head); }\n catch { throw new Error(\"Detached checkout moved to a different history; original repair evidence was retained. Inspect that baseline explicitly.\"); }\n }\n let cached: unknown = null;\n const diagnostics: string[] = cacheDiagnostic ? [cacheDiagnostic] : [];\n try { cached = await readStoreJson(ws.root, ws.directory + \"/cache.json\"); }\n catch { diagnostics.push(\"Unreadable automation cache; checks are being recomputed.\"); }\n const cache = checkCache(cached, inputs);\n if (cache.diagnostic) diagnostics.push(cache.diagnostic);\n // Only complete, validated raw checks can bypass current-audit preparation.\n // Retained history and review outcomes are still evaluated on every invocation.\n const cachedAudit = previousAudit?.gitAvailable && previousAudit.headHash === inputs.head &&\n previousAudit.root === ws.root && !previousAudit.skippedChecks.length &&\n ALL_CHECKS.every(name => previousAudit.checksRun?.includes(name) && cache.has(name)) ? previousAudit : undefined;\n if (cachedAudit) for (const name of ALL_CHECKS) cache.reused.add(name);\n let currentAudit: AuditReport | null = null;\n const verifications = await withRepairSession(ws.root, cache.options, async repairs => {\n const saveBaseline = async () => {\n if (baselines.length >= 128) throw new Error(\"128 retained baselines need review; automatic capture stopped without discarding original evidence.\");\n const prepared = await repairs.prepare();\n baselines.push({ path: prepared.baselinePath, at: now, event: event.event, fingerprint: inputs.fingerprint });\n };\n if (!baselines.length) await saveBaseline();\n const verifications: RepairVerification[] = [];\n for (const baseline of baselines) verifications.push(await repairs.verify(baseline.path));\n const known = new Set(verifications.flatMap(v => v.findings.map(f => f.id)));\n // A clean initial baseline cannot retain findings introduced by a later rename.\n // Preserve those findings now, before another tool can edit or commit the docs.\n if (verifications.some(v => v.newFindings.some(f => !known.has(findingId(f))))) {\n await saveBaseline();\n verifications.push(await repairs.verify(baselines.at(-1)!.path));\n }\n currentAudit = await repairs.currentAudit();\n return verifications;\n }, () => verifyInputs(ws, inputs), cachedAudit);\n const merged = new Map<string, RepairFinding>();\n for (const verification of verifications) {\n for (const finding of verification.findings) {\n const previous = merged.get(finding.id);\n if (!previous || priority[finding.status] > priority[previous.status]) merged.set(finding.id, finding);\n }\n diagnostics.push(...verification.diagnostics);\n }\n\n const counts = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const finding of merged.values()) counts[finding.status]++;\n const report: AutomationReport = {\n version: 1, status: diagnostics.length || verifications.some(v => v.status === \"incomplete\") ? \"incomplete\" : counts.unresolved ? \"issues-remain\" : \"verified\",\n root: ws.root, branch: ws.branch, head: inputs.head, baselinePaths: baselines.map(b => b.path), reportPath: \"\",\n findings: [...merged.values()], diagnostics: [...new Set(diagnostics)],\n checks: { ran: [...cache.ran], reused: [...cache.reused].filter(name => !cache.ran.has(name)), skipped: verifications.at(-1)!.currentAudit?.skippedChecks ?? [], ...(cachedAudit ? { auditReused: true } : {}) },\n counts, capture: \"unknown\", scope: SCOPE,\n };\n return { baselines, report, currentAudit, cache: cache.ran.size || cached === null || cache.diagnostic ? cache.serialize() : null };\n}\n\n/** Per-input coordination shares expensive work; unrelated inputs can be checked concurrently. */\nasync function analyze(ws: Workspace, inputs: Inputs, event: AutomationEvent, startedAt: number) {\n return withLock(ws.root, ws.directory + \"/analysis/\" + inputs.fingerprint, async () => {\n const before = await loadState(ws);\n const { analysis: previous, diagnostic } = await matchingAnalysis(ws, before, inputs);\n // Overlap may share the whole verification. Sequential calls reuse only its\n // current audit: original history and review scopes need fresh inspection.\n if (previous && previous.completedAt >= startedAt) return { analysis: previous, shared: true };\n const originalDigest = await baselineDigest(ws, before);\n const computed = await computeAnalysis(ws, before, inputs, event, previous?.currentAudit as AuditReport | undefined, diagnostic);\n if (originalDigest !== await baselineDigest(ws, before)) throw new Error(\"Repair baseline was modified during automation; original evidence must be inspected.\");\n const id = randomUUID();\n const analysis = analysisSchema.parse({ id, fingerprint: inputs.fingerprint, completedAt: Date.now(),\n baselineDigest: await baselineDigest(ws, { ...before, baselines: computed.baselines }), report: computed.report, currentAudit: computed.currentAudit });\n const analysisPath = ws.directory + \"/checks/analysis-\" + inputs.fingerprint + \".json\";\n await withLock(ws.root, ws.directory, async () => {\n const state = await loadState(ws);\n // A concurrent check may have retained different original evidence. Never overwrite it.\n if (hash(state.baselines) !== hash(before.baselines) || state.analysis?.id !== before.analysis?.id) {\n throw new Error(\"Automation evidence changed during analysis; retry against the retained baselines.\");\n }\n await writeStoreJson(ws.root, analysisPath, { analysis, digest: hash(analysis) });\n if (computed.cache) await writeStoreJson(ws.root, ws.directory + \"/cache.json\", computed.cache);\n state.baselines = computed.baselines;\n state.analysis = { id, fingerprint: inputs.fingerprint, completedAt: analysis.completedAt, path: analysisPath };\n await writeStoreJson(ws.root, ws.directory + \"/state.json\", state);\n });\n return { analysis, shared: false };\n }, Math.max(0, 25000 - (Date.now() - startedAt)));\n}\n\n/** Durable lifecycle: read concurrently, then merge each call into the latest state. */\nexport async function automate(dir: string, event: AutomationEvent) {\n const startedAt = Date.now();\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n return recordExecution(ws.root, ws.directory, event.event, () => withRepositoryInspection(ws.root, async () => {\n const inputs = await readInputs(ws.root);\n const result = await profilePhase(\"automation.analysis\", () => analyze(ws, inputs, event, startedAt));\n if (result.shared) {\n await verifyInputs(ws, inputs);\n if (result.analysis.baselineDigest !== await baselineDigest(ws, await loadState(ws))) {\n throw new Error(\"Repair baseline was modified during shared automation; original evidence must be inspected.\");\n }\n }\n return profilePhase(\"automation.publish\", () => withLock(ws.root, ws.directory, async () => {\n const state = await loadState(ws);\n if (state.analysis?.id !== result.analysis.id) throw new Error(\"Automation evidence changed during publication; retry against the current inputs.\");\n const report = structuredClone(result.analysis.report) as AutomationReport;\n if (result.shared) report.checks = { ...report.checks, ran: [], reused: [...new Set([...report.checks.ran, ...report.checks.reused])], shared: true };\n report.reportPath = ws.directory + \"/checks/\" + randomUUID() + \".json\";\n const now = new Date().toISOString();\n const key = event.host && event.sessionId ? hash([event.host, event.sessionId]) : null;\n const newSession = key !== null && !state.sessions[key];\n if (key && !state.sessions[key]) {\n const keys = Object.keys(state.sessions).sort((a, b) => state.sessions[a].lastUsed.localeCompare(state.sessions[b].lastUsed));\n // Pending pre-edit captures cannot be evicted by another session's arrival.\n const removable = keys.filter(k => !Object.keys(state.sessions[k].pending).length);\n for (const expired of removable.slice(0, Math.max(0, keys.length - 31))) delete state.sessions[expired];\n if (Object.keys(state.sessions).length >= 128) throw new Error(\"Too many sessions with unfinished tool calls; original evidence was retained.\");\n state.sessions[key] = { host: event.host!, seen: null, continued: false,\n initialIssues: report.findings.filter(f => f.status === \"unresolved\").map(f => f.id), initialDocs: inputs.docs,\n lastUsed: now, mutationObserved: false, pending: {}, coverageGaps: [], events: {} };\n }\n const session = key ? state.sessions[key] : null;\n if (session) {\n session.lastUsed = now;\n session.events[event.event] = { at: now, count: (session.events[event.event]?.count ?? 0) + 1 };\n if (event.event === \"before_tool\" && event.mutating && event.toolId) {\n if (Object.keys(session.pending).length >= 128) throw new Error(\"Too many unfinished tool calls to track pre-edit evidence.\");\n session.pending[event.toolId] = inputs.fingerprint;\n }\n if (event.event === \"after_tool\" && event.mutating) {\n session.mutationObserved = true;\n if (!event.toolId || !session.pending[event.toolId]) {\n const gap = \"A tool completed without an observed matching pre-tool capture; pre-edit coverage is unknown.\";\n if (!session.coverageGaps.includes(gap)) session.coverageGaps.push(gap);\n }\n if (event.toolId) delete session.pending[event.toolId];\n }\n report.diagnostics.push(...session.coverageGaps);\n if (session.coverageGaps.length && report.status !== \"unavailable\") report.status = \"incomplete\";\n report.capture = report.status !== \"unavailable\" && !session.coverageGaps.length &&\n (session.events.session_start || session.events.before_tool) ? \"observed\" : \"unknown\";\n }\n const signature = hash([report.status, report.findings, report.diagnostics, report.checks.skipped]);\n const relevant = report.findings.some(f => f.status === \"unresolved\" && session &&\n (!session.initialIssues.includes(f.id) || session.initialDocs[f.original.anchor.doc] !== inputs.docs[f.original.anchor.doc]));\n const continueOnce = event.event === \"task_end\" && !!session?.mutationObserved && relevant && !session.continued && !event.stopHookActive;\n const notify = !session || newSession || signature !== session.seen || continueOnce;\n if (session) { session.seen = signature; if (continueOnce) session.continued = true; }\n const persistReport = !state.latest || state.fingerprint !== inputs.fingerprint || notify || event.event === \"task_end\";\n if (!persistReport) report.reportPath = state.latest!;\n state.updatedAt = now; state.fingerprint = inputs.fingerprint; state.latest = report.reportPath;\n if (persistReport) await writeStoreJson(ws.root, report.reportPath, report);\n await writeStoreJson(ws.root, ws.directory + \"/state.json\", state);\n return { report, message: notify ? summarize(report) : null, continueOnce };\n }));\n }));\n}\n\n/** Read-only inspection: configured hooks and observed runtime events are different facts. */\nexport async function automationStatus(dir: string) {\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n const execution = await executionStatus(ws.root, ws.directory);\n const notifications = await failureNotifications(ws.root, ws.directory);\n const raw = await readStoreJson(ws.root, ws.directory + \"/state.json\");\n if (raw === null) return { version: 1, status: execution.status === \"not-observed\" ? \"not-observed\" : \"unavailable\", root: ws.root, branch: ws.branch, baselinePaths: [], hosts: {}, execution, notifications };\n const state = parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) throw new Error(\"Automation state belongs to another workspace.\");\n const inputs = await readInputs(ws.root);\n const latest = state.latest ? await readStoreJson(ws.root, state.latest) as AutomationReport | null : null;\n const hosts: Record<string, { sessions: number; observedEvents: string[] }> = {};\n for (const session of Object.values(state.sessions)) {\n const host = hosts[session.host] ??= { sessions: 0, observedEvents: [] };\n host.sessions++;\n host.observedEvents = [...new Set([...host.observedEvents, ...Object.keys(session.events)])];\n }\n const unfinished = [\"failed\", \"unknown\", \"running\"].includes(execution.status);\n return { version: 1, status: unfinished ? \"unavailable\" : inputs.fingerprint === state.fingerprint ? \"current\" : \"changed\", root: ws.root,\n branch: ws.branch, baselinePaths: state.baselines.map(b => b.path), reportPath: state.latest,\n verificationStatus: unfinished ? \"unavailable\" : latest?.status ?? \"unavailable\", hosts, execution, notifications,\n note: \"Observed events do not prove all tool paths are intercepted. Run check to verify the retained evidence.\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { git } from \"./evidence.js\";\nimport type { Host } from \"./store.js\";\n\nasync function repositoryRoot(dir: string): Promise<string | null> {\n if (!path.isAbsolute(dir)) throw new Error(\"Hook input working directory must be absolute.\");\n try { return await fs.realpath((await git(dir, \"rev-parse\", \"--show-toplevel\")).trim()); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\" ||\n /not a git repository/.test(String((error as { stderr?: string }).stderr))) return null;\n throw error;\n }\n}\n\n/** The host payload follows directory/worktree changes; the launch directory may not. */\nexport async function resolveHookRoot(host: Host, cwd: string, options: {\n launchCwd?: string; projectDir?: string;\n} = {}): Promise<string> {\n const current = await repositoryRoot(cwd);\n if (current) return current;\n const projectDir = options.projectDir ?? (host === \"claude\" ? process.env.CLAUDE_PROJECT_DIR : undefined);\n const projectRoot = projectDir ? await repositoryRoot(projectDir) : null;\n if (projectDir && !projectRoot) throw new Error(\"Hook input is outside Git and the host project is no longer a Git repository. Restore its history before running mason check.\");\n const launchRoot = await repositoryRoot(options.launchCwd ?? process.cwd());\n const roots = [...new Set([launchRoot, projectRoot].filter((root): root is string => root !== null))];\n if (!roots.length) throw new Error(\"Hook input is outside a Git repository and no project root is available. Return to the project and run mason check.\");\n if (roots.length > 1) throw new Error(\"Hook input is outside a Git repository and project roots disagree. Return to the intended checkout and run mason check; verification was not established.\");\n // CLAUDE_PROJECT_DIR stays at the original checkout after EnterWorktree.\n // Without a current repository, it cannot distinguish those checkouts.\n const worktrees = (await git(roots[0], \"worktree\", \"list\", \"--porcelain\", \"-z\"))\n .split(\"\\0\").filter(field => field.startsWith(\"worktree \"));\n if (worktrees.length !== 1) throw new Error(\"Hook input is outside a Git repository with multiple worktrees. Return to the intended worktree and run mason check; the active checkout is unknown.\");\n return roots[0];\n}\n","import { failureMessage, hookFailureMessage } from \"./execution.js\";\nimport { z } from \"zod\";\nimport { automate, observeReadOnlyTool, type AutomationEvent } from \"./runtime.js\";\nimport { hostSchema, type Host } from \"./store.js\";\nimport { resolveHookRoot } from \"./hook-root.js\";\n\nconst inputSchema = z.object({\n cwd: z.string().min(1), session_id: z.string().min(1).max(500),\n hook_event_name: z.enum([\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"Stop\"]),\n tool_name: z.string().optional(), tool_use_id: z.string().max(500).optional(),\n tool_input: z.unknown().optional(), stop_hook_active: z.boolean().optional(), permission_mode: z.string().optional(),\n});\nconst lifecycle: Record<z.infer<typeof inputSchema>[\"hook_event_name\"], AutomationEvent[\"event\"]> = {\n SessionStart: \"session_start\", UserPromptSubmit: \"turn_start\", PreToolUse: \"before_tool\", PostToolUse: \"after_tool\", Stop: \"task_end\",\n};\n\n/** Shell and unknown/MCP tools are conservatively observed: edits need not use a file editor. */\nexport function normalizeHook(host: Host, raw: unknown): { cwd: string; name: string; readOnly: boolean; event: AutomationEvent } {\n hostSchema.parse(host);\n const input = inputSchema.parse(raw);\n const readOnly = (host === \"claude\" ? /^(Read|Glob|Grep|WebSearch|WebFetch)$/ : /^(read_file|list_dir|grep_files|Read|Glob|Grep)$/).test(input.tool_name ?? \"\");\n return { cwd: input.cwd, name: input.hook_event_name, readOnly, event: {\n event: lifecycle[input.hook_event_name], host, sessionId: input.session_id, toolId: input.tool_use_id,\n mutating: !!input.tool_name && !readOnly,\n stopHookActive: input.stop_hook_active || input.permission_mode === \"plan\",\n } };\n}\n\nexport async function runAutomationHook(host: Host, stdin: string, options: { managed?: boolean } = {}): Promise<Record<string, unknown> | null> {\n let name = \"\";\n let hook: ReturnType<typeof normalizeHook> | undefined;\n try {\n if (Buffer.byteLength(stdin) > 1024 * 1024) throw new Error(\"Hook input exceeds 1 MiB.\");\n let raw: unknown;\n try { raw = JSON.parse(stdin); }\n catch { throw new Error(\"Hook input is not valid JSON.\"); }\n const input = normalizeHook(host, raw);\n hook = input;\n name = input.name;\n if (options.managed) {\n input.cwd = await resolveHookRoot(host, input.cwd);\n const { prepareLaunch } = await import(\"../setup/launcher.js\");\n if (!await prepareLaunch(host, { dir: input.cwd, allowInactive: true })) return null;\n }\n if ([\"before_tool\", \"after_tool\"].includes(input.event.event) && input.readOnly) {\n const observed = await observeReadOnlyTool(input.cwd, input.event);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(observed.root, input.event.event, { sessionId: input.event.sessionId, directory: observed.directory });\n return warning ? { systemMessage: warning } : null;\n }\n const result = await automate(input.cwd, input.event);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(result.report.root, input.event.event, {\n sessionId: input.event.sessionId, verificationStatus: result.report.status, reportPath: result.report.reportPath,\n });\n if (warning) result.message = [result.message, warning].filter(Boolean).join(\"\\n\");\n if (!result.message) return null;\n if (name === \"Stop\") {\n // A single continuation for actionable task findings; advisories never create a loop.\n return result.continueOnce ? { decision: \"block\", reason: result.message } : { systemMessage: result.message };\n }\n return { hookSpecificOutput: { hookEventName: name, additionalContext: result.message } };\n } catch (error) {\n const message = hook ? await hookFailureMessage(hook.cwd, host, hook.event.sessionId!, error) : failureMessage(error);\n if (!message) return null;\n // Hook failure is visible but does not turn documentation advice into an editing permission gate.\n return { systemMessage: message, ...([\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\"].includes(name)\n ? { hookSpecificOutput: { hookEventName: name, additionalContext: message } } : {}) };\n }\n}\n\nexport const HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"Stop\"] as const;\n/** Only guard Mason's generated launch, never interpret a custom command prefix. */\nexport function managedHookCommand(host: Host, platform = process.platform) {\n const command = `mason --setup-host ${host} auto hook --host ${host}`;\n return platform === \"win32\"\n ? `cmd.exe /d /s /c \"where mason >nul 2>nul & if errorlevel 1 (exit /b 0) else (${command})\"`\n : `if command -v mason >/dev/null 2>&1; then ${command}; fi`;\n}\nexport function knownManagedHookCommands(host: Host) {\n return [managedHookCommand(host, \"linux\"), managedHookCommand(host, \"win32\"), `mason --setup-host ${host} auto hook --host ${host}`];\n}\n/** Migration recognizes both platforms; runtime compatibility is platform-specific. */\nexport function compatibleManagedHookCommands(host: Host, platform = process.platform) {\n return [managedHookCommand(host, platform), `mason --setup-host ${host} auto hook --host ${host}`];\n}\nexport function hookConfig(host: Host, command = \"npx --no-install --package mason-context mason-auto\") {\n const handler = { type: \"command\", command: command === `mason --setup-host ${host} auto`\n ? managedHookCommand(host) : command + \" hook --host \" + host, timeout: 30 };\n return { hooks: Object.fromEntries(HOOK_EVENTS.map(name => [name,\n [{ ...([\"PreToolUse\", \"PostToolUse\"].includes(name) ? { matcher: \".*\" } : {}), hooks: [{ ...handler }] }],\n ])) };\n}\n","import { z } from \"zod\";\nimport { parse } from \"smol-toml\";\nimport { hash } from \"../automation/evidence.js\";\nimport { readText, type FileEdit } from \"./files.js\";\n\nexport const OWNERSHIP_PATH = \".mason/local/integration.json\";\nexport const BLOCKS = [\n [\"<!-- mason:start -->\", \"<!-- mason:end -->\"],\n [\"<!-- mason:agents:start -->\", \"<!-- mason:agents:end -->\"],\n [\"# mason:mcp:start\", \"# mason:mcp:end\"],\n] as const;\nconst fileSchema = z.object({ created: z.boolean(), initialHash: z.string(),\n blocks: z.record(z.string()), mcpHash: z.string().optional(), hookCommands: z.array(z.string()).optional(), hooks: z.record(z.array(z.string())).optional() });\nexport const ownershipSchema = z.object({ version: z.literal(1), files: z.record(fileSchema) });\nexport type Ownership = z.infer<typeof ownershipSchema>;\n\nexport function blockSpan(text: string, start: string, end: string) {\n const starts = text.split(start).length - 1, ends = text.split(end).length - 1;\n if (!starts && !ends) return null;\n const from = text.indexOf(start), to = text.indexOf(end) + end.length;\n if (starts !== 1 || ends !== 1 || to <= from) throw new Error(\"Ambiguous Mason markers; inspect the marked block manually.\");\n return { from, to, text: text.slice(from, to) };\n}\n\n/** Persist ownership before shared edits so interrupted setup remains removable. */\nexport async function ownershipEdit(root: string, edits: FileEdit[], hookCommands: Record<string, string> = {}): Promise<FileEdit> {\n const before = await readText(root, OWNERSHIP_PATH);\n const record: Ownership = before === null ? { version: 1, files: {} } : ownershipSchema.parse(JSON.parse(before));\n for (const edit of edits) {\n const previous = record.files[edit.path];\n const entry = { created: edit.before === null || (previous?.created ?? false),\n initialHash: edit.before === null || previous?.initialHash === hash(edit.before) ? hash(edit.after) : previous?.initialHash ?? hash(edit.after),\n blocks: Object.fromEntries(BLOCKS.flatMap(([start, end]) => {\n const block = blockSpan(edit.after, start, end);\n return block ? [[start, hash(block.text)]] : [];\n })),\n };\n const mcp = edit.path === \".codex/config.toml\" ? (parse(edit.after).mcp_servers as Record<string, unknown>)?.mason\n : edit.path === \".mcp.json\" ? JSON.parse(edit.after).mcpServers?.mason : undefined;\n const hooks = edit.path === \".codex/hooks.json\" || edit.path === \".claude/settings.json\"\n ? JSON.parse(edit.after).hooks as Record<string, Array<{ hooks: unknown[] }>> | undefined : undefined;\n record.files[edit.path] = { ...entry, ...(mcp === undefined ? {} : { mcpHash: hash(mcp) }),\n ...(hookCommands[edit.path] ? { hookCommands: [...new Set([...(previous?.hookCommands ?? []), hookCommands[edit.path]])] } : {}),\n ...(hooks === undefined ? {} : { hooks: Object.fromEntries(Object.entries(hooks).map(([event, groups]) =>\n [event, groups.flatMap(group => group.hooks.map(hash))])) }),\n };\n }\n return { path: OWNERSHIP_PATH, before, after: JSON.stringify(record, null, 2) + \"\\n\" };\n}\n\n/** Forget earlier commands only after their replacement and installation record were saved. */\nexport async function completedHookOwnership(root: string, file: string, command: string): Promise<FileEdit> {\n const before = await readText(root, OWNERSHIP_PATH);\n const record = ownershipSchema.parse(JSON.parse(before ?? \"null\"));\n record.files[file].hookCommands = [command];\n return { path: OWNERSHIP_PATH, before, after: JSON.stringify(record, null, 2) + \"\\n\" };\n}\n","import { z } from \"zod\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { workspace } from \"./evidence.js\";\nimport { HOOK_EVENTS, hookConfig, knownManagedHookCommands } from \"./adapters.js\";\nimport { withLock, type Host } from \"./store.js\";\nimport { readText } from \"../setup/files.js\";\nimport { OWNERSHIP_PATH, ownershipSchema } from \"../setup/ownership.js\";\n\nconst groupSchema = z.object({ hooks: z.array(z.object({ type: z.string(), command: z.string().optional() }).passthrough()) }).passthrough();\nexport const automationConfigSchema = z.object({ hooks: z.record(z.array(groupSchema)).optional() }).passthrough();\nexport const recordSchema = z.object({ version: z.literal(1), hosts: z.record(z.object({ command: z.string() })) });\nexport const AUTOMATION_PATH = \".mason/local/automation.json\";\nasync function installationRecord(root: string) {\n return recordSchema.parse(await readStoreJson(root, AUTOMATION_PATH) ?? { version: 1, hosts: {} });\n}\nexport const configPath = (host: Host) => host === \"claude\" ? \".claude/settings.json\" : \".codex/hooks.json\";\n\n/** Explicit install preserves other settings and hooks, replacing only Mason's recorded handlers. */\nexport async function installAutomation(dir: string, host: Host, command?: string) {\n const ws = await workspace(dir);\n return withLock(ws.root, \".mason/reports/setup-lock\", () => installLocked(ws.root, host, command));\n}\n\nexport async function planAutomationInstall(root: string, host: Host, command?: string) {\n const file = configPath(host);\n const before = await readText(root, file);\n const existing = automationConfigSchema.parse(JSON.parse(before ?? \"{}\"));\n const record = await installationRecord(root);\n const desired = hookConfig(host, command);\n const newCommand = desired.hooks.SessionStart[0].hooks[0].command;\n const previous = record.hosts[host]?.command;\n const ownershipText = await readText(root, OWNERSHIP_PATH);\n const pending = ownershipText === null ? [] : ownershipSchema.parse(JSON.parse(ownershipText)).files[file]?.hookCommands ?? [];\n // A clone has shared hooks but no local ownership receipt.\n const owned = new Set([previous, ...pending, newCommand, ...knownManagedHookCommands(host)]);\n const hooks = existing.hooks ?? {};\n for (const event of HOOK_EVENTS) {\n hooks[event] = (hooks[event] ?? []).map(group => ({ ...group,\n hooks: group.hooks.filter(handler => !(handler.type === \"command\" && typeof handler.command === \"string\" &&\n owned.has(handler.command))),\n })).filter(group => group.hooks.length);\n hooks[event].push(...desired.hooks[event]);\n }\n record.hosts[host] = { command: newCommand };\n return { file, before, config: { ...existing, hooks }, record, newCommand };\n}\n\nasync function installLocked(root: string, host: Host, command?: string) {\n const { file, before, config, record, newCommand } = await planAutomationInstall(root, host, command);\n const { ancillaryEdits } = await import(\"../setup/config.js\");\n const { applyEdit } = await import(\"../setup/files.js\");\n const { ownershipEdit, completedHookOwnership } = await import(\"../setup/ownership.js\");\n const edit = { path: file, before, after: JSON.stringify(config, null, 2) + \"\\n\" };\n const ancillary = await ancillaryEdits(root);\n await applyEdit(root, await ownershipEdit(root, [edit], { [file]: newCommand }));\n for (const edit of ancillary) await applyEdit(root, edit);\n await applyEdit(root, edit);\n // Keep the previous command until its replacement is installed. Ownership\n // records the pending command so teardown/reinstallation can resume either side.\n await writeStoreJson(root, AUTOMATION_PATH, record);\n await applyEdit(root, await completedHookOwnership(root, file, newCommand));\n return { version: 1, host, configPath: file, status: \"configured\", command: newCommand,\n events: HOOK_EVENTS,\n next: host === \"codex\"\n ? \"Review/trust these hooks using Codex /hooks and start a new session. mason-auto status reports observed events separately from configuration.\"\n : \"Start a new Claude Code session. mason-auto status reports observed events separately from configuration.\",\n note: \"Install mason-context in the project before using the default command. Ignore .mason/reports/ to keep local evidence out of commits. Hooks preserve evidence and suggest scoped repairs; they do not approve edits or decisions.\" };\n}\n\nexport async function installedAutomation(dir: string) {\n const ws = await workspace(dir);\n const record = await installationRecord(ws.root);\n const result: Record<string, unknown> = {};\n for (const host of [\"claude\", \"codex\"] as const) {\n const expected = record.hosts[host];\n if (!expected) continue;\n const current = automationConfigSchema.parse(await readStoreJson(ws.root, configPath(host)) ?? {});\n const configuredEvents = HOOK_EVENTS.filter(event => current.hooks?.[event]?.some(group =>\n group.hooks.some(handler => handler.type === \"command\" && handler.command === expected.command)));\n result[host] = { configPath: configPath(host), configuredEvents,\n status: current.disableAllHooks === true ? \"disabled\" : configuredEvents.length === HOOK_EVENTS.length ? \"configured\" : \"incomplete\",\n runtime: \"Host version, trust, policy, and tool coverage still determine execution; inspect observed events.\" };\n }\n return result;\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { parse, stringify } from \"smol-toml\";\nimport { z } from \"zod\";\nimport { CLAUDE_MD_SECTION } from \"../mcp/init.js\";\nimport { DOC_CANDIDATES } from \"../audit/docs.js\";\nimport { hookConfig, compatibleManagedHookCommands } from \"../automation/adapters.js\";\nimport { configPath, automationConfigSchema, AUTOMATION_PATH } from \"../automation/install.js\";\nimport type { Host } from \"../automation/store.js\";\nimport { readText, managedBlock, type FileEdit } from \"./files.js\";\nimport { hookCommand, mcpCommand } from \"./launcher.js\";\n\nconst object = z.record(z.unknown());\nexport const mcpPath = (host: Host) => host === \"codex\" ? \".codex/config.toml\" : \".mcp.json\";\nconst TOML_START = \"# mason:mcp:start\", TOML_END = \"# mason:mcp:end\";\nconst POINTER_START = \"<!-- mason:agents:start -->\", POINTER_END = \"<!-- mason:agents:end -->\";\nexport async function instructionEdits(root: string, host?: Host) {\n const found = await Promise.all(DOC_CANDIDATES.map(async file => ({ path: file, text: await readText(root, file) })));\n const existing = found.find(f => f.text !== null);\n const primary = host === \"codex\" && found[0].text === null ? { path: \"AGENTS.md\", text: null }\n : existing ?? { path: \"AGENTS.md\", text: null };\n const originalGuidance = primary.text === null && existing ? \"Follow the existing project conventions in \" + existing.path + \".\\n\" : \"\";\n const edits: FileEdit[] = [{ path: primary.path, before: primary.text,\n after: managedBlock(primary.text ?? originalGuidance, \"<!-- mason:start -->\", \"<!-- mason:end -->\", CLAUDE_MD_SECTION.split(\"\\n\").slice(1, -1).join(\"\\n\")) }];\n if (primary.path === \"AGENTS.md\") {\n const secondary = found.filter(f => f.path !== \"AGENTS.md\" && f.text !== null);\n if (host === \"claude\" && !secondary.length) secondary.push({ path: \"CLAUDE.md\", text: null });\n for (const file of secondary) {\n const text = file.text ?? \"\";\n const legacy = text.includes(\"<!-- mason:start -->\") || text.includes(\"<!-- mason:end -->\");\n const imported = \"@\" + (file.path.startsWith(\".claude/\") ? \"../AGENTS.md\" : \"AGENTS.md\");\n if (text.trim() === imported) continue;\n // Claude expands native imports at session start; a prose mention does not load the guidance.\n const pointer = \"Mason project knowledge and shared project instructions:\\n\" + imported;\n edits.push({ path: file.path, before: file.text,\n after: managedBlock(text, legacy ? \"<!-- mason:start -->\" : POINTER_START, legacy ? \"<!-- mason:end -->\" : POINTER_END, pointer) });\n }\n }\n return edits;\n}\n\n/** Retain host options and environment; replace only transport/launch details. */\nfunction managedMcp(previous: unknown, host: Host) {\n const options = previous === undefined ? {} : object.parse(previous);\n for (const key of [\"command\", \"args\", \"url\", \"type\", \"headers\", \"http_headers\", \"env_http_headers\", \"bearer_token_env_var\"]) delete options[key];\n return { ...options, ...(host === \"claude\" ? { type: \"stdio\" } : {}), ...mcpCommand(host) };\n}\n\nexport async function mcpEdit(root: string, host: Host): Promise<FileEdit> {\n const file = mcpPath(host), before = await readText(root, file);\n if (host === \"claude\") {\n const config = before === null ? {} : object.parse(JSON.parse(before));\n const servers = object.parse(config.mcpServers ?? {});\n // Mason owns only its named server; other servers and settings retain their values.\n return { path: file, before, after: JSON.stringify({ ...config, mcpServers: { ...servers, mason: managedMcp(servers.mason, host) } }, null, 2) + \"\\n\" };\n }\n const config = parse(before ?? \"\");\n const managed = (before ?? \"\").includes(TOML_START);\n const servers = config.mcp_servers as Record<string, unknown> | undefined;\n const desired = managedMcp(servers?.mason, host);\n let base = before ?? \"\";\n if (servers?.mason && !managed) {\n // Migrate ordinary explicit tables without reserializing the rest of TOML.\n // Validate the whole semantic result afterwards, including multiline strings.\n const headers = [...base.matchAll(/^\\s*\\[\\[?.+?\\]\\]?[^\\S\\r\\n]*(?:#.*)?$/gm)];\n const spans = headers.flatMap((header, index) => /^\\s*\\[mcp_servers\\.mason(?:\\.[A-Za-z0-9_-]+)*\\]/.test(header[0])\n ? [{ start: header.index!, end: headers[index + 1]?.index ?? base.length }] : []);\n if (!spans.length) throw new Error(\"Cannot safely migrate the existing Mason MCP TOML entry. Use an explicit [mcp_servers.mason] table and rerun setup; the file was retained.\");\n for (const span of spans.reverse()) base = base.slice(0, span.start) + base.slice(span.end);\n }\n const after = managedBlock(base, TOML_START, TOML_END, stringify({ mcp_servers: { mason: desired } }).trimEnd());\n const parsed = parse(after);\n const expected = { ...config, mcp_servers: { ...(servers ?? {}), mason: desired } };\n if (!isDeepStrictEqual(parsed, expected)) throw new Error(\"Could not safely configure the Mason MCP entry without changing other settings.\");\n return { path: file, before, after };\n}\n\nexport async function hookEdits(root: string, host: Host): Promise<FileEdit[]> {\n const file = configPath(host), before = await readText(root, file);\n const { planAutomationInstall } = await import(\"../automation/install.js\");\n const plan = await planAutomationInstall(root, host, hookCommand(host));\n return [{ path: file, before, after: JSON.stringify(plan.config, null, 2) + \"\\n\" },\n { path: AUTOMATION_PATH, before: await readText(root, AUTOMATION_PATH), after: JSON.stringify(plan.record, null, 2) + \"\\n\" }];\n}\n\nexport async function ancillaryEdits(root: string) {\n const ignore = await readText(root, \".gitignore\");\n const rules = [\"!/.mason/\", \"/.mason/*\",\n \"!/.mason/decisions/\", \"!/.mason/decisions/**\", \"!/.mason/reviews/\", \"!/.mason/reviews/**\", \"!/.mason/config.json\", \"!/.mason/snapshot.json\",\n \"/.mason/local/\", \"/.mason/reports/\"].join(\"\\n\");\n return [{ path: \".gitignore\", before: ignore, after: managedBlock(ignore ?? \"\", \"# mason:ignore:start\", \"# mason:ignore:end\", rules) }];\n}\n\nexport async function inspectHostConfig(root: string, host: Host, plannedMcp?: string) {\n const text = plannedMcp ?? await readText(root, mcpPath(host));\n const config = host === \"codex\" ? parse(text ?? \"\") : object.parse(JSON.parse(text ?? \"{}\"));\n const servers = (host === \"codex\" ? config.mcp_servers : config.mcpServers) as Record<string, unknown> | undefined;\n const hooks = automationConfigSchema.parse(JSON.parse(await readText(root, configPath(host)) ?? \"{}\"));\n const expected = hookConfig(host, hookCommand(host));\n const compatible = compatibleManagedHookCommands(host);\n const mcp = servers?.mason === undefined ? null : object.parse(servers.mason);\n return { mcp, mcpDisabled: mcp?.enabled === false, hooks: Object.fromEntries(Object.keys(expected.hooks).map(event => [event,\n (hooks.hooks?.[event] ?? []).flatMap(group => group.hooks.filter(handler => compatible.includes(handler.command ?? \"\")).map(handler => ({ ...group, hooks: [handler] })) ?? [])])),\n disabled: hooks.disableAllHooks === true || (config.features as Record<string, unknown> | undefined)?.hooks === false ||\n (config.features as Record<string, unknown> | undefined)?.codex_hooks === false };\n}\n","import { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { applyEdit, readText, type FileEdit } from \"../setup/files.js\";\n\nexport interface ProjectMarker {\n version: 1;\n initializedAt: string;\n features?: {\n confluence?: boolean;\n };\n}\n\nconst markerSchema = z.object({\n version: z.literal(1), initializedAt: z.string(),\n features: z.object({ confluence: z.boolean().optional() }).passthrough().optional(),\n}).passthrough();\n\nexport async function loadProjectMarker(rootDir: string): Promise<ProjectMarker | null> {\n const raw = await readStoreJson(rootDir, \".mason/local/project.json\");\n if (raw === null) return null;\n const marker = markerSchema.parse(raw);\n return { ...marker, features: await loadProjectFeatures(rootDir) };\n}\n\nexport async function loadProjectFeatures(rootDir: string) {\n const config = z.record(z.unknown()).parse(await readStoreJson(rootDir, \".mason/config.json\") ?? {});\n return z.object({ confluence: z.boolean().optional() }).passthrough().parse(config.features ?? {});\n}\n\nexport async function saveProjectMarker(rootDir: string, marker: ProjectMarker): Promise<void> {\n const { ancillaryEdits } = await import(\"../setup/config.js\");\n for (const edit of [...await ancillaryEdits(rootDir), ...await projectMarkerEdits(rootDir, marker)]) await applyEdit(rootDir, edit);\n}\n\nasync function projectMarkerEdits(rootDir: string, marker: ProjectMarker): Promise<FileEdit[]> {\n const { features, ...local } = markerSchema.parse(marker);\n const file = \".mason/local/project.json\";\n const edits = [{ path: file, before: await readText(rootDir, file), after: JSON.stringify(local, null, 2) + \"\\n\" }];\n if (features && Object.keys(features).length) {\n const configPath = \".mason/config.json\", before = await readText(rootDir, configPath);\n const config = z.record(z.unknown()).parse(JSON.parse(before ?? \"{}\"));\n config.features = { ...z.record(z.unknown()).parse(config.features ?? {}), ...features };\n edits.push({ path: configPath, before, after: JSON.stringify(config, null, 2) + \"\\n\" });\n }\n return edits;\n}\n\n/** Marker-delimited project instructions make the tools useful in later sessions. */\nexport const CLAUDE_MD_SECTION = `<!-- mason:start -->\n## Mason project knowledge\n\nMason provides recorded decisions and file impact over MCP. A concept map is optional.\n\n- Task, bug, change request, or investigation of why the project works this way → \\`get_context\\` with the task text and known files: matching decisions, related tests, impact, and any available map entries.\n- Before editing a file → \\`get_impact\\` to check references, tests, and historical change partners.\n- Investigation or correction reveals a reusable project lesson → \\`save_decision\\` before finishing. Capture only the lasting constraint and reason, with anchors and known sources, owner, and recorder. This creates a proposal; never infer approval. Preserve uncertain causes and unknown attribution. Route project lessons here; keep personal preferences in agent memory. Skip code summaries, current checkout status, temporary task permissions, session trivia, and secrets. No qualifying lesson means no record.\n- Before saving, compare the lesson with matching \\`get_context\\` records and any pending proposal. If new evidence changes the same lesson's assumptions, scope, or recommended action, revise it with \\`save_decision(id: existingId)\\`, including when it is accepted. Preserve supported rationale and sources, replace obsolete instructions, and add the new evidence. Create a separate record for a genuinely distinct lesson; skip unchanged restatements. Revision preserves history and leaves the accepted version operative until authorized review.\n- Consult trust metadata before relying on entries: unknown or changed freshness requires inspection, stale or unknown map verification requires a fresh evidence review, and a recorded failed verdict means the description must be corrected. Check approval too: proposals are suggestions, legacy records are unreviewed, and accepted decisions are recorded constraints subject to freshness checks. An accepted revision remains operative while a pending proposal is reviewed; keep both versions and their freshness distinct.\n- Asked to review or re-verify a decision → \\`review_decision\\` first to inspect content, sources, history, and code changes. Record acceptance, reaffirmation, or retirement only when authorized by the user or a cited team review, with the actual reviewer and reason. Never infer approval from unchanged code. Review and commit the local record through the normal project workflow.\n- For an architectural overview, use \\`get_snapshot\\` if a map is available. If \\`map.status\\` is missing or invalid, use available decisions and source evidence; do not start building a map unless requested.\n- \\`mason_init\\` returns documentation audit and committed-diff review results, plus a short setup guide. Pass \\`evidence\\` with local CI manifest paths to include test and analysis results; the CLI equivalent is \\`mason-review --evidence <manifest>\\`. State skipped, unavailable, stale, or unknown checks explicitly. Related accepted decisions identify review context, not proven violations.\n\n- When documentation repair is authorized, use \\`mason_repair(action: \"prepare\")\\` before edits, keep its baselinePath, and use \\`mason_repair(action: \"verify\", baselinePath)\\` after edits and any final doc commit. Report every original finding's outcome and any new findings. Suppressed advisories remain unresolved; editing a doc does not approve it.\n- When advisory assessment is authorized, use \\`review_advisory(action: \"prepare\", baselinePath, findingId)\\` to inspect original evidence and history. Record \\`addressed\\`, \\`inapplicable\\`, or \\`deferred\\` with the actual reviewer, reason in note, and returned reviewToken only after relevant edits are committed. Commit the assessment and verify the same baseline again. Relevant evidence changes reopen it; deferral stays outstanding. Decision findings use \\`review_decision\\`; advisory closure never approves a decision.\n\n- When Mason automation is installed, use \\`mason_automation(action: \"status\")\\` to inspect configured hooks and observed events, and \\`mason_automation(action: \"check\")\\` to resume its retained repair evidence. CLI fallback: \\`mason-auto status\\` / \\`mason-auto check\\`. Preserve existing baselines across sessions. Automatic checks do not authorize unrelated repairs or approve advisories.\n\nInspect source for what the retrieved context does not answer.\n<!-- mason:end -->`;\n\nexport type InitMode = \"quickstart\" | \"map\" | \"setup\";\n\nconst ASSISTANT_SETUP = `UNIFIED SETUP\nWhen the user requests Mason setup, call mason_init again with mode: \"setup\" and host: \"codex\" or \"claude\" for the assistant being configured. This uses the same engine as mason-auto setup: retain the initial audit before instruction edits, use the installed mason command on PATH, merge project MCP configuration and hooks, update marker-delimited instructions and Git ignore rules, and record setup. A concept map is optional.\nIf the user only requested inspection or review, report findings without running setup. The setup result distinguishes configured from observed activation. Explain the host's native trust step and request a new session; never trust hooks on the user's behalf or claim activation from generated configuration alone. After a normal task finishes, mason_automation(action: \"status\") or mason-auto status reports observed context use and hook events. Existing findings remain reviewable; setup does not approve advisories or manufacture decisions.\n\nThe managed project guidance is:\n${CLAUDE_MD_SECTION}`;\n\nconst QUICKSTART_PLAYBOOK = `Start with the audit and review results included in this response. No concept map is required.\n\n1. Explain the actionable findings with their source evidence. Separate audit issues, advisories, and skipped checks. The review covers committed changes from the merge base to HEAD; workingTree paths are not included in that review. An unavailable or empty check is not proof that the project is correct. Use the CLI for full output if a summary is truncated.\n2. Address findings within the user's requested scope. Setup alone authorizes Mason host configuration, hooks, instructions, and ignore rules; rewriting existing project claims requires repair scope. If repair is authorized, call \\`mason_repair(dir, action: \"prepare\")\\` before editing; it saves the full original findings even when this summary is truncated. Inspect relevant source, make grounded edits, then call \\`mason_repair(dir, action: \"verify\", baselinePath)\\` with that same baseline, including after any final doc commit. Report resolved, unresolved, review-required, unverified, and new findings. Keep suppressed advisories visible even when setup has already dirtied a doc. Do not invent a decision just to populate the store.\n3. When the task reveals a real lesson or constraint, compare matching \\`get_context\\` records first. If its assumptions, scope, or recommended action changed, revise that record using \\`save_decision(id: existingId)\\`; create a separate record for a genuinely distinct lesson and skip unchanged restatements. Include title, body, category, anchors, and known owner/source/actor information. Preserve supported rationale and sources, replace obsolete instructions, and add new evidence. Missing attribution can be added later. The tool writes a local proposal; editing it preserves revision history and requires a new acceptance, while any earlier accepted revision remains operative. An unchanged save never refreshes its evidence. When decision review is requested, \\`review_decision\\` prepares the record and code evidence before any authorized verdict. Review and commit records through the normal workflow. Retrieve it on the next relevant task with \\`get_context(dir, task, files)\\`.\n\n${ASSISTANT_SETUP}\n\nOPTIONAL ARCHITECTURE MAP\nA full map adds feature and flow navigation. Build it only if the user requests it, by calling \\`mason_init(dir, mode: \"map\")\\`. Decision capture and task context do not depend on that build.`;\n\nconst MAP_PLAYBOOK = `The user has requested a full architecture map. Follow this Map-Reduce workflow to cover the codebase. Report the audit and review findings included in this response before beginning.\n\nPHASE 1 — Map (loop until done)\nGoal: process every file in the codebase, batch by batch, producing a partial concept map per batch.\n\n 1. Call \\`generate_snapshot_batch(dir)\\` (omit offset on the first call).\n The response includes:\n - \\`batchId\\`: identifier for this batch\n - \\`offset\\`, \\`nextOffset\\`, \\`totalFiles\\`: progress markers\n - \\`instructions\\`: the system prompt for the batch step\n - \\`prompt\\`: the files in this batch (skeletons + a few deeper bodies)\n 2. Following the \\`instructions\\`, derive features and flows that involve ONLY the files in this batch. Use product-natural feature names (\"home screen\", not \"HomeScreenAndroid\") so the reduce step can merge platform variants.\n 3. Call \\`save_partial_snapshot(dir, batchId, offset, features, flows)\\` to persist the partial.\n 4. If \\`nextOffset\\` is null, the Map phase is done. Otherwise call \\`generate_snapshot_batch(dir, offset=nextOffset)\\` and repeat from step 2.\n\n Briefly tell the user \"Batch N of M done\" each iteration so they see progress.\n\n CRITICAL RULES FOR PHASE 1:\n - Derive features and file paths ONLY from what appears verbatim in the \\`prompt\\` field of each batch response. NEVER invent paths from memory, prior projects, or what you assume a project of this kind would contain. If you have not seen a path in a batch \\`prompt\\`, do not put it in \\`features.files\\` or \\`flows.chain\\`.\n - Process batches SEQUENTIALLY: one \\`generate_snapshot_batch\\` → derive → one \\`save_partial_snapshot\\` → next \\`generate_snapshot_batch\\`. Do not parallelise. Do not call \\`save_snapshot\\` during this phase — that is a Phase 2 step.\n - You must walk every batch until \\`nextOffset\\` is null. Do not stop early. Do not skip ahead to reduce until every batch has been saved as a partial.\n\nPHASE 2 — Reduce (once)\nGoal: merge all partial maps into one coherent product-shaped catalog.\n\n 1. Call \\`reduce_snapshot(dir)\\`. It returns every partial map plus reconciliation instructions.\n 2. Follow the instructions to produce a unified \\`features\\` and \\`flows\\` map. Specifically: merge platform variants (\"home Android\" + \"home iOS\" → \"home screen\"), dedupe near-duplicates, reconcile descriptions, and ensure every file from every partial appears somewhere in the final map.\n 3. Call \\`save_snapshot(dir, features, flows)\\` ONCE with the unified map. Mason detects that partials exist and replaces the snapshot wholesale (rather than merging with any earlier state) and then clears the partials. Do not call \\`save_snapshot\\` more than once per Map-Reduce run.\n\n${ASSISTANT_SETUP}\n\nIf a build is interrupted, its partials remain in \\`.mason/partial-snapshots/\\`. Re-run \\`mason_init(dir, mode: \"map\")\\` to obtain this workflow again.`;\n\nexport function setupPlaybook(mode: InitMode = \"quickstart\"): string {\n return mode === \"map\" ? MAP_PLAYBOOK : QUICKSTART_PLAYBOOK;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\n/**\n * History window for the co-change matrix. One capped git log for the whole\n * repo — unlike impact.ts's per-target walk, review analyzes many files at\n * once and needs a single pass.\n */\nconst HISTORY_COMMITS = 1500;\n\n/** Below this many commits for a file, a co-change rate is noise. */\nconst MIN_FILE_COMMITS = 5;\n/** A partner must share at least this many commits to count. */\nconst MIN_SHARED_COMMITS = 4;\n/** ...and appear in at least this fraction of the changed file's commits. */\nconst MIN_COCHANGE_RATE = 0.6;\n/** Commits touching more files than this are refactors, not signal. */\nconst MAX_COMMIT_FILES = 30;\n\nexport interface CochangeFinding {\n changedFile: string;\n missingPartner: string;\n sharedCommits: number;\n fileCommits: number;\n /** sharedCommits / fileCommits, rounded to 2 places. */\n rate: number;\n}\n\ninterface CochangeMatrix {\n commitsByFile: Map<string, Set<number>>;\n totalCommits: number;\n}\n\nasync function buildMatrix(resolvedRoot: string): Promise<CochangeMatrix | null> {\n try {\n const { stdout: shallow } = await exec(\"git\", [\"rev-parse\", \"--is-shallow-repository\"], { cwd: resolvedRoot });\n if (shallow.trim() === \"true\") return null;\n const { stdout } = await exec(\n \"git\",\n [\"log\", `-n${HISTORY_COMMITS}`, \"--format=%x01\", \"--name-only\", \"-M\"],\n { cwd: resolvedRoot, maxBuffer: 100 * 1024 * 1024 }\n );\n const commitsByFile = new Map<string, Set<number>>();\n const blocks = stdout.split(\"\\x01\");\n let index = 0;\n for (const block of blocks) {\n const files = block\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0 && !l.startsWith(\".mason/\"));\n if (files.length === 0 || files.length > MAX_COMMIT_FILES) continue;\n for (const file of files) {\n let set = commitsByFile.get(file);\n if (!set) {\n set = new Set();\n commitsByFile.set(file, set);\n }\n set.add(index);\n }\n index++;\n }\n return { commitsByFile, totalCommits: index };\n } catch {\n return null;\n }\n}\n\n/**\n * For each changed file, find its historical co-change partners that this\n * diff leaves untouched: files that appeared in >= MIN_COCHANGE_RATE of the\n * changed file's commits (within the window) but are absent from the diff.\n * Deterministic — pure git history, no LLM. Returns null when history is\n * unavailable.\n */\nexport async function findMissingPartners(\n resolvedRoot: string,\n changedFiles: string[],\n existsOnDisk: (relPath: string) => Promise<boolean>,\n allChangedFiles: string[] = changedFiles\n): Promise<CochangeFinding[] | null> {\n const matrix = await buildMatrix(resolvedRoot);\n if (!matrix) return null;\n\n const changedSet = new Set(allChangedFiles);\n const findings: CochangeFinding[] = [];\n\n for (const changedFile of changedFiles) {\n const fileCommits = matrix.commitsByFile.get(changedFile);\n if (!fileCommits || fileCommits.size < MIN_FILE_COMMITS) continue;\n\n for (const [partner, partnerCommits] of matrix.commitsByFile) {\n if (partner === changedFile || changedSet.has(partner)) continue;\n let shared = 0;\n for (const c of fileCommits) {\n if (partnerCommits.has(c)) shared++;\n }\n if (shared < MIN_SHARED_COMMITS) continue;\n const rate = shared / fileCommits.size;\n if (rate < MIN_COCHANGE_RATE) continue;\n if (!(await existsOnDisk(partner))) continue;\n findings.push({\n changedFile,\n missingPartner: partner,\n sharedCommits: shared,\n fileCommits: fileCommits.size,\n rate: Math.round(rate * 100) / 100,\n });\n }\n }\n\n findings.sort((a, b) => b.rate - a.rate || b.sharedCommits - a.sharedCommits);\n return findings;\n}\n","import { normalizeRepoPath } from \"../../utils/paths.js\";\n\n/** Map reported paths from the runner's checkout; never read source via a report URI. */\nexport function evidencePath(value: string, sourceRoot: string, uri = false): string | null {\n if (value.length > 4000) return null;\n let file = value;\n try {\n if (uri) {\n if (file.startsWith(\"file:\")) {\n const url = new URL(file);\n if (url.hostname && url.hostname !== \"localhost\") return null;\n file = decodeURIComponent(url.pathname).replace(/^\\/([A-Za-z]:\\/)/, \"$1\");\n } else {\n if (/^[a-z][a-z0-9+.-]*:/i.test(file)) return null;\n file = decodeURIComponent(file);\n }\n }\n } catch { return null; }\n file = file.replace(/\\\\/g, \"/\");\n const root = sourceRoot.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n if (file.startsWith(\"/\") || /^[A-Za-z]:/.test(file)) {\n if (!file.startsWith(root + \"/\")) return null;\n file = file.slice(root.length + 1);\n }\n return normalizeRepoPath(file);\n}\n","export type CheckOutcome = \"passed\" | \"failed\" | \"skipped\" | \"unavailable\";\nexport interface EvidenceLocation { file: string; line?: number; column?: number }\nexport interface RawFinding {\n id: string;\n message: string;\n severity: \"error\" | \"warning\" | \"note\";\n state: \"active\" | \"suppressed\" | \"absent\" | \"informational\";\n locations: EvidenceLocation[];\n ruleId?: string;\n truncated?: boolean;\n}\nexport interface ParsedEvidence {\n outcome: CheckOutcome;\n findings: RawFinding[];\n counts: Record<string, number>;\n incomplete: boolean;\n diagnostics: string[];\n reportedCommits?: string[];\n reportedCommands?: string[];\n reportedTools?: string[];\n executed?: boolean;\n}\nexport const MAX_FINDINGS = 200;\nexport function messagePreview(message: string) {\n return { message: message.slice(0, 4000), ...(message.length > 4000 ? { truncated: true } : {}) };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding } from \"./types.js\";\n\nconst count = z.number().int().nonnegative();\nconst schema = z.object({\n success: z.boolean(), numTotalTests: count, numPassedTests: count, numFailedTests: count,\n numPendingTests: count, numTodoTests: count, numFailedTestSuites: count,\n testResults: z.array(z.object({\n name: z.string().min(1), status: z.enum([\"passed\", \"failed\"]), message: z.string().optional(),\n assertionResults: z.array(z.object({\n fullName: z.string(), status: z.enum([\"passed\", \"failed\", \"pending\", \"skipped\", \"todo\", \"disabled\"]),\n failureMessages: z.array(z.string()).nullable().optional(),\n location: z.object({ line: count, column: count }).nullable().optional(),\n })),\n })),\n});\n\n/** Vitest JSON reporter output; summary and assertion counts must agree. */\nexport function parseVitest(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw);\n const findings: RawFinding[] = [], diagnostics: string[] = [];\n let passed = 0, failed = 0, skipped = 0;\n for (const [index, suite] of report.testResults.entries()) {\n const file = evidencePath(suite.name, sourceRoot);\n if (!file) diagnostics.push(`Test path is outside the declared checkout or invalid: ${suite.name}`);\n let suiteFailures = 0;\n for (const [testIndex, test] of suite.assertionResults.entries()) {\n if (test.status === \"passed\") passed++;\n else if (test.status === \"failed\") {\n failed++; suiteFailures++;\n findings.push({ id: `${index}:${testIndex}`, ...messagePreview([test.fullName, ...(test.failureMessages ?? [])].join(\"\\n\")),\n severity: \"error\", state: \"active\", locations: file ? [{ file, ...(test.location ? { line: test.location.line, column: test.location.column } : {}) }] : [] });\n } else skipped++;\n }\n if (suite.status === \"failed\" && !suiteFailures) {\n findings.push({ id: `${index}:suite`, ...messagePreview(suite.message || `Test suite failed: ${suite.name}`), severity: \"error\", state: \"active\", locations: file ? [{ file }] : [] });\n }\n }\n if (passed !== report.numPassedTests || failed !== report.numFailedTests || skipped !== report.numPendingTests + report.numTodoTests || passed + failed + skipped !== report.numTotalTests) {\n throw new Error(\"Vitest summary counts disagree with its assertion results\");\n }\n const hasFailures = failed > 0 || report.numFailedTestSuites > 0 || report.testResults.some(s => s.status === \"failed\");\n if (report.success && hasFailures) throw new Error(\"Vitest success conflicts with failed tests or suites\");\n const outcome = hasFailures || !report.success ? \"failed\" : !report.numTotalTests ? \"unavailable\" : !passed ? \"skipped\" : \"passed\";\n if (!report.numTotalTests) diagnostics.push(\"No tests executed; an empty report is not passing test evidence.\");\n if (skipped) diagnostics.push(`${skipped} tests were skipped, pending, disabled, or todo.`);\n return { outcome, findings, counts: { total: report.numTotalTests, passed, failed, skipped, failedSuites: report.numFailedTestSuites },\n incomplete: skipped > 0 || diagnostics.length > 0, diagnostics };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding, type EvidenceLocation } from \"./types.js\";\n\nconst index = z.number().int().nonnegative();\nconst artifact = z.object({ uri: z.string().optional(), uriBaseId: z.string().optional(), index: index.optional() });\nconst message = z.object({ text: z.string().optional(), markdown: z.string().optional(), id: z.string().optional(), arguments: z.array(z.string()).optional() });\nconst level = z.enum([\"error\", \"warning\", \"note\", \"none\"]);\nconst location = z.object({ physicalLocation: z.object({ artifactLocation: artifact.optional(), region: z.object({ startLine: index.optional(), startColumn: index.optional() }).optional() }).optional() });\nconst schema = z.object({\n version: z.literal(\"2.1.0\"), runs: z.array(z.object({\n tool: z.object({ driver: z.object({ name: z.string().min(1), rules: z.array(z.object({ id: z.string(), defaultConfiguration: z.object({ level: level.optional() }).optional(), messageStrings: z.record(message).optional() })).optional(), globalMessageStrings: z.record(message).optional() }) }),\n invocations: z.array(z.object({ executionSuccessful: z.boolean(), commandLine: z.string().optional(), toolExecutionNotifications: z.array(z.object({ level: level.optional(), message })).optional() })).optional(),\n versionControlProvenance: z.array(z.object({ revisionId: z.string().optional() })).optional(),\n originalUriBaseIds: z.record(artifact).optional(), artifacts: z.array(z.object({ location: artifact.optional() })).optional(),\n results: z.array(z.object({\n ruleId: z.string().optional(), ruleIndex: index.optional(), message, level: level.optional(),\n kind: z.enum([\"fail\", \"pass\", \"open\", \"informational\", \"notApplicable\", \"review\"]).optional(),\n baselineState: z.enum([\"new\", \"unchanged\", \"updated\", \"absent\"]).optional(),\n suppressions: z.array(z.object({ kind: z.enum([\"inSource\", \"external\"]), status: z.enum([\"accepted\", \"underReview\", \"rejected\"]).optional() })).nullable().optional(),\n locations: z.array(location).optional(), relatedLocations: z.array(location).optional(),\n })).optional(),\n })),\n});\n\nexport function parseSarif(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw), findings: RawFinding[] = [], diagnostics: string[] = [];\n let active = 0, suppressed = 0, absent = 0, unresolved = 0;\n let executed = report.runs.length > 0, executionFailed = false;\n const reportedCommits: string[] = [], reportedCommands: string[] = [], reportedTools: string[] = [];\n for (const [runIndex, run] of report.runs.entries()) {\n reportedTools.push(run.tool.driver.name);\n reportedCommits.push(...(run.versionControlProvenance ?? []).flatMap(v => v.revisionId ? [v.revisionId] : []));\n if (!run.invocations?.length) executed = false;\n for (const invocation of run.invocations ?? []) {\n if (invocation.commandLine) reportedCommands.push(invocation.commandLine);\n if (!invocation.executionSuccessful) executionFailed = true;\n for (const notification of invocation.toolExecutionNotifications ?? []) {\n diagnostics.push(notification.message.text ?? notification.message.markdown ?? \"SARIF tool execution notification\");\n if (notification.level === \"error\") executionFailed = true;\n }\n }\n if (!run.results) { diagnostics.push(`Run ${runIndex} omits results; analysis output is unavailable.`); executed = false; }\n const resolve = (ref: z.infer<typeof artifact>, seen = new Set<string>()): string | null => {\n if (!ref.uri && ref.index !== undefined) {\n const key = `artifact:${ref.index}`;\n if (seen.has(key)) return null;\n const entry = run.artifacts?.[ref.index]?.location;\n return entry ? resolve(entry, new Set([...seen, key])) : null;\n }\n if (!ref.uri) return null;\n if (!ref.uriBaseId) return ref.uri;\n if (seen.has(ref.uriBaseId)) return null;\n const base = run.originalUriBaseIds?.[ref.uriBaseId];\n if (!base) return null;\n const prefix = resolve(base, new Set([...seen, ref.uriBaseId]));\n if (!prefix) return null;\n // Base URIs use concatenation, preserving traversal for the path validator.\n return /^[a-z][a-z0-9+.-]*:/i.test(ref.uri) ? ref.uri : prefix + ref.uri;\n };\n for (const [resultIndex, result] of (run.results ?? []).entries()) {\n const kind = result.kind ?? \"fail\";\n const isSuppressed = result.suppressions?.some(s => s.status === \"accepted\");\n if (result.suppressions?.some(s => !s.status || s.status === \"underReview\")) {\n diagnostics.push(`Suppression state unresolved for result ${runIndex}:${resultIndex}.`); unresolved++;\n }\n const state = result.baselineState === \"absent\" ? \"absent\" : isSuppressed ? \"suppressed\" : kind === \"fail\" ? \"active\" : \"informational\";\n if (state === \"active\") active++;\n if (state === \"absent\") absent++;\n if (state === \"suppressed\") suppressed++;\n if ([\"open\", \"review\"].includes(kind) && state === \"informational\") { unresolved++; diagnostics.push(`Result ${runIndex}:${resultIndex} needs further analysis or review.`); }\n if (kind === \"pass\" || kind === \"notApplicable\") continue;\n const rule = result.ruleIndex !== undefined ? run.tool.driver.rules?.[result.ruleIndex] : run.tool.driver.rules?.find(rule => rule.id === result.ruleId);\n const template = result.message.id ? rule?.messageStrings?.[result.message.id] ?? run.tool.driver.globalMessageStrings?.[result.message.id] : undefined;\n const rawMessage = result.message.text ?? result.message.markdown ?? template?.text ?? template?.markdown;\n if (!rawMessage) diagnostics.push(`Message cannot be resolved for result ${runIndex}:${resultIndex}.`);\n const rendered = (rawMessage ?? `Unresolved SARIF message ${result.message.id ?? \"\"}`).replace(/\\{(\\d+)\\}/g, (match, n) => result.message.arguments?.[Number(n)] ?? match);\n const locations: EvidenceLocation[] = [];\n for (const entry of [...(result.locations ?? []), ...(result.relatedLocations ?? [])]) {\n const ref = entry.physicalLocation?.artifactLocation;\n const uri = ref ? resolve(ref) : null;\n const file = uri ? evidencePath(uri, sourceRoot, true) : null;\n if (file) locations.push({ file, line: entry.physicalLocation?.region?.startLine, column: entry.physicalLocation?.region?.startColumn });\n else diagnostics.push(`Unresolved or out-of-checkout location for result ${runIndex}:${resultIndex}.`);\n }\n const severity = result.level ?? rule?.defaultConfiguration?.level ?? (kind === \"fail\" ? \"warning\" : \"none\");\n findings.push({ id: `${runIndex}:${resultIndex}`, ruleId: result.ruleId ?? rule?.id, ...messagePreview(rendered), severity: severity === \"none\" ? \"note\" : severity, state, locations });\n }\n }\n if (!report.runs.length) diagnostics.push(\"SARIF contains no analysis runs.\");\n if (executionFailed) diagnostics.push(\"The SARIF tool reported an unsuccessful analysis invocation.\");\n return { outcome: executionFailed || !report.runs.length || report.runs.some(r => !r.results) ? \"unavailable\" : active ? \"failed\" : \"passed\",\n findings, counts: { active, suppressed, absent, unresolved }, incomplete: diagnostics.length > 0,\n diagnostics, reportedCommits, reportedCommands, reportedTools, executed: executed && !executionFailed };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding } from \"./types.js\";\n\nconst schema = z.object({\n version: z.literal(1),\n commit: z.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/).optional(),\n results: z.array(z.object({\n name: z.string().min(1).max(1000), status: z.enum([\"passed\", \"failed\", \"skipped\"]),\n message: z.string().max(100000).optional(),\n locations: z.array(z.object({ file: z.string().min(1).max(4000),\n line: z.number().int().positive().optional(), column: z.number().int().positive().optional() })).max(100).default([]),\n })).max(100000),\n});\n\n/** Adapter boundary for native validators. Derive outcomes from individual results;\n * a manifest still has to establish command completion and commit attribution. */\nexport function parseCheck(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw);\n const diagnostics: string[] = [], findings: RawFinding[] = [];\n const counts = { total: report.results.length, passed: 0, failed: 0, skipped: 0 };\n for (const [index, result] of report.results.entries()) {\n counts[result.status]++;\n const locations = result.locations.flatMap(location => {\n const file = evidencePath(location.file, sourceRoot);\n if (!file) { diagnostics.push(`Check location is outside the declared checkout or invalid: ${location.file}`); return []; }\n return [{ ...location, file }];\n });\n if (result.status === \"failed\") findings.push({ id: String(index),\n ...messagePreview([result.name, result.message].filter(Boolean).join(\"\\n\")), severity: \"error\", state: \"active\", locations });\n }\n if (!counts.total) diagnostics.push(\"No check results were recorded; an empty report is not passing evidence.\");\n if (counts.skipped) diagnostics.push(`${counts.skipped} checks were skipped; verification is incomplete.`);\n return { outcome: counts.failed ? \"failed\" : !counts.total ? \"unavailable\" : !counts.passed ? \"skipped\" : \"passed\",\n counts, findings, incomplete: diagnostics.length > 0, diagnostics,\n ...(report.commit ? { reportedCommits: [report.commit] } : {}) };\n}\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { normalizeRepoPath, matchingPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getWorkingTree } from \"../drift/drift.js\";\nimport { buildTestMap, type TestPair } from \"../test-map.js\";\nimport { decisionApproval, decisionProvenance, effectiveDecision, type DecisionRecord } from \"../decisions/provenance.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { parseVitest } from \"./evidence/vitest.js\";\nimport { parseSarif } from \"./evidence/sarif.js\";\nimport { parseCheck } from \"./evidence/check.js\";\nimport { MAX_FINDINGS, type CheckOutcome, type RawFinding, type ParsedEvidence } from \"./evidence/types.js\";\n\nconst checkSchema = z.object({\n id: z.string().min(1).max(100), kind: z.enum([\"tests\", \"static-analysis\", \"security\", \"complexity\", \"duplication\", \"documentation\"]),\n tool: z.string().min(1).max(200), command: z.string().min(1).max(2000),\n commit: z.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/).nullable().optional(),\n workingTreeClean: z.boolean().optional(),\n source: z.string().max(2000).optional(), sourceRoot: z.string().min(1).max(4000).optional(),\n status: z.enum([\"completed\", \"skipped\", \"unavailable\"]).default(\"completed\"), reason: z.string().min(1).max(2000).optional(),\n exitCode: z.number().int().nullable().optional(),\n environment: z.object({ toolVersion: z.string().min(1).max(200),\n runtime: z.string().min(1).max(200).optional(), platform: z.string().min(1).max(200).optional(),\n configuration: z.array(z.string().min(1).max(4000)).max(100).optional() }).optional(),\n report: z.object({ format: z.enum([\"vitest-json\", \"sarif\", \"mason-check-json\"]), path: z.string().min(1).max(4000) }).optional(),\n});\ntype CheckInput = z.infer<typeof checkSchema>;\nexport interface LinkedFinding extends RawFinding {\n relatedChangedFiles: Array<{ file: string; relationship: \"direct\" | \"paired-test\"; confidence?: string }>;\n acceptedDecisions: Array<{ id: string; title: string; owner: string | null; freshness: Freshness; reviewRequired: boolean; viaFiles: string[] }>;\n totalAcceptedDecisions: number;\n}\nexport interface EvidenceCheck {\n id: string; kind: CheckInput[\"kind\"]; tool: string; command: string; commit: string | null;\n workingTreeClean: boolean | null;\n source: string | null; manifest: string; report: CheckInput[\"report\"] | null;\n outcome: CheckOutcome; freshness: \"current\" | \"stale\" | \"unknown\";\n findings: LinkedFinding[]; totalFindings: number; counts: Record<string, number>;\n incomplete: boolean; diagnostics: string[]; truncated: boolean;\n reportedCommands?: string[]; reportedTools?: string[];\n environment?: CheckInput[\"environment\"];\n}\nexport interface ReviewEvidence {\n version: 1; scope: \"committed\"; headHash: string;\n status: \"passed\" | \"failed\" | \"incomplete\" | \"unavailable\";\n checks: EvidenceCheck[]; diagnostics: string[];\n summary: { passed: number; failed: number; skipped: number; unavailable: number; stale: number; unknown: number };\n workingTree: Awaited<ReturnType<typeof getWorkingTree>>;\n hint: string;\n}\n\nfunction relativeArtifact(root: string, file: string): string {\n const relative = path.isAbsolute(file) ? path.relative(root, file) : file;\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Evidence artifact must be inside the repository: ${file}`);\n return normalized;\n}\n\nfunction linkFinding(finding: RawFinding, changed: Set<string>, pairs: TestPair[], decisions: DecisionRecord[], freshness: Record<string, Freshness>): LinkedFinding {\n const located = [...new Set(finding.locations.map(l => l.file))];\n const paired = pairs.filter(pair => located.includes(pair.test));\n const relatedChangedFiles: LinkedFinding[\"relatedChangedFiles\"] = located.filter(file => changed.has(file)).map(file => ({ file, relationship: \"direct\" }));\n for (const pair of paired) {\n if (changed.has(pair.source) && !relatedChangedFiles.some(f => f.file === pair.source)) relatedChangedFiles.push({ file: pair.source, relationship: \"paired-test\", confidence: pair.confidence });\n }\n const allFiles = [...new Set([...located, ...paired.map(pair => pair.source)])];\n const acceptedDecisions = decisions.map(effectiveDecision).filter(d => d.status === \"active\" && decisionApproval(d) === \"accepted\")\n .map(d => ({ d, viaFiles: matchingPaths(d.files, allFiles) })).filter(match => match.viaFiles.length)\n .map(({ d, viaFiles }) => {\n const state = freshness[d.id] ?? \"unknown\", provenance = decisionProvenance(d, state);\n return { id: d.id, title: d.title, owner: provenance.owner, freshness: state, reviewRequired: provenance.reviewRequired, viaFiles };\n });\n return { ...finding, relatedChangedFiles, acceptedDecisions: acceptedDecisions.slice(0, 5), totalAcceptedDecisions: acceptedDecisions.length };\n}\n\n/** Read-only imports. Commands, URLs, and result locations are never executed or fetched. */\nexport async function collectReviewEvidence(root: string, manifests: string[], changedFiles: string[], decisions: DecisionRecord[], decisionFreshness: Record<string, Freshness> = {}, reviewedHead?: string): Promise<ReviewEvidence> {\n const [headHash, workingTree] = await Promise.all([reviewedHead ?? getCurrentGitHash(root), getWorkingTree(root)]);\n const output: ReviewEvidence = {\n version: 1, scope: \"committed\", headHash, status: \"unavailable\", checks: [], diagnostics: [], workingTree,\n summary: { passed: 0, failed: 0, skipped: 0, unavailable: 0, stale: 0, unknown: 0 },\n hint: \"Evidence describes the recorded check runs for a commit, not uncommitted edits or complete test coverage. Commands and CI provenance are imported assertions, not authenticated execution. File and test-pair associations identify relevant decisions; they do not prove a decision was violated. Missing checks must be declared in the manifest to be reported.\",\n };\n const seen = new Set<string>(), changed = new Set(changedFiles);\n let pairs: TestPair[] | undefined;\n if (manifests.length > 10) output.diagnostics.push(\"Only the first 10 evidence manifests were imported.\");\n for (const supplied of manifests.slice(0, 10)) {\n let manifest: string, raw: { version: 1; checks: unknown[] };\n try {\n manifest = relativeArtifact(root, supplied);\n raw = z.object({ version: z.literal(1), checks: z.array(z.unknown()) }).parse(await readStoreJson(root, manifest));\n } catch (error) { output.diagnostics.push(`${supplied}: ${String(error)}`); continue; }\n if (!raw.checks.length) output.diagnostics.push(`${manifest}: no checks declared.`);\n for (const [index, item] of raw.checks.entries()) {\n if (output.checks.length >= 50) { output.diagnostics.push(\"Only the first 50 checks were imported.\"); break; }\n const input = checkSchema.safeParse(item);\n if (!input.success) { output.diagnostics.push(`${manifest} check ${index}: ${input.error.message}`); continue; }\n const check = input.data;\n if (seen.has(check.id)) { output.diagnostics.push(`Duplicate check id ${check.id}; give different runs distinct ids.`); continue; }\n seen.add(check.id);\n const result: EvidenceCheck = {\n id: check.id, kind: check.kind, tool: check.tool, command: check.command,\n commit: check.commit?.toLowerCase() ?? null, workingTreeClean: check.workingTreeClean ?? null, source: check.source ?? null, manifest, report: check.report ?? null,\n outcome: \"unavailable\", freshness: \"unknown\", findings: [], totalFindings: 0, counts: {}, incomplete: false, diagnostics: [], truncated: false,\n ...(check.environment ? { environment: check.environment } : {}),\n };\n output.checks.push(result);\n if (check.workingTreeClean !== true) result.diagnostics.push(\"The check's working tree was dirty or not recorded; its results cannot be attributed to the claimed commit alone.\");\n else if (result.commit && headHash !== \"unknown\") result.freshness = result.commit === headHash.toLowerCase() ? \"current\" : \"stale\";\n else result.diagnostics.push(\"The tested commit or reviewed HEAD is unknown.\");\n if (check.status !== \"completed\") {\n result.outcome = check.status;\n result.diagnostics.push(check.reason ?? \"No reason was recorded for this skipped or unavailable check.\");\n continue;\n }\n try {\n if (!check.report) throw new Error(\"Completed check has no report artifact.\");\n if (check.report.format !== \"mason-check-json\" && (check.kind === \"tests\") !== (check.report.format === \"vitest-json\")) throw new Error(\"Test checks require vitest-json or mason-check-json; analysis checks require sarif or mason-check-json.\");\n const file = relativeArtifact(root, check.report.path);\n const report = await readStoreJson(root, file);\n if (report === null) throw new Error(`Report artifact is missing: ${file}`);\n const sourceRoot = check.sourceRoot ?? root;\n if (!path.posix.isAbsolute(sourceRoot) && !/^[A-Za-z]:[\\\\/]/.test(sourceRoot)) throw new Error(\"sourceRoot must identify the absolute checkout root on the check runner.\");\n const parsed: ParsedEvidence = check.report.format === \"vitest-json\" ? parseVitest(report, sourceRoot)\n : check.report.format === \"mason-check-json\" ? parseCheck(report, sourceRoot) : parseSarif(report, sourceRoot);\n result.outcome = parsed.outcome; result.counts = parsed.counts; result.incomplete = parsed.incomplete;\n result.diagnostics.push(...parsed.diagnostics);\n result.reportedCommands = parsed.reportedCommands; result.reportedTools = parsed.reportedTools;\n if (parsed.reportedCommits?.some(commit => !result.commit || commit.toLowerCase() !== result.commit)) {\n result.freshness = \"unknown\"; result.incomplete = true;\n result.diagnostics.push(\"Report revision metadata conflicts with, or cannot be tied to, the manifest's tested commit.\");\n }\n if (check.exitCode == null && !parsed.executed) {\n result.incomplete = true; result.diagnostics.push(\"Neither an exit code nor successful analysis invocation was recorded; completion cannot be confirmed.\");\n }\n if (check.exitCode != null && check.exitCode !== 0 && result.outcome === \"passed\") {\n result.outcome = \"failed\"; result.diagnostics.push(`Check command exited ${check.exitCode} despite a report with no active failures.`);\n }\n if (check.kind === \"tests\" && pairs === undefined) {\n try { pairs = (await buildTestMap(root)).paired; }\n catch (error) { pairs = []; output.diagnostics.push(`Test pairing unavailable: ${String(error)}`); }\n }\n result.totalFindings = parsed.findings.length;\n // Prioritize findings on changed files while retaining overall outcomes and counts.\n const testPairs = check.kind === \"tests\" ? pairs ?? [] : [];\n const relevant = new Set([...changed, ...testPairs.filter(p => changed.has(p.source)).map(p => p.test)]);\n const touchesChange = (f: RawFinding) => f.locations.some(l => relevant.has(l.file));\n parsed.findings.sort((a, b) => Number(b.state === \"active\") - Number(a.state === \"active\") || Number(touchesChange(b)) - Number(touchesChange(a)));\n result.findings = parsed.findings.slice(0, MAX_FINDINGS).map(f => linkFinding(f, changed, testPairs, decisions, decisionFreshness));\n result.truncated = parsed.findings.length > MAX_FINDINGS || result.findings.some(f => f.truncated || f.totalAcceptedDecisions > f.acceptedDecisions.length);\n } catch (error) {\n result.outcome = \"unavailable\"; result.incomplete = true; result.diagnostics.push(String(error));\n }\n }\n }\n if (!output.checks.length) output.diagnostics.push(\"No readable checks were imported.\");\n for (const check of output.checks) {\n output.summary[check.outcome]++;\n if (check.freshness !== \"current\") output.summary[check.freshness]++;\n }\n if (output.checks.some(c => c.outcome === \"failed\" && c.freshness === \"current\")) output.status = \"failed\";\n else if (!output.checks.length || output.checks.every(c => c.outcome === \"unavailable\")) output.status = \"unavailable\";\n else if (output.diagnostics.length || output.checks.some(c => c.outcome !== \"passed\" || c.freshness !== \"current\" || c.incomplete)) output.status = \"incomplete\";\n else output.status = \"passed\";\n return output;\n}\n\nexport function summarizeEvidence(evidence: ReviewEvidence) {\n const previews = (values: string[], limit: number) => values.slice(0, limit).map(value => value.slice(0, 2000));\n const checks = evidence.checks.slice(0, 10).map(check => {\n const findings = check.findings.slice(0, 5).map(finding => ({ ...finding,\n ruleId: finding.ruleId?.slice(0, 200),\n locations: finding.locations.slice(0, 5), totalLocations: finding.locations.length,\n relatedChangedFiles: finding.relatedChangedFiles.slice(0, 5), totalRelatedChangedFiles: finding.relatedChangedFiles.length,\n acceptedDecisions: finding.acceptedDecisions.map(decision => ({ ...decision, viaFiles: decision.viaFiles.slice(0, 5) })),\n truncated: finding.truncated || finding.locations.length > 5 || finding.relatedChangedFiles.length > 5 ||\n (finding.ruleId?.length ?? 0) > 200 || finding.acceptedDecisions.some(d => d.viaFiles.length > 5),\n }));\n return { ...check, findings, reportedCommands: check.reportedCommands ? previews(check.reportedCommands, 5) : undefined,\n reportedTools: check.reportedTools ? previews(check.reportedTools, 5) : undefined,\n diagnostics: previews(check.diagnostics, 10),\n truncated: check.truncated || check.findings.length > 5 || findings.some(f => f.truncated) || check.diagnostics.length > 10 ||\n check.diagnostics.some(d => d.length > 2000) || [check.reportedCommands ?? [], check.reportedTools ?? []].some(values => values.length > 5 || values.some(v => v.length > 2000)),\n };\n });\n return { ...evidence, checks, diagnostics: previews(evidence.diagnostics, 20),\n truncated: evidence.checks.length > 10 || evidence.diagnostics.length > 20 || evidence.diagnostics.some(d => d.length > 2000) || checks.some(c => c.truncated),\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getChangesWithStatus, touchedPaths } from \"../drift/drift.js\";\nimport { decisionProvenance, decisionKnowledge, effectiveDecision } from \"../decisions/provenance.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionRecord } from \"../decisions/decisions.js\";\nimport { findMissingPartners } from \"./cochange.js\";\nimport type { CochangeFinding } from \"./cochange.js\";\nimport { collectReviewEvidence, type ReviewEvidence } from \"./evidence.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\n\nconst exec = promisify(execFile);\n\n/** Diffs larger than this are refactors; partner analysis would be noise. */\nconst MAX_ANALYZED_FILES = 50;\n\nexport interface TouchedDecision extends Partial<ReturnType<typeof decisionProvenance>> {\n id: string;\n title: string;\n body: string;\n category: string;\n anchors: string[];\n freshness?: Freshness;\n touchedFiles: string[];\n pendingProposal?: NonNullable<ReturnType<typeof decisionKnowledge>[\"pendingProposal\"]> & { touchedFiles: string[] };\n}\n\nexport interface ReviewReport {\n /** Additive-only schema. */\n version: 1;\n diagnostics?: StoreDiagnostic[];\n root: string;\n base: string;\n mergeBase: string;\n changedFiles: string[];\n /** Historical partners this diff leaves untouched — drive exit 1. */\n missingPartners: CochangeFinding[];\n /** Decisions whose anchors the diff touches — informational only. */\n touchedDecisions: TouchedDecision[];\n historyAvailable: boolean;\n truncated: boolean;\n /** Optional imported CI results. Does not change the legacy review exit codes. */\n evidence?: ReviewEvidence;\n}\n\nasync function resolveMergeBase(\n resolvedRoot: string,\n base: string,\n head: string\n): Promise<string | null> {\n try {\n const { stdout } = await exec(\"git\", [\"merge-base\", base, head], {\n cwd: resolvedRoot,\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/** First base ref that resolves: origin/HEAD, origin/main, origin/master, main. */\nexport async function defaultBase(resolvedRoot: string): Promise<string | null> {\n for (const ref of [\"origin/HEAD\", \"origin/main\", \"origin/master\", \"main\"]) {\n try {\n await exec(\"git\", [\"rev-parse\", \"--verify\", \"--quiet\", ref], {\n cwd: resolvedRoot,\n });\n return ref;\n } catch {\n // Try the next candidate.\n }\n }\n return null;\n}\n\nfunction anchorsTouched(\n record: DecisionRecord,\n changedFiles: string[]\n): string[] {\n return matchingPaths(record.files, changedFiles);\n}\n\n/**\n * Review a diff against what git history and the decision store know:\n * co-change partners the diff forgot, and recorded constraints it touches.\n * Deterministic — no LLM, no network. Returns null when the base ref or\n * merge base cannot be resolved.\n */\nexport async function computeReview(\n rootDir: string,\n base: string,\n options: { evidence?: string[] } = {}\n): Promise<ReviewReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const head = await getCurrentGitHash(resolvedRoot);\n if (head === \"unknown\") return null;\n const mergeBase = await resolveMergeBase(resolvedRoot, base, head);\n if (!mergeBase) return null;\n\n const changes = await getChangesWithStatus(resolvedRoot, mergeBase, head);\n if (changes === null) return null;\n\n const changedFiles = touchedPaths(changes);\n\n const report: ReviewReport = {\n version: 1,\n root: resolvedRoot,\n base,\n mergeBase,\n changedFiles,\n missingPartners: [],\n touchedDecisions: [],\n historyAvailable: true,\n truncated: false,\n };\n const store = await loadDecisionStore(resolvedRoot);\n report.diagnostics = store.diagnostics;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, store.records);\n if (options.evidence !== undefined) {\n report.evidence = await collectReviewEvidence(resolvedRoot, options.evidence, changedFiles, store.records, decisionDrift.freshness, head);\n if (store.diagnostics.length) {\n report.evidence.diagnostics.push(\"Invalid decision records make knowledge associations incomplete; consult review diagnostics.\");\n if (report.evidence.status === \"passed\") report.evidence.status = \"incomplete\";\n }\n }\n const finalize = async () => {\n if (report.evidence && await getCurrentGitHash(resolvedRoot) !== head) {\n report.evidence.diagnostics.push(\"HEAD changed during the review; rerun to obtain consistent change and knowledge associations.\");\n for (const check of report.evidence.checks) check.freshness = \"unknown\";\n report.evidence.summary.stale = 0;\n report.evidence.summary.unknown = report.evidence.checks.length;\n if (report.evidence.status !== \"unavailable\") report.evidence.status = \"incomplete\";\n }\n return report;\n };\n if (changedFiles.length === 0) return finalize();\n\n let analyzed = changedFiles;\n if (changedFiles.length > MAX_ANALYZED_FILES) {\n analyzed = changedFiles.slice(0, MAX_ANALYZED_FILES);\n report.truncated = true;\n }\n\n const partners = await findMissingPartners(\n resolvedRoot,\n analyzed,\n async (relPath) => {\n try {\n await fs.access(path.join(resolvedRoot, relPath));\n return true;\n } catch {\n return false;\n }\n },\n changedFiles\n );\n if (partners === null) {\n report.historyAvailable = false;\n } else {\n report.missingPartners = partners;\n }\n\n const decisions = store.records;\n for (const record of decisions) {\n if (record.status !== \"active\") continue;\n const effective = effectiveDecision(record);\n const touched = anchorsTouched(effective, changedFiles);\n const proposalTouched = effective !== record ? anchorsTouched(record, changedFiles) : [];\n if (touched.length > 0 || proposalTouched.length > 0) {\n const { pendingProposal, ...knowledge } = decisionKnowledge(record, decisionDrift.freshness?.[record.id] ?? \"unknown\", decisionDrift.pendingProposals?.[record.id]?.freshness ?? \"unknown\");\n report.touchedDecisions.push({\n ...knowledge,\n ...(pendingProposal ? { pendingProposal: { ...pendingProposal, touchedFiles: proposalTouched } } : {}),\n id: record.id,\n anchors: effective.files,\n freshness: decisionDrift.freshness?.[record.id] ?? \"unknown\",\n touchedFiles: touched,\n });\n }\n }\n\n return finalize();\n}\n","import { computeAudit } from \"../audit/audit.js\";\nimport { computeReview, defaultBase } from \"../review/review.js\";\nimport { getWorkingTree } from \"../drift/drift.js\";\nimport { inspectSnapshot } from \"../snapshot/snapshot.js\";\nimport { decisionApproval, effectiveDecision } from \"../decisions/provenance.js\";\nimport { summarizeEvidence } from \"../review/evidence.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\n\nconst MAX_FINDINGS = 20;\nconst reason = (error: unknown) => error instanceof Error ? error.message : String(error);\n\nasync function auditSummary(root: string) {\n try {\n const report = await computeAudit(root);\n if (!report) return { status: \"no-context-files\", reason: \"No README.md or agent instruction files found to audit.\" };\n if (!report.gitAvailable) return { status: \"unavailable\", reason: \"Audit needs readable Git history to verify documentation claims.\", docs: report.docs };\n return {\n ...report, status: \"complete\",\n issues: report.issues.slice(0, MAX_FINDINGS),\n advisories: report.advisories.slice(0, MAX_FINDINGS),\n suppressedAdvisories: (report.suppressedAdvisories ?? []).slice(0, MAX_FINDINGS),\n counts: { issues: report.issues.length, advisories: report.advisories.length,\n suppressedAdvisories: report.suppressedAdvisories?.length ?? 0 },\n truncated: report.issues.length > MAX_FINDINGS || report.advisories.length > MAX_FINDINGS ||\n (report.suppressedAdvisories?.length ?? 0) > MAX_FINDINGS,\n };\n } catch (error) { return { status: \"unavailable\", reason: reason(error) }; }\n}\n\nasync function reviewSummary(root: string, requestedBase?: string, evidence?: string[]) {\n const workingTree = await getWorkingTree(root);\n const scope = \"committed\" as const;\n try {\n const base = requestedBase ?? await defaultBase(root);\n if (!base) return { status: \"unavailable\", scope, workingTree, reason: \"No default review base resolves. Pass base to mason_init, or run mason-review --base <ref>.\" };\n const report = await computeReview(root, base, { evidence });\n if (!report) return { status: \"unavailable\", scope, base, workingTree, reason: \"The review base, merge base, or committed diff could not be read.\" };\n return {\n ...report, scope, workingTree,\n ...(report.evidence ? { evidence: summarizeEvidence(report.evidence) } : {}),\n status: !report.historyAvailable ? \"unavailable\" : report.changedFiles.length ? \"complete\" : \"no-changes\",\n ...(!report.historyAvailable ? { reason: \"Co-change history could not be read; review findings are incomplete.\" } : {}),\n changedFiles: report.changedFiles.slice(0, MAX_FINDINGS),\n missingPartners: report.missingPartners.slice(0, MAX_FINDINGS),\n touchedDecisions: report.touchedDecisions.slice(0, MAX_FINDINGS),\n counts: { changedFiles: report.changedFiles.length, missingPartners: report.missingPartners.length, touchedDecisions: report.touchedDecisions.length },\n truncated: report.truncated || [report.changedFiles, report.missingPartners, report.touchedDecisions].some(list => list.length > MAX_FINDINGS),\n hint: \"Reviews cover merge-base..HEAD. Uncommitted paths are reported separately in workingTree; they have not been reviewed.\",\n };\n } catch (error) { return { status: \"unavailable\", scope, workingTree, reason: reason(error) }; }\n}\n\n/** Useful first-run results, with no writes, model calls, or map requirement. */\nexport async function inspectOnboarding(root: string, base?: string, evidence?: string[]) {\n const [audit, review, map, decisions] = await Promise.all([\n auditSummary(root), reviewSummary(root, base, evidence), inspectSnapshot(root), loadDecisionStore(root),\n ]);\n return {\n audit, review, map: { status: map.status },\n decisions: {\n active: decisions.records.filter(record => record.status === \"active\").length,\n ...Object.fromEntries([\"accepted\", \"proposed\", \"unreviewed\"].map(approval => [approval, decisions.records.filter(record => record.status === \"active\" && decisionApproval(effectiveDecision(record)) === approval).length])),\n pendingProposals: decisions.records.filter(record => effectiveDecision(record) !== record).length,\n },\n diagnostics: [...map.diagnostics, ...decisions.diagnostics],\n };\n}\n","import path from \"node:path\";\n\nexport interface ReferenceEntry {\n file: string;\n matches: string[];\n /** Literal relative JS/TS paths or named JVM imports tied to declared symbols. */\n kind: \"import\" | \"mention\";\n evidence: \"resolved-import\" | \"explicit-path\" | \"name-candidate\";\n}\n\nconst jsExtensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".cts\", \".mjs\", \".cjs\"];\nconst genericNames = new Set([\"index\", \"main\", \"app\", \"init\", \"config\", \"settings\", \"types\", \"utils\", \"test\", \"tests\"]);\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst word = (s: string) => new RegExp(`(?<![\\\\w$])${escape(s)}(?![\\\\w$])`);\n\n/** Treat templates (including nested interpolation strings) as opaque syntax. */\nfunction templateEnd(content: string, start: number): number {\n let i = start + 1, interpolation = 0;\n while (i < content.length) {\n const c = content[i];\n if (c === \"\\\\\") { i += 2; continue; }\n if (!interpolation) {\n if (c === \"`\") return i + 1;\n if (c === \"$\" && content[i + 1] === \"{\") { interpolation = 1; i += 2; continue; }\n } else {\n if (c === \"`\") { i = templateEnd(content, i); continue; }\n if (c === '\"' || c === \"'\") {\n const quote = c;\n for (i++; i < content.length; i++) { if (content[i] === \"\\\\\") i++; else if (content[i] === quote) { i++; break; } }\n continue;\n }\n if (content.startsWith(\"//\", i)) { const end = content.indexOf(\"\\n\", i + 2); i = end < 0 ? content.length : end; continue; }\n if (content.startsWith(\"/*\", i)) { const end = content.indexOf(\"*/\", i + 2); i = end < 0 ? content.length : end + 2; continue; }\n if (c === \"{\") interpolation++;\n if (c === \"}\") interpolation--;\n }\n i++;\n }\n return content.length;\n}\n\n/** Skip comments and string bodies before inspecting JS/TS import syntax. */\nfunction tokens(content: string): { value: string; string?: boolean }[] {\n const result: { value: string; string?: boolean }[] = [];\n const re = /\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)|\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|`(?:\\\\.|[^`\\\\])*`|[\\w$]+|[^\\s]/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(content))) {\n const value = match[0];\n if (value.startsWith(\"//\") || value.startsWith(\"/*\")) continue;\n if (/^[\"'`]/.test(value)) {\n if (value[0] === \"`\") {\n re.lastIndex = templateEnd(content, match.index);\n result.push({ value: \"<opaque>\" });\n continue;\n }\n // Escaped or interpolated module strings require runtime/language resolution.\n result.push({ value: value.slice(1, -1), string: !value.includes(\"\\\\\") && value[0] !== \"`\" });\n // Keep opaque strings opaque even if their content equals import/from.\n if (!result.at(-1)!.string) result[result.length - 1] = { value: \"<opaque>\" };\n } else result.push({ value });\n }\n return result;\n}\n\nfunction imports(content: string): string[] {\n const ts = tokens(content), found: string[] = [];\n for (let i = 0; i < ts.length; i++) {\n const t = ts[i];\n if (t.string || ts[i - 1]?.value === \".\") continue;\n if ([\"require\", \"import\"].includes(t.value) && ts[i + 1]?.value === \"(\" && ts[i + 2]?.string && ts[i + 3]?.value === \")\") {\n found.push(ts[i + 2].value);\n }\n if (![\"import\", \"export\"].includes(t.value) || ts[i + 1]?.value === \"(\") continue;\n if (t.value === \"import\" && ts[i + 1]?.string) { found.push(ts[i + 1].value); continue; }\n for (let j = i + 1; j < Math.min(ts.length, i + 150); j++) {\n if ([\";\", \"=\", \"import\", \"export\"].includes(ts[j].value) && !ts[j].string) break;\n if (ts[j].value === \"from\" && !ts[j].string && ts[j + 1]?.string) { found.push(ts[j + 1].value); break; }\n }\n }\n return found;\n}\n\nfunction qualifiedName(ts: ReturnType<typeof tokens>, start: number): string {\n let name = \"\";\n for (let i = start; i < ts.length; i++) {\n if (ts[i].string || !/^[A-Za-z_$][\\w$]*$/.test(ts[i].value)) break;\n name += ts[i].value;\n if (ts[i + 1]?.value !== \".\" || !/^[A-Za-z_$][\\w$]*$/.test(ts[i + 2]?.value ?? \"\")) break;\n name += \".\"; i++;\n }\n return name;\n}\n\n/** Match explicit package/symbol identity; package wildcards stay unresolved. */\nfunction declaredSymbols(content: string): string[] {\n const ts = tokens(content);\n const packageAt = ts.findIndex(t => !t.string && t.value === \"package\");\n if (packageAt < 0) return [];\n const pkg = qualifiedName(ts, packageAt + 1), names: string[] = [];\n let depth = 0;\n for (let i = 0; i < ts.length; i++) {\n if (ts[i].string) continue;\n if (ts[i].value === \"{\") depth++;\n if (ts[i].value === \"}\") depth--;\n if (depth === 0 && [\"class\", \"interface\", \"object\", \"enum\", \"typealias\", \"fun\"].includes(ts[i].value) &&\n /^[A-Za-z_$][\\w$]*$/.test(ts[i + 1]?.value ?? \"\") && ts[i + 1].value !== \"class\") names.push(pkg + \".\" + ts[i + 1].value);\n }\n return names;\n}\n\nfunction jvmImports(content: string): string[] {\n const ts = tokens(content), result: string[] = [];\n for (let i = 0; i < ts.length; i++) if (!ts[i].string && ts[i].value === \"import\") {\n const name = qualifiedName(ts, i + (ts[i + 1]?.value === \"static\" ? 2 : 1));\n if (name) result.push(name);\n }\n return result;\n}\n\nfunction resolveImport(file: string, specifier: string, available: Set<string>): string | null {\n if (!specifier.startsWith(\"./\") && !specifier.startsWith(\"../\")) return null;\n const relative = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier));\n if (relative.startsWith(\"../\")) return null;\n if (available.has(relative)) return relative;\n const ext = path.posix.extname(relative);\n const replacements: Record<string, string[]> = { \".js\": [\".ts\", \".tsx\"], \".mjs\": [\".mts\"], \".cjs\": [\".cts\"] };\n const candidates = ext ? (replacements[ext] ?? []).map(e => relative.slice(0, -ext.length) + e) :\n jsExtensions.flatMap(e => [relative + e, relative + \"/index\" + e]);\n const found = candidates.filter(f => available.has(f));\n // Resolution depends on compiler configuration when multiple candidates exist.\n return found.length === 1 ? found[0] : null;\n}\n\n/** Explicit paths are textual evidence, not proof of a dependency. */\nfunction mentionsPath(content: string, target: string): boolean {\n return new RegExp(`(?<![\\\\w./\\\\\\\\-])(?:\\\\./)?${escape(target)}(?![\\\\w./\\\\\\\\-])`).test(content);\n}\n\nexport function createReferenceMatcher(targets: string[], available: Set<string>, targetContents = new Map<string, string>()) {\n const counts = new Map<string, number>();\n for (const file of available) {\n const name = path.posix.basename(file, path.posix.extname(file));\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n const jvmTargets = new Map([...targetContents].filter(([file]) => /\\.(?:kt|kts|java)$/.test(file)).map(([file, content]) => [file, declaredSymbols(content)]));\n return (source: { path: string; content: string }): ReferenceEntry[] => {\n if (targets.includes(source.path)) return [];\n const resolved = new Set(jsExtensions.includes(path.posix.extname(source.path)) ?\n imports(source.content).map(s => resolveImport(source.path, s, available)).filter(Boolean) : []);\n if (/\\.(?:kt|kts|java)$/.test(source.path)) {\n const imported = jvmImports(source.content);\n for (const [target, symbols] of jvmTargets) if (symbols.some(symbol => imported.some(name => name === symbol || name.startsWith(symbol + \".\")))) resolved.add(target);\n }\n // Keep each evidence class separate: one resolved import must not promote\n // another target's ambiguous name match in the same source file.\n const groups = new Map<ReferenceEntry[\"evidence\"], string[]>();\n const add = (evidence: ReferenceEntry[\"evidence\"], match: string) => groups.set(evidence, [...(groups.get(evidence) ?? []), match]);\n for (const target of targets) {\n if (resolved.has(target)) { add(\"resolved-import\", target); continue; }\n if (mentionsPath(source.content, target)) {\n add(\"explicit-path\", target);\n continue;\n }\n const ext = path.posix.extname(target), name = path.posix.basename(target, ext);\n // A config/doc name, generic symbol, or duplicate basename has too little identity.\n if (!/\\.(?:[cm]?[jt]sx?|py|kt|java|go|rs|swift|rb|cs|cpp|c|h|hpp|dart|php)$/.test(ext) ||\n name.startsWith(\".\") || name.length < 3 || genericNames.has(name.toLowerCase()) || counts.get(name) !== 1) continue;\n if (word(name).test(source.content)) {\n add(\"name-candidate\", name);\n }\n }\n return [...groups].map(([evidence, matches]) => ({ file: source.path, matches, kind: evidence === \"resolved-import\" ? \"import\" : \"mention\", evidence }));\n };\n}\n\nexport function sortReferences(result: ReferenceEntry[]): ReferenceEntry[] {\n const rank = { \"resolved-import\": 0, \"explicit-path\": 1, \"name-candidate\": 2 };\n return result.sort((a, b) => rank[a.evidence] - rank[b.evidence] || b.matches.length - a.matches.length || a.file.localeCompare(b.file));\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_GLOB } from \"../utils/files.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { createReferenceMatcher, sortReferences, type ReferenceEntry } from \"./references.js\";\nexport type { ReferenceEntry } from \"./references.js\";\n\nconst exec = promisify(execFile);\n\nexport interface CochangeEntry {\n file: string;\n cochangeRate: number;\n sharedCommits: number;\n}\n\nexport interface TestEntry {\n file: string;\n confidence: \"exact\" | \"best-guess\";\n}\n\nexport interface ImpactResult {\n targetFiles: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n tests: TestEntry[];\n}\n\nexport async function analyzeImpact(\n rootDir: string,\n targetFiles: string[]\n): Promise<ImpactResult> {\n const resolvedRoot = path.resolve(rootDir);\n\n // Resolve target files to full relative paths if only basename given\n const resolvedTargets = await resolveTargetFiles(resolvedRoot, targetFiles);\n\n const [cochange, references, tests] = await Promise.all([\n getCochangeFiles(resolvedRoot, resolvedTargets),\n getReferences(resolvedRoot, resolvedTargets),\n getRelatedTests(resolvedRoot, resolvedTargets),\n ]);\n\n return {\n targetFiles: resolvedTargets,\n cochange,\n references,\n tests,\n };\n}\n\nasync function resolveTargetFiles(\n rootDir: string,\n targets: string[]\n): Promise<string[]> {\n const resolved: string[] = [];\n const access = await createFileAccess(rootDir);\n\n for (const target of targets) {\n // If it contains a path separator, use as-is\n if (target.includes(\"/\")) {\n const normalized = normalizeRepoPath(target);\n if (normalized) resolved.push(normalized);\n continue;\n }\n\n // Otherwise, search for the filename\n const matches = await access.list(`**/${target}`);\n\n if (matches.length > 0) {\n resolved.push(matches[0]);\n } else {\n // Try without extension\n const noExt = target.replace(/\\.[^.]+$/, \"\");\n const extMatches = await access.list(`**/${noExt}.*`);\n if (extMatches.length > 0) {\n resolved.push(extMatches[0]);\n } else {\n resolved.push(target); // Keep as-is, might still work for grep\n }\n }\n }\n\n return resolved;\n}\n\nasync function getCochangeFiles(\n rootDir: string,\n targetFiles: string[]\n): Promise<CochangeEntry[]> {\n const cochangeCounts = new Map<string, number>();\n let totalTargetCommits = 0;\n\n for (const targetFile of targetFiles) {\n try {\n // Get commits that touched this file (cap at 500)\n const { stdout: commitLog } = await exec(\n \"git\",\n [\"log\", \"--format=%H\", \"-n\", \"500\", \"--\", targetFile],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const commits = commitLog.trim().split(\"\\n\").filter(Boolean);\n totalTargetCommits += commits.length;\n\n if (commits.length === 0) continue;\n\n // For each commit, get the other files that changed\n for (const commit of commits) {\n try {\n const { stdout: filesInCommit } = await exec(\n \"git\",\n [\"diff-tree\", \"--no-commit-id\", \"--name-only\", \"-r\", commit],\n { cwd: rootDir }\n );\n\n const files = filesInCommit.trim().split(\"\\n\").filter(Boolean);\n for (const file of files) {\n if (targetFiles.includes(file)) continue; // Skip the target itself\n cochangeCounts.set(file, (cochangeCounts.get(file) ?? 0) + 1);\n }\n } catch {\n // Skip this commit\n }\n }\n } catch {\n // No git or file not tracked\n }\n }\n\n if (totalTargetCommits === 0) return [];\n\n // Filter to files that co-change >30% of the time, sort by rate\n return [...cochangeCounts.entries()]\n .map(([file, count]) => ({\n file,\n cochangeRate: Math.round((count / totalTargetCommits) * 100) / 100,\n sharedCommits: count,\n }))\n .filter((e) => e.cochangeRate >= 0.3 || e.sharedCommits >= 3)\n .sort((a, b) => b.cochangeRate - a.cochangeRate)\n .slice(0, 20);\n}\n\nasync function getReferences(\n rootDir: string,\n targetFiles: string[]\n): Promise<ReferenceEntry[]> {\n const access = await createFileAccess(rootDir);\n const allSourceFiles = await access.list(SOURCE_GLOB);\n const available = new Set(allSourceFiles);\n const targetContents = new Map<string, string>();\n for (const target of targetFiles) {\n const source = await access.read(target);\n if (source) { available.add(target); targetContents.set(target, source.content); }\n }\n const match = createReferenceMatcher(targetFiles, available, targetContents);\n const references: ReferenceEntry[] = [];\n for (let i = 0; i < allSourceFiles.length; i += 50) {\n const batch = await Promise.all(allSourceFiles.slice(i, i + 50).map(file => access.read(file)));\n for (const source of batch) if (source) references.push(...match(source));\n }\n return sortReferences(references);\n}\n\nasync function getRelatedTests(\n rootDir: string,\n targetFiles: string[]\n): Promise<TestEntry[]> {\n const testPatterns = [\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*Test.kt\",\n \"**/*Test.java\",\n \"**/*Tests.kt\",\n \"**/*Tests.java\",\n \"**/test_*.py\",\n \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\",\n \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n\n const testFiles = await (await createFileAccess(rootDir)).list(testPatterns);\n const results: TestEntry[] = [];\n\n for (const target of targetFiles) {\n const targetBaseName = path\n .basename(target)\n .replace(/\\.[^.]+$/, \"\");\n\n for (const testFile of testFiles) {\n const testBaseName = path\n .basename(testFile)\n .replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (sourceName === targetBaseName) {\n results.push({\n file: testFile,\n confidence: \"exact\",\n });\n }\n }\n }\n\n return results;\n}\n","import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { inspectSnapshot, normalizeFeatureType } from \"../snapshot/snapshot.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport type { FeatureType, Snapshot } from \"../snapshot/snapshot.js\";\nimport { createSnapshotTrustReader, readSnapshotTrustIndex } from \"../snapshot/trust.js\";\nimport { computeDrift, type DriftReport } from \"../drift/drift.js\";\nimport { analyzeImpact } from \"../impact/impact.js\";\nimport type { CochangeEntry, ReferenceEntry } from \"../impact/impact.js\";\nimport { scoreEntry, tokenSet } from \"./lexical.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { decisionKnowledge, effectiveDecision, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport { anchorMatches, sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { trustHint, type TrustState } from \"./trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionDriftReport } from \"../decisions/drift.js\";\nimport type { DecisionCategory, DecisionRecord } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst MAX_FEATURES = 5;\nconst MAX_FLOWS = 3;\nconst MAX_IMPACT_TARGETS = 3;\nconst MAX_DECISIONS = 5;\nconst DECISION_FEATURE_OVERLAP_BOOST = 2;\n\nexport interface MatchedFeature {\n description: string;\n files: string[];\n tests?: string[];\n type: FeatureType;\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedFlow {\n description: string;\n chain: string[];\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedDecision extends ReturnType<typeof decisionKnowledge> {\n title: string;\n /** Full body — the payload the decisions store exists for. */\n body: string;\n category: DecisionCategory;\n files: string[];\n score: number;\n /** Anchor files changed since this record was last verified. */\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface ContextBundle {\n exists: true;\n map: { status: \"available\" };\n diagnostics?: StoreDiagnostic[];\n task: string;\n features: Record<string, MatchedFeature>;\n flows: Record<string, MatchedFlow>;\n /** Relevant knowledge; approval distinguishes constraints from proposals. */\n decisions: Record<string, MatchedDecision>;\n /** All tests paired with the matched files, deduped. */\n relatedTests: string[];\n impact: {\n targets: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n /** Weak name-only candidates omitted from compact context; available via get_impact. */\n referenceCandidatesOmitted?: number;\n } | null;\n freshness: {\n stale: boolean;\n recommendation: string;\n /** Matched entries whose files changed since they were last verified. */\n staleMatches: string[];\n };\n hint: string;\n}\n\nexport interface NoMatchBundle {\n exists: true;\n map: { status: \"available\" };\n impact?: ContextBundle[\"impact\"];\n relatedTests?: string[];\n diagnostics?: StoreDiagnostic[];\n freshness?: DriftReport | null;\n trust?: { features: Record<string, TrustState>; flows: Record<string, TrustState> };\n task: string;\n features: Record<string, never>;\n flows: Record<string, never>;\n /** Decisions can match even when no feature does. */\n decisions: Record<string, MatchedDecision>;\n /** The full feature catalog, so the caller can still act without a second guess. */\n availableFeatures: Record<string, string>;\n availableFlows: Record<string, string>;\n hint: string;\n}\n\nexport interface UnmappedContextBundle extends Omit<ContextBundle, \"exists\" | \"map\" | \"freshness\"> {\n /** Legacy exists indicates map availability, not decision availability. */\n exists: false;\n map: { status: \"missing\" | \"invalid\" };\n freshness: { stale: null; recommendation: \"no-map\" | \"repair-map\"; staleMatches: string[] };\n}\n\nasync function collectImpact(root: string, candidates: string[]): Promise<{\n impact: ContextBundle[\"impact\"]; relatedTests: string[];\n}> {\n const targets = new Set<string>();\n let sourceFiles: string[] | undefined;\n for (const candidate of sanitizeRepoPaths(candidates)) {\n const stat = await fs.stat(path.join(root, candidate)).catch(() => null);\n if (stat?.isDirectory()) {\n sourceFiles ??= await (await createFileAccess(root)).list();\n for (const file of sourceFiles) {\n if (anchorMatches(candidate, file)) targets.add(file);\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n } else {\n targets.add(candidate);\n }\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n if (!targets.size) return { impact: null, relatedTests: [] };\n const result = await analyzeImpact(root, [...targets]);\n const referenceCandidatesOmitted = result.references.filter(r => r.evidence === \"name-candidate\").length;\n return {\n impact: { targets: result.targetFiles, cochange: result.cochange, references: result.references.filter(r => r.evidence !== \"name-candidate\").slice(0, 10),\n ...(referenceCandidatesOmitted ? { referenceCandidatesOmitted } : {}) },\n relatedTests: [...new Set(result.tests.map(t => t.file))],\n };\n}\n\n/**\n * Assemble everything needed to start a task in one call: matching map\n * entries, their files and tests, blast radius for the top files, and\n * per-entry freshness. Deterministic and LLM-free.\n *\n * `files` optionally anchors matching to an explicit file list (e.g. a diff):\n * entries containing those files are boosted above pure lexical matches.\n */\nexport async function assembleContext(\n rootDir: string,\n task: string,\n files?: string[]\n): Promise<ContextBundle | NoMatchBundle | UnmappedContextBundle> {\n const resolvedRoot = path.resolve(rootDir);\n const mapState = await inspectSnapshot(resolvedRoot);\n const snapshot = mapState.snapshot;\n const store = await loadDecisionStore(resolvedRoot);\n const allDecisions = store.records;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, allDecisions);\n const taskTokens = tokenSet(task);\n const anchorFiles = new Set(sanitizeRepoPaths(files ?? []));\n\n const anchorBoost = (entryFiles: string[]): number => {\n let boost = 0;\n for (const f of entryFiles) if ([...anchorFiles].some(file => anchorMatches(f, file))) boost += 5;\n return boost;\n };\n\n if (!snapshot) {\n const decisions = matchDecisions(allDecisions, taskTokens, anchorBoost, new Set(), decisionDrift);\n const { impact, relatedTests } = await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]);\n const invalid = mapState.status === \"invalid\";\n return {\n exists: false, map: { status: invalid ? \"invalid\" : \"missing\" }, task,\n features: {}, flows: {}, decisions, impact, relatedTests,\n diagnostics: [...mapState.diagnostics, ...store.diagnostics],\n freshness: { stale: null, recommendation: invalid ? \"repair-map\" : \"no-map\", staleMatches: [] },\n hint: (invalid ? \"The concept map is invalid; consult diagnostics and repair it before relying on map entries. \" : \"No concept map is present. Maps are optional; decisions and file impact work now. \") +\n (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" + trustHint(Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])) : \"No saved decision matched. Inspect the source and use save_decision for a learned constraint or incident rationale. \") +\n (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n }\n\n const drift = await computeDrift(resolvedRoot);\n const readTrust = createSnapshotTrustReader(resolvedRoot);\n\n const featureScores = Object.entries(snapshot.features)\n .map(([name, feat]) => ({\n name,\n feat,\n score:\n scoreEntry(taskTokens, { name, description: feat.description, files: feat.files }) +\n anchorBoost([...feat.files, ...(feat.tests ?? [])]),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FEATURES);\n\n const flowScores = Object.entries(snapshot.flows)\n .map(([name, flow]) => ({\n name,\n flow,\n score:\n scoreEntry(taskTokens, { name, description: flow.description, files: flow.chain }) +\n anchorBoost(flow.chain),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FLOWS);\n\n const matchedEntryFiles = new Set<string>([\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap((e) => e.flow.chain),\n ]);\n const decisions = matchDecisions(\n allDecisions,\n taskTokens,\n anchorBoost,\n matchedEntryFiles,\n decisionDrift\n );\n\n if (featureScores.length === 0 && flowScores.length === 0) {\n const bundle = noMatchBundle(snapshot, task, decisions);\n Object.assign(bundle, await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]));\n bundle.diagnostics = store.diagnostics;\n bundle.freshness = drift;\n bundle.trust = await readSnapshotTrustIndex(readTrust, snapshot, drift);\n bundle.hint += \" \" + trustHint([\n ...Object.values(bundle.trust.features),\n ...Object.values(bundle.trust.flows),\n ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])]),\n ]);\n if (Object.keys(decisions).length) bundle.hint += \" \" + DECISION_GUIDANCE;\n if (store.diagnostics.length) bundle.hint += \" Some decision records are invalid; consult diagnostics.\";\n return bundle;\n }\n\n const features: Record<string, MatchedFeature> = {};\n const staleMatches: string[] = [];\n for (const { name, feat, score } of featureScores) {\n const trust = await readTrust(\"feature\", name, feat, drift?.featureFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n features[name] = {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n score,\n stale,\n trust,\n };\n }\n\n const flows: Record<string, MatchedFlow> = {};\n for (const { name, flow, score } of flowScores) {\n const trust = await readTrust(\"flow\", name, flow, drift?.flowFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n flows[name] = {\n description: flow.description,\n chain: flow.chain,\n score,\n stale,\n trust,\n };\n }\n\n const { impact, relatedTests: impactTests } = await collectImpact(resolvedRoot, [\n ...anchorFiles,\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap(e => e.flow.chain),\n ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])]),\n ]);\n\n const relatedTests = [\n ...new Set([\n ...featureScores.flatMap((e) => e.feat.tests ?? []),\n ...impactTests,\n ]),\n ];\n\n const stale = drift?.stale ?? false;\n return {\n exists: true,\n map: { status: \"available\" },\n diagnostics: store.diagnostics,\n task,\n features,\n flows,\n decisions,\n relatedTests,\n impact,\n freshness: {\n stale,\n recommendation: drift?.recommendation ?? \"up-to-date\",\n staleMatches,\n },\n hint: (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" : \"\") + trustHint([...Object.values(features).map(e => e.trust), ...Object.values(flows).map(e => e.trust), ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])]) + (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n}\n\n/**\n * Score active decisions against the task with the same lexical machinery\n * as map entries, plus a feature-overlap boost: a decision anchored to a\n * file of an already-matched feature is relevant even with zero lexical\n * overlap (\"auth is weird\" should surface on any auth task).\n */\nfunction matchDecisions(\n allDecisions: DecisionRecord[],\n taskTokens: Set<string>,\n anchorBoost: (files: string[]) => number,\n matchedEntryFiles: Set<string>,\n decisionDrift: DecisionDriftReport\n): Record<string, MatchedDecision> {\n const scored = allDecisions\n .filter((d) => d.status === \"active\")\n .map((d) => {\n const scoreRevision = (revision: DecisionRecord) =>\n scoreEntry(taskTokens, { name: revision.title, description: revision.body, files: revision.files }) + anchorBoost(revision.files) +\n (revision.files.some(f => [...matchedEntryFiles].some(file => anchorMatches(f, file))) ? DECISION_FEATURE_OVERLAP_BOOST : 0);\n const score = Math.max(scoreRevision(effectiveDecision(d)), scoreRevision(d));\n return { d, score };\n })\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_DECISIONS);\n\n const result: Record<string, MatchedDecision> = {};\n for (const { d, score } of scored) {\n result[d.id] = {\n ...decisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\"),\n score,\n stale: decisionDrift.freshness?.[d.id] !== \"current\",\n };\n }\n return result;\n}\n\nfunction noMatchBundle(\n snapshot: Snapshot,\n task: string,\n decisions: Record<string, MatchedDecision>\n): NoMatchBundle {\n const availableFeatures: Record<string, string> = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n availableFeatures[name] = feat.description;\n }\n const availableFlows: Record<string, string> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n availableFlows[name] = flow.description;\n }\n return {\n exists: true,\n map: { status: \"available\" },\n task,\n features: {},\n flows: {},\n decisions,\n availableFeatures,\n availableFlows,\n hint: \"No map entry matched the task wording. The full catalog is listed — pick the relevant entries and call get_context again with their names in the task, or read their files directly via get_snapshot.\",\n };\n}\n","import fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { withLock, events, type Host } from \"../automation/store.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { loadSetup } from \"./model.js\";\nimport { executingVersion, inactiveSetupMessage } from \"./launcher.js\";\n\nconst observationSchema = z.object({ version: z.literal(1), masonVersion: z.string(), root: z.string(), revision: z.string(), host: z.enum([\"codex\", \"claude\"]),\n contextCalls: z.number().int().nonnegative(), lastContextAt: z.string().optional(),\n sessions: z.record(z.object({ events: z.array(z.enum(events)), at: z.string(),\n verificationStatus: z.string().optional(), reportPath: z.string().optional() })),\n});\nexport type Observation = z.infer<typeof observationSchema>;\nexport function observationPath(directory: string, host: Host, revision: string, version = executingVersion()) { return `${directory}/activation/${host}-${revision}-${hash(version).slice(0, 12)}.json`; }\n\nexport async function readObservation(root: string, directory: string, host: Host, revision: string, version = executingVersion()): Promise<Observation | null> {\n const raw = await readStoreJson(root, observationPath(directory, host, revision, version));\n if (raw === null) return null;\n const record = observationSchema.parse(raw);\n if (record.root !== root || record.host !== host || record.revision !== revision || record.masonVersion !== version) throw new Error(\"Activation receipt belongs to another installation.\");\n return record;\n}\n\n/** Only the configured Mason invocation supplies these values. Never persist task text or tool arguments. */\nexport async function observeActivation(dir: string, event: \"context\" | typeof events[number], options: {\n sessionId?: string; verificationStatus?: string; reportPath?: string; directory?: string;\n} = {}): Promise<string | null> {\n const host = process.env.MASON_SETUP_HOST, revision = process.env.MASON_SETUP_REVISION;\n if ((host !== \"codex\" && host !== \"claude\") || !process.env.MASON_SETUP_ROOT) return null;\n try {\n if (!revision) {\n if ((await loadSetup(process.env.MASON_SETUP_ROOT))?.hosts[host]) {\n return \"Mason setup is now present. Restart the assistant to connect this MCP session to the configured integration; activation has not been established by this session.\";\n }\n return inactiveSetupMessage();\n }\n const capturedDirectory = options.directory?.match(/^\\.mason\\/reports\\/automation\\/[a-f0-9]{24}$/)?.[0]\n ?? options.reportPath?.match(/^(\\.mason\\/reports\\/automation\\/[a-f0-9]{24})\\/checks\\//)?.[1];\n const ws = capturedDirectory ? { root: await fs.realpath(dir), directory: capturedDirectory } : await workspace(dir);\n if (ws.root !== await fs.realpath(process.env.MASON_SETUP_ROOT)) return null;\n const setup = await loadSetup(ws.root);\n if (setup?.hosts[host]?.revision !== revision) return \"Mason setup changed; restart the assistant to observe the current integration.\";\n const directory = ws.directory + \"/activation\";\n await withLock(ws.root, directory, async () => {\n const now = new Date().toISOString();\n const record = await readObservation(ws.root, ws.directory, host, revision) ?? {\n version: 1, masonVersion: executingVersion(), root: ws.root, revision, host, contextCalls: 0, sessions: {},\n } satisfies Observation;\n if (event === \"context\") { record.contextCalls++; record.lastContextAt = now; }\n else if (options.sessionId) {\n const key = hash(options.sessionId);\n const session = record.sessions[key] ?? { events: [], at: now };\n // Repeated tool observations add no activation evidence; avoid another write.\n if (event !== \"task_end\" && session.events.includes(event)) return;\n session.events = [...new Set([...session.events, event])];\n session.at = now;\n if (event === \"task_end\") { session.verificationStatus = options.verificationStatus; session.reportPath = options.reportPath; }\n record.sessions[key] = session;\n const ordered = Object.entries(record.sessions).sort(([, a], [, b]) => b.at.localeCompare(a.at));\n record.sessions = Object.fromEntries(ordered.slice(0, 32));\n } else return;\n await writeStoreJson(ws.root, observationPath(ws.directory, host, revision), record);\n });\n return null;\n } catch (error) {\n return \"Mason activation observation could not be saved; activation coverage is unknown. \" + (error instanceof Error ? error.message : String(error)).replace(/[\\u0000-\\u001f\\u007f]/g, \" \").slice(0, 300);\n }\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { events, type Host } from \"../automation/store.js\";\nimport { automationStatus } from \"../automation/runtime.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { hookConfig } from \"../automation/adapters.js\";\nimport { loadSetup, loadSetupReceipt } from \"./model.js\";\nimport { inspectHostConfig, instructionEdits } from \"./config.js\";\nimport { hookCommand, mcpCommand, installedCommand } from \"./launcher.js\";\nimport { readObservation } from \"./observations.js\";\n\nexport async function setupStatus(dir: string) {\n const ws = await workspace(dir);\n const setup = await loadSetup(ws.root);\n if (!setup) {\n const partial = await Promise.all(([\"codex\", \"claude\"] as const).map(async host => ({ host,\n receipt: await loadSetupReceipt(ws.root, ws.directory, host) })));\n const pending = partial.filter(item => item.receipt !== null).map(item => item.host);\n return { version: 1, status: pending.length ? \"incomplete\" : \"not-configured\", hosts: {},\n next: pending.length ? \"Setup did not finish. Rerun mason-auto setup --host \" + pending[0] + \" to resume using the retained original evidence.\"\n : \"Project hooks are inactive until local setup. Run mason setup --host codex or --host claude.\" };\n }\n const hosts: Record<string, { status: string; runtime: string; mcp: string; instructions: string; hookConfiguration: string;\n observedEvents: string[]; contextCalls: number; verificationStatus: string; pending: string[]; updates: string[] }> = {};\n const installed = await installedCommand();\n const automation = await automationStatus(ws.root);\n for (const host of [\"codex\", \"claude\"] as const) {\n const entry = setup.hosts[host];\n if (!entry) continue;\n const instructions = await instructionEdits(ws.root, host);\n const instructionsCurrent = instructions.every(edit => edit.before === edit.after);\n const config = await inspectHostConfig(ws.root, host, undefined);\n const mcp = !config.mcpDisabled && hash(config.mcp) === entry.mcpFingerprint &&\n isDeepStrictEqual({ command: config.mcp?.command, args: config.mcp?.args }, mcpCommand(host));\n const expectedHooks = hookConfig(host, hookCommand(host)).hooks;\n const currentHooks = isDeepStrictEqual(config.hooks, expectedHooks);\n const compatibleHooks = Object.fromEntries(Object.entries(config.hooks).map(([event, groups]) => [event,\n groups.map(group => ({ ...group, hooks: group.hooks.map(handler => ({ ...handler,\n command: expectedHooks.SessionStart[0].hooks[0].command })) }))]));\n const hooks = isDeepStrictEqual(compatibleHooks, expectedHooks) && !config.disabled;\n const local = await loadSetupReceipt(ws.root, ws.directory, host);\n const configured = local?.status === \"configured\" && local.root === ws.root && local.revision === entry.revision;\n const observation = await readObservation(ws.root, ws.directory, host, entry.revision, installed.version ?? \"unavailable\");\n // Complete lifecycle evidence must come from one session in this worktree/branch.\n const sessions = Object.values(observation?.sessions ?? {}).sort((a, b) => b.at.localeCompare(a.at));\n const complete = sessions.find(session => events.every(event => session.events.includes(event)));\n const observedEvents = complete?.events ?? sessions[0]?.events ?? [];\n const pending: string[] = [];\n if (!installed.available) pending.push(installed.message!);\n if (!mcp || !hooks || !instructionsCurrent || !configured) pending.push(\"Rerun setup to reconcile project configuration; inspect any disabled host settings.\");\n if (!observation?.contextCalls) pending.push(\"Start a new assistant session and request task context through Mason's get_context tool.\");\n if (!complete) pending.push(\"Review/trust the host configuration, then complete a normal task to observe the full hook lifecycle.\");\n if (automation.status === \"unavailable\") pending.push(\"The latest automation attempt did not establish verification. Run mason-auto check and inspect its diagnostics.\");\n const healthy = installed.available && mcp && hooks && instructionsCurrent && configured && automation.status !== \"unavailable\";\n hosts[host] = { status: healthy ? complete && observation?.contextCalls ? \"active\" : \"pending\" : \"attention\",\n runtime: installed.available ? \"global (\" + installed.version + \")\" : \"unavailable-on-path\", mcp: mcp ? \"configured\" : \"changed\",\n instructions: instructionsCurrent ? \"current\" : \"changed\", hookConfiguration: hooks ? currentHooks ? \"configured\" : \"compatible\" : \"disabled-or-changed\",\n observedEvents, contextCalls: observation?.contextCalls ?? 0,\n verificationStatus: automation.status === \"current\" ? automation.verificationStatus ?? \"unavailable\" : \"unavailable\", pending,\n updates: hooks && !currentHooks ? [\"A newer hook template is available. Run mason setup --host \" + host + \" to update it when convenient; review and commit the configuration changes.\"] : [] };\n }\n const statuses = Object.values(hosts).map(host => host.status);\n const decisions = await loadDecisionStore(ws.root);\n return { version: 1, status: statuses.length && statuses.every(status => status === \"active\") ? \"active\"\n : statuses.includes(\"attention\") ? \"attention\" : \"pending\", root: ws.root, hosts,\n decisionRecords: decisions.records.length, diagnostics: decisions.diagnostics,\n scope: \"Activation receipts record observed use after setup, not complete interception, correct repairs, or measured usefulness. Host trust and higher-priority settings may prevent execution. Receipts are local to this worktree and branch.\" };\n}\n\nexport function summarizeActivation(status: Awaited<ReturnType<typeof setupStatus>>): string {\n const lines = [\"Mason setup: \" + status.status + \".\"];\n for (const [host, state] of Object.entries(status.hosts)) {\n lines.push(`${host}: ${state.status}`, ` Runtime: ${state.runtime}; MCP: ${state.mcp}; instructions: ${state.instructions}.`,\n ` Hooks: ${state.hookConfiguration}; observed: ${state.observedEvents.join(\", \") || \"none\"}.`,\n ` Task context requests: ${state.contextCalls}; verification: ${state.verificationStatus}.`,\n ...state.pending.map(message => \" Next: \" + message));\n lines.push(...state.updates.map(message => \" Optional: \" + message));\n }\n if (\"decisionRecords\" in status) lines.push(`Decision records: ${status.decisionRecords}.`);\n if (status.next) lines.push(status.next);\n return lines.join(\"\\n\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { withLock, type Host } from \"../automation/store.js\";\nimport { automate } from \"../automation/runtime.js\";\nimport { inspectOnboarding } from \"../mcp/onboarding.js\";\nimport { writeStoreJson } from \"../utils/storage.js\";\nimport { applyEdit, readText } from \"./files.js\";\nimport { ancillaryEdits, hookEdits, instructionEdits, mcpEdit, inspectHostConfig } from \"./config.js\";\nimport { hookCommand, installedCommand } from \"./launcher.js\";\nimport { hookConfig } from \"../automation/adapters.js\";\nimport { loadSetup, loadSetupReceipt, SETUP_PATH, type SetupConfig } from \"./model.js\";\nimport { setupStatus } from \"./status.js\";\nimport { ownershipEdit, completedHookOwnership } from \"./ownership.js\";\nimport type { Progress } from \"../utils/progress.js\";\n\nexport async function selectHost(root: string, explicit?: Host): Promise<Host> {\n if (explicit) return explicit;\n if (process.env.MASON_SETUP_HOST === \"codex\" || process.env.MASON_SETUP_HOST === \"claude\") return process.env.MASON_SETUP_HOST;\n const found: Host[] = [];\n if (await readText(root, \".codex/config.toml\") !== null || await readText(root, \".codex/hooks.json\") !== null) found.push(\"codex\");\n if (await readText(root, \".claude/settings.json\") !== null || await readText(root, \".mcp.json\") !== null) found.push(\"claude\");\n if (found.length === 1) return found[0];\n throw new Error(\"Choose the assistant for setup with --host codex or --host claude.\");\n}\n\nexport async function setupProject(dir: string, options: { host?: Host; base?: string; evidence?: string[]; progress?: Progress } = {}) {\n options.progress?.step(\"Checking project configuration\");\n const ws = await workspace(dir);\n const host = await selectHost(ws.root, options.host);\n return withLock(ws.root, \".mason/reports/setup-lock\", async () => {\n const existing = await loadSetup(ws.root);\n const previousReceipt = await loadSetupReceipt(ws.root, ws.directory, host);\n const installed = await installedCommand();\n if (!installed.available) throw new Error(installed.message!);\n // Preflight every edit before shared files change.\n const instructions = await instructionEdits(ws.root, host);\n const mcp = await mcpEdit(ws.root, host);\n const hooks = await hookEdits(ws.root, host);\n const ancillary = await ancillaryEdits(ws.root);\n const edits = [...ancillary, ...instructions, mcp, ...hooks];\n const setupBefore = await readText(ws.root, SETUP_PATH);\n const mcpFingerprint = hash((await inspectHostConfig(ws.root, host, mcp.after)).mcp);\n const desiredHooks = hookConfig(host, hookCommand(host)).hooks;\n const configuredHook = desiredHooks.SessionStart[0].hooks[0].command;\n const ownership = await ownershipEdit(ws.root, [...instructions, mcp, hooks[0]], { [hooks[0].path]: configuredHook });\n const fingerprint = hash({ command: \"mason\",\n mcp: mcpFingerprint, hooks: desiredHooks,\n instructions: instructions.map(edit => edit.path) });\n const previous = existing?.hosts[host];\n const changed = edits.some(edit => edit.before !== edit.after) || previous?.fingerprint !== fingerprint;\n const revision = !changed && previous ? previous.revision : randomUUID();\n const setup: SetupConfig = existing ?? { version: 2, hosts: {} };\n setup.hosts[host] = { configuredVersion: installed.version!, revision, fingerprint, mcpFingerprint, instructions: instructions.map(e => e.path) };\n\n // Capture through the ordinary automation engine so later hooks resume the\n // same immutable baselines. This must precede instruction and ignore edits.\n options.progress?.step(\"Auditing documentation and preserving original findings\");\n const initial = await automate(ws.root, { event: \"turn_start\" });\n options.progress?.step(\"Reviewing project context and committed changes\");\n const findings = await inspectOnboarding(ws.root, options.base, options.evidence);\n const receiptPath = ws.directory + \"/setup-\" + host + \".json\";\n const initialReportPath = previousReceipt?.initialReportPath ?? initial.report.reportPath;\n const initialBaselinePaths = previousReceipt?.initialBaselinePaths ?? initial.report.baselinePaths;\n options.progress?.step(`Configuring ${host === \"codex\" ? \"Codex\" : \"Claude Code\"} integration`);\n await writeStoreJson(ws.root, receiptPath, { version: 1, host, status: \"installing\", initialReportPath,\n initialBaselinePaths, root: ws.root, revision });\n const changedFiles: string[] = [];\n if (await applyEdit(ws.root, ownership)) changedFiles.push(ownership.path);\n for (const edit of edits) if (await applyEdit(ws.root, edit)) changedFiles.push(edit.path);\n if (await applyEdit(ws.root, { path: SETUP_PATH, before: setupBefore, after: JSON.stringify(setup, null, 2) + \"\\n\" })) changedFiles.push(SETUP_PATH);\n if (await applyEdit(ws.root, await completedHookOwnership(ws.root, hooks[0].path, configuredHook)) && !changedFiles.includes(ownership.path)) changedFiles.push(ownership.path);\n // Ensure a repo that initially had no instructions now has a baseline too.\n options.progress?.step(\"Checking configuration and retained findings\");\n const checked = await automate(ws.root, { event: \"turn_start\" });\n const configured = await inspectHostConfig(ws.root, host, undefined);\n await writeStoreJson(ws.root, receiptPath, { version: 1, host, status: \"configured\", initialReportPath,\n initialBaselinePaths, root: ws.root, revision, configuredAt: new Date().toISOString() });\n return { version: 1, action: \"setup\", status: \"configured\", host, root: ws.root,\n runtime: { kind: \"global\", command: \"mason\", version: installed.version }, changedFiles, initialReportPath, findings, reportPath: checked.report.reportPath,\n activation: await setupStatus(ws.root),\n next: configured.disabled || configured.mcpDisabled ? \"Mason hooks or MCP are disabled in project configuration. Review that setting before activation.\"\n : host === \"codex\" ? \"Review/trust this project's MCP configuration and hooks in Codex (/hooks in the CLI), then start a new session and give it a normal task.\"\n : \"Approve the project MCP server in Claude Code, then start a new session and give it a normal task.\",\n };\n });\n}\n\nexport function summarizeSetup(result: Awaited<ReturnType<typeof setupProject>>): string {\n const audit = result.findings.audit;\n return [`Mason configured for ${result.host}.`,\n \" MCP server and lifecycle hooks use mason from PATH.\",\n \" Project instructions updated; original audit evidence retained.\",\n ` ${result.changedFiles.length} files changed.`,\n `Initial audit: ${audit.status}${\"counts\" in audit ? `; ${audit.counts.issues} issues, ${audit.counts.advisories + audit.counts.suppressedAdvisories} advisories` : \"\"}.`,\n ...(\"issues\" in audit ? audit.issues.slice(0, 3).map(f => \" \" + f.message) : []),\n `Original evidence: ${result.initialReportPath}`,\n \"Activation: \" + result.activation.status + \".\",\n result.next,\n \"If the assistant cannot find mason, restart the desktop app so it picks up PATH.\",\n \"After the task finishes, run mason-auto status. Configuration alone does not establish activation.\",\n ].join(\"\\n\");\n}\n","import type { ConfluenceConfig } from \"../llm/config.js\";\n\nexport interface ConfluencePage {\n id: string;\n title: string;\n version: number;\n body: string;\n parentId?: string;\n}\n\nexport interface CreatePageInput {\n spaceId: string;\n title: string;\n body: string;\n parentId?: string;\n}\n\nexport interface UpdatePageInput {\n id: string;\n title: string;\n body: string;\n version: number;\n parentId?: string;\n}\n\nexport interface ConfluenceSpace {\n id: string;\n key: string;\n name: string;\n}\n\nexport interface ConfluenceRootPage {\n id: string;\n title: string;\n}\n\nexport interface ConfluenceClient {\n resolveSpaceId(spaceKey: string): Promise<string>;\n listSpaces(): Promise<ConfluenceSpace[]>;\n listRootPages(spaceId: string): Promise<ConfluenceRootPage[]>;\n findPageByTitle(spaceId: string, title: string): Promise<ConfluencePage | null>;\n createPage(input: CreatePageInput): Promise<ConfluencePage>;\n updatePage(input: UpdatePageInput): Promise<ConfluencePage>;\n}\n\ninterface PageApiResponse {\n id: string;\n title: string;\n parentId?: string;\n version?: { number: number };\n body?: { storage?: { value?: string } };\n}\n\nexport function createConfluenceClient(\n config: ConfluenceConfig,\n fetchFn: typeof fetch = fetch\n): ConfluenceClient {\n const baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n const auth =\n \"Basic \" +\n Buffer.from(`${config.email}:${config.apiToken}`).toString(\"base64\");\n\n async function call(\n method: string,\n path: string,\n body?: unknown\n ): Promise<unknown> {\n const res = await fetchFn(`${baseUrl}${path}`, {\n method,\n headers: {\n Authorization: auth,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `Confluence ${method} ${path} failed: ${res.status} ${res.statusText} — ${text}`\n );\n }\n\n if (res.status === 204) return null;\n return res.json();\n }\n\n function toPage(raw: PageApiResponse): ConfluencePage {\n return {\n id: raw.id,\n title: raw.title,\n version: raw.version?.number ?? 1,\n body: raw.body?.storage?.value ?? \"\",\n parentId: raw.parentId,\n };\n }\n\n return {\n async resolveSpaceId(spaceKey: string): Promise<string> {\n const res = (await call(\n \"GET\",\n `/wiki/api/v2/spaces?keys=${encodeURIComponent(spaceKey)}`\n )) as { results?: Array<{ id: string; key: string }> };\n const space = res.results?.find((s) => s.key === spaceKey);\n if (!space) {\n throw new Error(`Confluence space not found: ${spaceKey}`);\n }\n return space.id;\n },\n\n async listSpaces(): Promise<ConfluenceSpace[]> {\n const all: ConfluenceSpace[] = [];\n let cursor = \"/wiki/api/v2/spaces?limit=100\";\n while (cursor) {\n const res = (await call(\"GET\", cursor)) as {\n results?: Array<{ id: string; key: string; name?: string }>;\n _links?: { next?: string };\n };\n for (const s of res.results ?? []) {\n all.push({ id: s.id, key: s.key, name: s.name ?? s.key });\n }\n const next = res._links?.next;\n if (!next) break;\n // v2 returns relative paths beginning with \"/wiki/...\"\n cursor = next.startsWith(\"/\") ? next : `/${next}`;\n }\n return all;\n },\n\n async listRootPages(spaceId: string): Promise<ConfluenceRootPage[]> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?depth=root&limit=50`;\n const res = (await call(\"GET\", url)) as {\n results?: Array<{ id: string; title: string }>;\n };\n return (res.results ?? []).map((p) => ({ id: p.id, title: p.title }));\n },\n\n async findPageByTitle(\n spaceId: string,\n title: string\n ): Promise<ConfluencePage | null> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?title=${encodeURIComponent(title)}&body-format=storage&limit=1`;\n const res = (await call(\"GET\", url)) as {\n results?: PageApiResponse[];\n };\n const match = res.results?.find((p) => p.title === title);\n return match ? toPage(match) : null;\n },\n\n async createPage(input: CreatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"POST\", \"/wiki/api/v2/pages\", {\n spaceId: input.spaceId,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n\n async updatePage(input: UpdatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"PUT\", `/wiki/api/v2/pages/${input.id}`, {\n id: input.id,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n version: {\n number: input.version + 1,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport type Provider = \"claude\" | \"gemini\" | \"openai\" | \"ollama\";\n\nexport interface ConfluenceConfig {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey: string;\n parentPageId?: string;\n}\n\nexport interface MasonConfig {\n provider: Provider;\n apiKey?: string;\n model?: string;\n ollamaHost?: string;\n confluence?: ConfluenceConfig;\n}\n\nfunction configDir(): string {\n return path.join(os.homedir(), \".mason\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nconst DEFAULT_MODELS: Record<Provider, string> = {\n claude: \"claude-sonnet-4-20250514\",\n gemini: \"gemini-2.5-flash\",\n openai: \"gpt-4o\",\n ollama: \"llama3\",\n};\n\nexport async function loadConfig(): Promise<MasonConfig | null> {\n try {\n const raw = await fs.readFile(configFile(), \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: MasonConfig): Promise<void> {\n await fs.mkdir(configDir(), { recursive: true });\n await fs.writeFile(configFile(), JSON.stringify(config, null, 2), \"utf-8\");\n}\n\nexport function getDefaultModel(provider: Provider): string {\n return DEFAULT_MODELS[provider];\n}\n\nexport function validateProvider(value: string): Provider {\n const valid: Provider[] = [\"claude\", \"gemini\", \"openai\", \"ollama\"];\n if (!valid.includes(value as Provider)) {\n throw new Error(\n `Invalid provider \"${value}\". Must be one of: ${valid.join(\", \")}`\n );\n }\n return value as Provider;\n}\n\nexport async function detectCLI(\n provider: Provider\n): Promise<{ available: boolean; version?: string }> {\n const cliName = provider === \"claude\" ? \"claude\"\n : provider === \"gemini\" ? \"gemini\"\n : provider === \"ollama\" ? \"ollama\"\n : null;\n\n if (!cliName) return { available: false };\n\n try {\n const { stdout } = await exec(cliName, [\"--version\"]);\n return { available: true, version: stdout.trim() };\n } catch {\n return { available: false };\n }\n}\n\nexport function needsApiKey(provider: Provider): boolean {\n return provider === \"openai\";\n}\n\nexport async function saveConfluenceConfig(\n confluence: ConfluenceConfig\n): Promise<void> {\n const existing = (await loadConfig()) ?? { provider: \"claude\" as Provider };\n await saveConfig({ ...existing, confluence });\n}\n\nexport async function loadConfluenceConfig(): Promise<ConfluenceConfig | null> {\n const config = await loadConfig();\n return config?.confluence ?? null;\n}\n","export function normalizeAtlassianBaseUrl(input: string): string {\n const trimmed = input.trim().replace(/\\/+$/, \"\");\n if (!trimmed) throw new Error(\"Confluence baseUrl is required.\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n if (trimmed.includes(\".\")) return `https://${trimmed}`;\n // Bare subdomain — assume Atlassian Cloud\n return `https://${trimmed}.atlassian.net`;\n}\n","import type { FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\n\n// Mason fully owns each page body and overwrites it on every sync. Confluence\n// strips HTML comments and re-serializes storage XHTML, so in-page region\n// markers can't survive a round-trip — no-op detection happens via a content\n// hash in the local sync state instead (see sync.ts / diff.ts).\n\nfunction escape(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction infoPanel(text: string): string {\n return (\n `<ac:structured-macro ac:name=\"info\"><ac:rich-text-body>` +\n `<p>${escape(text)}</p>` +\n `</ac:rich-text-body></ac:structured-macro>`\n );\n}\n\nexport function featurePageTitle(prefix: string, name: string): string {\n return `${prefix}${name}`;\n}\n\nexport interface RenderedFeaturePage {\n body: string;\n title: string;\n}\n\nexport interface RenderFeaturePageOptions {\n name: string;\n productDescription: string;\n flowDescriptions: Array<{ name: string; description: string }>;\n indexPageTitle: string;\n}\n\nexport function renderFeaturePage(\n options: RenderFeaturePageOptions\n): RenderedFeaturePage {\n const overviewBody =\n `<h2>What it does</h2>` + `<p>${escape(options.productDescription)}</p>`;\n\n // Only render \"How it fits in\" when there are flows — an empty section with a\n // \"nothing here\" placeholder reads as unfinished.\n const flowsBody = options.flowDescriptions.length\n ? `<h2>How it fits in</h2><ul>` +\n options.flowDescriptions\n .map(\n (f) =>\n `<li><strong>${escape(f.name)}</strong> — ${escape(f.description)}</li>`\n )\n .join(\"\") +\n `</ul>`\n : \"\";\n\n // Native Confluence page link, resolved by title.\n const navBody =\n `<p><ac:link><ri:page ri:content-title=\"${escape(options.indexPageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[Back to ${options.indexPageTitle}]]></ac:plain-text-link-body>` +\n `</ac:link></p>`;\n\n // Provenance note as a footer, not wedged between the content sections.\n const footer = infoPanel(\n `Generated from code by Mason. This page is overwritten on each sync — ` +\n `edit the code, not the page.`\n );\n\n const body = overviewBody + flowsBody + navBody + footer;\n\n return {\n title: options.name,\n body,\n };\n}\n\nexport interface RenderIndexPageOptions {\n featureTitles: string[];\n featurePrefix: string;\n}\n\nexport function renderIndexPage(options: RenderIndexPageOptions): string {\n if (options.featureTitles.length === 0) {\n return infoPanel(\"No features in the snapshot yet.\");\n }\n\n const list =\n `<h2>Features</h2><ul>` +\n options.featureTitles\n .map((name) => {\n const pageTitle = featurePageTitle(options.featurePrefix, name);\n return (\n `<li><ac:link><ri:page ri:content-title=\"${escape(pageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[${name}]]></ac:plain-text-link-body>` +\n `</ac:link></li>`\n );\n })\n .join(\"\") +\n `</ul>`;\n\n const banner = infoPanel(\n `Generated from code by Mason. Maintained automatically — edit the code, not this page.`\n );\n\n return banner + list;\n}\n\nexport interface DiffSection {\n syncedAt: string;\n addedFeatures: string[];\n removedFeatures: string[];\n changedFeatures: string[];\n addedFlows: string[];\n removedFlows: string[];\n}\n\nexport function renderChangelogSection(section: DiffSection): string {\n const segments: string[] = [];\n if (section.addedFeatures.length) {\n segments.push(\n `<p><strong>Added features:</strong> ${section.addedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFeatures.length) {\n segments.push(\n `<p><strong>Removed features:</strong> ${section.removedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.changedFeatures.length) {\n segments.push(\n `<p><strong>Updated features:</strong> ${section.changedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.addedFlows.length) {\n segments.push(\n `<p><strong>Added flows:</strong> ${section.addedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFlows.length) {\n segments.push(\n `<p><strong>Removed flows:</strong> ${section.removedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (segments.length === 0) {\n segments.push(`<p><em>No meaningful changes detected.</em></p>`);\n }\n\n return (\n `<h3>${escape(section.syncedAt)}</h3>` + segments.join(\"\")\n );\n}\n\nexport function renderChangelogPage(sections: string[]): string {\n if (sections.length === 0) {\n return `<p><em>No sync has run yet.</em></p>`;\n }\n // Newest first\n return sections.join(\"\\n<hr/>\\n\");\n}\n\nexport type FeatureMap = Record<string, FeatureEntry>;\nexport type FlowMap = Record<string, FlowEntry>;\n\nexport function flowsForFeature(\n featureFiles: string[],\n flows: FlowMap\n): Array<{ name: string; description: string }> {\n const fileSet = new Set(featureFiles);\n const result: Array<{ name: string; description: string }> = [];\n for (const [name, flow] of Object.entries(flows)) {\n if (flow.chain.some((file) => fileSet.has(file))) {\n result.push({ name, description: flow.description });\n }\n }\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { DiffSection } from \"./renderer.js\";\n\nexport interface RewriteCacheEntry {\n /** sha256 of the engineering (source) description this prose was derived from */\n sourceHash: string;\n /** the cached product-language prose */\n product: string;\n /** true when produced by the no-LLM fallback, not the model — re-attempted next run */\n fallback?: boolean;\n}\n\nexport interface RewriteCache {\n features: Record<string, RewriteCacheEntry>;\n flows: Record<string, RewriteCacheEntry>;\n}\n\nexport interface SyncState {\n version: 2;\n syncedAt: string;\n pageIds: {\n index?: string;\n changelog?: string;\n features: Record<string, string>;\n };\n lastSnapshot: {\n features: Record<string, { description: string }>;\n flows: Record<string, { description: string }>;\n };\n changelogSections: string[];\n /** product-language prose cache, keyed by feature/flow name */\n rewriteCache: RewriteCache;\n /**\n * Hash of the body Mason last rendered for each page, keyed by page title.\n * Used to skip re-publishing unchanged pages — we compare our render hash to\n * this, never to Confluence's re-serialized body. Optional for forward\n * compatibility with state written before this field existed.\n */\n pageHashes?: Record<string, string>;\n}\n\n/** Stable content hash of a source description, for cache invalidation. */\nexport function hashDescription(description: string): string {\n return createHash(\"sha256\").update(description, \"utf8\").digest(\"hex\");\n}\n\nfunction syncStateDir(rootDir: string): string {\n return path.join(rootDir, \".mason\");\n}\n\nfunction syncStatePath(rootDir: string): string {\n return path.join(syncStateDir(rootDir), \"confluence-sync.json\");\n}\n\nexport async function loadSyncState(rootDir: string): Promise<SyncState | null> {\n try {\n const raw = await fs.readFile(syncStatePath(rootDir), \"utf-8\");\n const parsed = JSON.parse(raw);\n // Only v2 state is usable. Older state (v1) is treated as absent: the next\n // export re-finds pages by title and rebuilds the rewrite cache from scratch.\n if (parsed.version !== 2) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nexport async function saveSyncState(\n rootDir: string,\n state: SyncState\n): Promise<void> {\n await fs.mkdir(syncStateDir(rootDir), { recursive: true });\n await fs.writeFile(\n syncStatePath(rootDir),\n JSON.stringify(state, null, 2),\n \"utf-8\"\n );\n}\n\nexport function computeDiff(\n previous: SyncState | null,\n current: Snapshot,\n syncedAt: string\n): DiffSection {\n const prevFeatures = previous?.lastSnapshot.features ?? {};\n const prevFlows = previous?.lastSnapshot.flows ?? {};\n\n const currentFeatureNames = Object.keys(current.features);\n const prevFeatureNames = Object.keys(prevFeatures);\n\n const addedFeatures = currentFeatureNames.filter(\n (n) => !(n in prevFeatures)\n );\n const removedFeatures = prevFeatureNames.filter(\n (n) => !(n in current.features)\n );\n const changedFeatures = currentFeatureNames.filter(\n (n) =>\n n in prevFeatures &&\n prevFeatures[n].description !== current.features[n].description\n );\n\n const currentFlowNames = Object.keys(current.flows);\n const prevFlowNames = Object.keys(prevFlows);\n const addedFlows = currentFlowNames.filter((n) => !(n in prevFlows));\n const removedFlows = prevFlowNames.filter((n) => !(n in current.flows));\n\n return {\n syncedAt,\n addedFeatures,\n removedFeatures,\n changedFeatures,\n addedFlows,\n removedFlows,\n };\n}\n\nexport function isMeaningfulDiff(diff: DiffSection): boolean {\n return (\n diff.addedFeatures.length > 0 ||\n diff.removedFeatures.length > 0 ||\n diff.changedFeatures.length > 0 ||\n diff.addedFlows.length > 0 ||\n diff.removedFlows.length > 0\n );\n}\n\nexport function snapshotMinimal(snapshot: Snapshot): SyncState[\"lastSnapshot\"] {\n const features: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.features)) {\n features[k] = { description: v.description };\n }\n const flows: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.flows)) {\n flows[k] = { description: v.description };\n }\n return { features, flows };\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { MasonConfig } from \"./config.js\";\nimport { getDefaultModel } from \"./config.js\";\n\nconst exec = promisify(execFile);\n\nconst CLAUDE_MD_SYSTEM_PROMPT = `You are Mason, a context engineering tool. You've been given a comprehensive analysis of a codebase including:\n- Git history stats (commit patterns, frequently changed files, stale directories)\n- Project structure (directory layout, file counts by type)\n- Curated code samples (key architectural files with previews)\n- Test-to-source file mapping\n\nYour job: write a COMPLETE CLAUDE.md file from scratch based ONLY on the analysis data provided below. Do NOT read any existing files in the project. Do NOT reference or preserve any existing CLAUDE.md. Generate the entire document fresh.\n\nCRITICAL: Output ONLY the raw markdown content. No preamble, no summary, no \"Here's the CLAUDE.md:\", no explanation, no questions, no commentary. Start directly with \"# CLAUDE.md\" and end with the last line of content. Your entire response will be written directly to a file.\n\nThe CLAUDE.md should include:\n- Project overview (what it is, tech stack, architecture)\n- Module/package structure and boundaries\n- Code conventions and patterns you observe in the samples\n- Testing conventions and coverage\n- Build and development commands\n- Important files and hot spots\n- Any warnings or gotchas\n\nBe specific and actionable. Reference actual file paths. Don't be generic — every rule should be grounded in what you see in the data.`;\n\nexport type CallResult =\n | { type: \"response\"; text: string }\n | { type: \"prompt\"; text: string };\n\nexport async function callLLM(\n config: MasonConfig,\n userMessage: string,\n systemPrompt?: string\n): Promise<CallResult> {\n const model = config.model ?? getDefaultModel(config.provider);\n const system = systemPrompt ?? CLAUDE_MD_SYSTEM_PROMPT;\n\n switch (config.provider) {\n case \"claude\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callClaudeAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callClaudeCLI(system, userMessage),\n };\n\n case \"ollama\":\n return {\n type: \"response\",\n text: await callOllamaCLI(\n config.ollamaHost ?? \"http://localhost:11434\",\n model,\n system,\n userMessage,\n ),\n };\n\n case \"gemini\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callGeminiAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callGeminiCLI(system, userMessage),\n };\n\n case \"openai\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callOpenAIAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"prompt\",\n text: formatPromptForCopy(system, userMessage),\n };\n }\n}\n\nfunction formatPromptForCopy(system: string, userMessage: string): string {\n return `${system}\\n\\n---\\n\\n${userMessage}`;\n}\n\n// === CLI-based providers (no API key) ===\n\nasync function callViaTempFile(\n command: string,\n args: (promptPath: string) => string[],\n system: string,\n userMessage: string\n): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n const os = await import(\"node:os\");\n const path = await import(\"node:path\");\n\n const prompt = `${system}\\n\\n${userMessage}`;\n const tmpFile = path.join(os.tmpdir(), `mason-prompt-${Date.now()}.txt`);\n\n try {\n await fs.writeFile(tmpFile, prompt, \"utf-8\");\n const { stdout } = await exec(command, args(tmpFile), {\n maxBuffer: 10_000_000,\n timeout: 300_000,\n });\n return stdout.trim();\n } finally {\n await fs.unlink(tmpFile).catch(() => {});\n }\n}\n\nfunction spawnWithStdin(\n command: string,\n args: string[],\n input: string\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n timeout: 300_000,\n });\n\n // ora puts stdin into raw mode, which means Ctrl+C is emitted as\n // process.emit(\"SIGINT\") rather than a real signal to the process\n // group. Forward it to the child so it can terminate.\n const onSigint = () => proc.kill(\"SIGINT\");\n process.on(\"SIGINT\", onSigint);\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code: number | null) => {\n process.off(\"SIGINT\", onSigint);\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(new Error(`${command} exited with code ${code}: ${stderr}`));\n }\n });\n\n proc.on(\"error\", (err) => {\n process.off(\"SIGINT\", onSigint);\n reject(err);\n });\n\n proc.stdin.write(input);\n proc.stdin.end();\n });\n}\n\nasync function callClaudeCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n return spawnWithStdin(\"claude\", [\"-p\", \"--system-prompt\", system], userMessage);\n}\n\nasync function callGeminiCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n const prompt = `<system>\\n${system}\\n</system>\\n\\n${userMessage}`;\n return spawnWithStdin(\"gemini\", [\"-p\", \"\"], prompt);\n}\n\nasync function callOllamaCLI(\n host: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const response = await fetch(`${host}/api/chat`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n stream: false,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n }),\n });\n\n const result = (await response.json()) as {\n message?: { content?: string };\n };\n return result.message?.content ?? \"\";\n}\n\n// === API-based providers ===\n\nasync function callClaudeAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: Anthropic } = await import(\"@anthropic-ai/sdk\");\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model,\n max_tokens: 8192,\n system,\n messages: [{ role: \"user\", content: userMessage }],\n });\n\n const textBlock = response.content.find((b) => b.type === \"text\");\n return textBlock?.text ?? \"\";\n}\n\nasync function callGeminiAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({\n apiKey,\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n\nasync function callOpenAIAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({ apiKey });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n","import { callLLM } from \"../llm/providers.js\";\nimport type { MasonConfig } from \"../llm/config.js\";\nimport type {\n FeatureEntry,\n FlowEntry,\n Snapshot,\n} from \"../snapshot/snapshot.js\";\nimport {\n hashDescription,\n type RewriteCache,\n type RewriteCacheEntry,\n} from \"./diff.js\";\n\nconst PM_REWRITE_SYSTEM_PROMPT = `You are Mason, rewriting an engineering-flavoured concept map into product-readable language for a company wiki.\n\nYou will receive a JSON object with two maps:\n- \"features\": each entry has a description and a list of source file paths.\n- \"flows\": each entry has a description and an ordered chain of file paths.\n\nYour job: rewrite EACH description so a Product Manager, designer, or non-engineering stakeholder can understand what the system does — without seeing any code. Treat the file paths as hints, not content. Do NOT include them in your output.\n\nHard rules:\n- NEVER mention file names, directory names, file extensions, class names, function names, repository names, framework names, or libraries.\n- NEVER use words like \"module\", \"service\", \"handler\", \"controller\", \"ViewModel\", \"repository\", \"endpoint\", \"API\", \"schema\", \"interface\", \"class\".\n- Use plain English. Focus on what users or the business can do, what data moves, what decisions get made, and why it matters.\n- 1–3 sentences per description. Concrete. No filler.\n- Preserve the original keys exactly; only the description values change.\n\nOutput ONLY raw JSON with the same shape as the input — same keys, rewritten descriptions. No markdown, no code fences, no preamble.`;\n\ntype Rewritten = {\n features: Record<string, string>;\n flows: Record<string, string>;\n};\n\ninterface RewriteInput {\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nfunction buildPrompt(input: RewriteInput): string {\n return `Rewrite the descriptions below for a product audience. Return ONLY a JSON object of the form {\"features\": {\"name\": \"rewritten description\", ...}, \"flows\": {...}}.\\n\\n${JSON.stringify(input, null, 2)}`;\n}\n\nfunction parseRewriteResponse(raw: string): Rewritten {\n let cleaned = raw.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n try {\n const parsed = JSON.parse(cleaned);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (match) {\n try {\n const parsed = JSON.parse(match[0]);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n return { features: {}, flows: {} };\n }\n }\n return { features: {}, flows: {} };\n }\n}\n\nexport interface RewriteResult {\n features: Record<string, string>;\n flows: Record<string, string>;\n /** Updated prose cache to persist into the sync state. */\n cache: RewriteCache;\n}\n\nexport interface RewriteContext {\n /** Prose cache from the previous sync; used to skip unchanged entries. */\n previousCache?: RewriteCache;\n /** LLM caller; injectable for tests. Defaults to the configured provider. */\n llm?: typeof callLLM;\n}\n\n/** Pick a subset of a record by key. */\nfunction pick<T>(source: Record<string, T>, keys: string[]): Record<string, T> {\n const out: Record<string, T> = {};\n for (const k of keys) out[k] = source[k];\n return out;\n}\n\n/**\n * Rewrite engineering descriptions into product-readable prose, incrementally.\n *\n * Entries whose source description is unchanged since the last sync (matched by\n * content hash) reuse their cached prose verbatim — no LLM call. Only new or\n * changed entries are sent to the model, batched into a single request. When\n * nothing changed, the LLM is not invoked at all.\n */\nexport async function rewriteForProduct(\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext = {}\n): Promise<RewriteResult> {\n const featureHashes = hashEntries(snapshot.features);\n const flowHashes = hashEntries(snapshot.flows);\n\n const missFeatures = missingNames(\n snapshot.features,\n featureHashes,\n ctx.previousCache?.features\n );\n const missFlows = missingNames(\n snapshot.flows,\n flowHashes,\n ctx.previousCache?.flows\n );\n\n let parsed: Rewritten = { features: {}, flows: {} };\n if (missFeatures.length > 0 || missFlows.length > 0) {\n const input: RewriteInput = {\n features: pick(snapshot.features, missFeatures),\n flows: pick(snapshot.flows, missFlows),\n };\n const prompt = buildPrompt(input);\n const llm = ctx.llm ?? callLLM;\n const result = await llm(config, prompt, PM_REWRITE_SYSTEM_PROMPT);\n const text =\n typeof result === \"string\"\n ? result\n : result.type === \"response\"\n ? result.text\n : \"\";\n // Empty text means no API/CLI is available — leave `parsed` empty so every\n // miss falls back to its engineering description (cached as fallback).\n if (text) parsed = parseRewriteResponse(text);\n }\n\n const features = resolve(\n snapshot.features,\n featureHashes,\n parsed.features,\n ctx.previousCache?.features\n );\n const flows = resolve(\n snapshot.flows,\n flowHashes,\n parsed.flows,\n ctx.previousCache?.flows\n );\n\n return {\n features: features.descriptions,\n flows: flows.descriptions,\n cache: { features: features.cache, flows: flows.cache },\n };\n}\n\nfunction hashEntries(\n entries: Record<string, { description: string }>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, entry] of Object.entries(entries)) {\n out[name] = hashDescription(entry.description);\n }\n return out;\n}\n\n/** A cache entry is a hit only if the source hash matches and it isn't a fallback. */\nfunction isHit(\n prev: RewriteCacheEntry | undefined,\n hash: string\n): prev is RewriteCacheEntry {\n return !!prev && prev.sourceHash === hash && !prev.fallback;\n}\n\nfunction missingNames(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): string[] {\n return Object.keys(entries).filter(\n (name) => !isHit(prevCache?.[name], hashes[name])\n );\n}\n\n/**\n * Build the final prose map + next cache for one collection (features or flows):\n * reuse cached prose on a hit, take fresh model prose on a miss, or fall back to\n * the engineering description (marked `fallback`) when the model omitted it.\n */\nfunction resolve(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n rewritten: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): { descriptions: Record<string, string>; cache: Record<string, RewriteCacheEntry> } {\n const descriptions: Record<string, string> = {};\n const cache: Record<string, RewriteCacheEntry> = {};\n\n for (const [name, entry] of Object.entries(entries)) {\n const hash = hashes[name];\n const prev = prevCache?.[name];\n\n if (isHit(prev, hash)) {\n descriptions[name] = prev.product;\n cache[name] = { sourceHash: hash, product: prev.product };\n continue;\n }\n\n const fresh = rewritten[name];\n if (typeof fresh === \"string\" && fresh.trim().length > 0) {\n descriptions[name] = fresh;\n cache[name] = { sourceHash: hash, product: fresh };\n } else {\n // No usable model output — keep the engineering description and mark it a\n // fallback so a later successful run re-attempts it.\n descriptions[name] = entry.description;\n cache[name] = { sourceHash: hash, product: entry.description, fallback: true };\n }\n }\n\n return { descriptions, cache };\n}\n","import { loadSnapshot } from \"../snapshot/snapshot.js\";\nimport type { MasonConfig, ConfluenceConfig } from \"../llm/config.js\";\nimport { createConfluenceClient, type ConfluenceClient } from \"./client.js\";\nimport {\n renderFeaturePage,\n renderIndexPage,\n renderChangelogPage,\n renderChangelogSection,\n flowsForFeature,\n featurePageTitle,\n} from \"./renderer.js\";\nimport {\n computeDiff,\n isMeaningfulDiff,\n loadSyncState,\n saveSyncState,\n snapshotMinimal,\n hashDescription,\n type SyncState,\n} from \"./diff.js\";\nimport {\n rewriteForProduct,\n type RewriteResult,\n type RewriteContext,\n} from \"./rewrite.js\";\nimport type { FeatureEntry, Snapshot } from \"../snapshot/snapshot.js\";\n\nexport interface SyncOptions {\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n}\n\nexport interface SyncSummary {\n created: string[];\n updated: string[];\n unchanged: string[];\n indexPageId: string;\n changelogPageId: string;\n hadChanges: boolean;\n}\n\nexport interface SyncDeps {\n client: ConfluenceClient;\n rewrite: (\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext\n ) => Promise<RewriteResult>;\n}\n\nconst DEFAULT_INDEX_TITLE = \"Mason — System Map\";\nconst DEFAULT_CHANGELOG_TITLE = \"Mason — Changelog\";\nconst DEFAULT_FEATURE_PREFIX = \"Feature: \";\n\nexport async function exportToConfluence(\n rootDir: string,\n config: MasonConfig,\n options: SyncOptions = {},\n deps?: Partial<SyncDeps>\n): Promise<SyncSummary> {\n const confluence = config.confluence;\n if (!confluence) {\n throw new Error(\n \"No Confluence credentials configured. Ask your assistant to call mason_set_confluence first.\"\n );\n }\n\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n throw new Error(\n \"No snapshot found. Build the concept map first (ask your assistant to run mason_init and follow the playbook).\"\n );\n }\n\n const client = deps?.client ?? createConfluenceClient(confluence);\n const rewrite = deps?.rewrite ?? rewriteForProduct;\n\n // Only user-facing capabilities are published to the wiki. Infrastructure\n // features (DI wiring, config, logging, provider plumbing) stay in the AI\n // concept map but never become PM-facing pages. Filter once here; everything\n // downstream — rewrite, index, feature pages, changelog diff, persisted\n // state — operates on this published subset. Missing type defaults to\n // \"capability\" (see normalizeFeatureType), so older snapshots publish as before.\n const publishedFeatures: Record<string, FeatureEntry> = {};\n for (const [name, entry] of Object.entries(snapshot.features)) {\n if (entry.type !== \"infrastructure\") publishedFeatures[name] = entry;\n }\n const publishSnapshot: Snapshot = { ...snapshot, features: publishedFeatures };\n\n const indexTitle = options.indexPageTitle ?? DEFAULT_INDEX_TITLE;\n const changelogTitle = options.changelogPageTitle ?? DEFAULT_CHANGELOG_TITLE;\n const featurePrefix = options.featurePagePrefix ?? DEFAULT_FEATURE_PREFIX;\n\n const spaceId = await client.resolveSpaceId(confluence.spaceKey);\n // Wall-clock time is used ONLY for the append-only changelog heading. Page\n // bodies carry no timestamp/hash, so a page is re-published only when its own\n // content (description/flows) changes — not on every unrelated commit.\n const syncedAt = new Date().toISOString();\n const previousState = await loadSyncState(rootDir);\n const previousHashes = previousState?.pageHashes ?? {};\n const nextHashes: Record<string, string> = {};\n\n const productLanguage = await rewrite(publishSnapshot, config, {\n previousCache: previousState?.rewriteCache,\n });\n\n // 1. Upsert index page (so feature pages can hang under it)\n const indexBody = renderIndexPage({\n featureTitles: Object.keys(publishSnapshot.features),\n featurePrefix,\n });\n\n const indexPage = await upsertPage({\n client,\n spaceId,\n title: indexTitle,\n parentId: confluence.parentPageId,\n renderedBody: indexBody,\n previousHash: previousHashes[indexTitle],\n });\n nextHashes[indexTitle] = indexPage.hash;\n\n // 2. Upsert each feature page under the index\n const created: string[] = [];\n const updated: string[] = [];\n const unchanged: string[] = [];\n const featurePageIds: Record<string, string> = {};\n\n for (const [name, entry] of Object.entries(publishSnapshot.features)) {\n const title = featurePageTitle(featurePrefix, name);\n const productDescription =\n productLanguage.features[name] ?? entry.description;\n const relatedFlows = flowsForFeature(entry.files, publishSnapshot.flows).map(\n (f) => ({\n name: f.name,\n description: productLanguage.flows[f.name] ?? f.description,\n })\n );\n\n const rendered = renderFeaturePage({\n name,\n productDescription,\n flowDescriptions: relatedFlows,\n indexPageTitle: indexTitle,\n });\n\n const result = await upsertPage({\n client,\n spaceId,\n title,\n parentId: indexPage.id,\n renderedBody: rendered.body,\n previousHash: previousHashes[title],\n });\n nextHashes[title] = result.hash;\n\n featurePageIds[name] = result.id;\n if (result.outcome === \"created\") created.push(title);\n else if (result.outcome === \"updated\") updated.push(title);\n else unchanged.push(title);\n }\n\n // 3. Diff + changelog page\n const diff = computeDiff(previousState, publishSnapshot, syncedAt);\n const hadChanges = previousState === null || isMeaningfulDiff(diff);\n\n const previousSections = previousState?.changelogSections ?? [];\n let newSections = previousSections;\n if (hadChanges) {\n const section = renderChangelogSection(diff);\n newSections = [section, ...previousSections].slice(0, 50);\n }\n\n const changelogBody = renderChangelogPage(newSections);\n const changelogPage = await upsertPage({\n client,\n spaceId,\n title: changelogTitle,\n parentId: indexPage.id,\n renderedBody: changelogBody,\n previousHash: previousHashes[changelogTitle],\n });\n nextHashes[changelogTitle] = changelogPage.hash;\n\n // 4. Persist sync state\n const nextState: SyncState = {\n version: 2,\n syncedAt,\n pageIds: {\n index: indexPage.id,\n changelog: changelogPage.id,\n features: featurePageIds,\n },\n lastSnapshot: snapshotMinimal(publishSnapshot),\n changelogSections: newSections,\n rewriteCache: productLanguage.cache,\n pageHashes: nextHashes,\n };\n await saveSyncState(rootDir, nextState);\n\n return {\n created,\n updated,\n unchanged,\n indexPageId: indexPage.id,\n changelogPageId: changelogPage.id,\n hadChanges,\n };\n}\n\ninterface UpsertArgs {\n client: ConfluenceClient;\n spaceId: string;\n title: string;\n parentId?: string;\n renderedBody: string;\n /** Hash of the body we published for this page last sync, if any. */\n previousHash?: string;\n}\n\ninterface UpsertResult {\n id: string;\n outcome: \"created\" | \"updated\" | \"unchanged\";\n /** Hash of the body published this sync — persist for next-run comparison. */\n hash: string;\n}\n\nasync function upsertPage(args: UpsertArgs): Promise<UpsertResult> {\n const hash = hashDescription(args.renderedBody);\n const existing = await args.client.findPageByTitle(args.spaceId, args.title);\n\n if (!existing) {\n const page = await args.client.createPage({\n spaceId: args.spaceId,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n });\n return { id: page.id, outcome: \"created\", hash };\n }\n\n // Confluence re-serializes stored bodies (strips comments, re-encodes\n // entities, injects macro ids), so we can't compare against existing.body.\n // Compare our render hash to the hash we stored last sync instead. When it\n // matches, the page is already current — skip the write entirely.\n if (args.previousHash === hash) {\n return { id: existing.id, outcome: \"unchanged\", hash };\n }\n\n // Mason owns the whole page body: overwrite it wholesale.\n const updated = await args.client.updatePage({\n id: existing.id,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n version: existing.version,\n });\n return { id: updated.id, outcome: \"updated\", hash };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { inactiveSetupMessage } from \"../setup/launcher.js\";\nimport { attributionSchema } from \"../decisions/provenance.js\";\nimport { advisoryReviewRequest } from \"../audit/advisory-review.js\";\nimport { decisionTitleSchema, decisionBodySchema, BODY_RECOMMENDED_CHARS, BODY_MAX_CHARS, TITLE_MAX_CHARS } from \"../decisions/decisions.js\";\nimport {\n analyzeProject,\n checkDrift,\n exportToConfluenceTool,\n fullAnalysis,\n generateSnapshotBatch,\n getCodeSamples,\n getContext,\n getImpact,\n getSnapshot,\n saveDecision,\n reviewDecision,\n saveVerification,\n verifySnapshot,\n masonCompleteInit,\n masonInit,\n masonRepair,\n masonReviewAdvisory,\n masonAutomation,\n masonSetConfluence,\n reduceSnapshot,\n saveSnapshotData,\n saveSnapshotPartial,\n} from \"./tools.js\";\n\ndeclare const PKG_VERSION: string;\n\nexport function createMcpServer(): McpServer {\n const setupNotice = inactiveSetupMessage();\n const server = new McpServer(\n {\n name: \"mason\",\n version: PKG_VERSION,\n },\n {\n instructions: (setupNotice ? setupNotice + \"\\n\\n\" : \"\") +\n \"Mason retrieves recorded decisions, file impact, and optional feature/flow maps. Use get_context with the task and known files, and get_impact before editing. Save learned rationale and constraints with save_decision; review and commit the local records through the project workflow. These tools work without initialization or a concept map. Consult trust and diagnostics: changed or unknown freshness needs source inspection, stale or unknown map verification needs a fresh review, recorded failed verdicts need correction, and proposals are suggestions and legacy records are unreviewed. Accepted decisions are recorded team constraints, still subject to freshness checks. Use review_decision to prepare code evidence and record only authorized acceptance, reaffirmation, or retirement. Never invent a reviewer or treat these recorded identities as authenticated approval. mason_init returns documentation audit and committed-diff review findings with a quickstart guide. Use mode: \\\"map\\\" only when a full architecture map is requested. A missing map is not a setup failure; use decisions and source evidence. get_snapshot provides architecture navigation when a map is available. The mason-audit and mason-review CLIs also work without setup.\",\n }\n );\n\n server.tool(\n \"mason_init\",\n \"Inspect this project now: returns documentation audit findings, committed-diff review findings, decision/map status, and a quickstart playbook. Quickstart and map modes are read-only and deterministic. Explicit mode: setup configures MCP, instructions and lifecycle hooks to use mason on PATH while retaining original audit evidence; use it only when the user requests setup. Optional host selects codex or claude. Optional base selects the review comparison; evidence imports CI manifests with check outcomes, commit freshness, and links to changed files and accepted decisions. mode: map returns the full Map-Reduce build workflow. Repeat calls refresh findings even after setup.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n mode: z.enum([\"quickstart\", \"map\", \"setup\"]).optional().default(\"quickstart\")\n .describe(\"Quickstart inspects without edits; map requests an architecture build; setup installs the shared onboarding flow.\"),\n host: z.enum([\"codex\", \"claude\"]).optional().describe(\"Assistant to configure in setup mode; inferred only when unambiguous.\"),\n base: z.string().optional().describe(\"Git ref for committed-diff review. Defaults to the first available main branch ref.\"),\n evidence: z.array(z.string()).max(10).optional().describe(\"Repository-local CI evidence manifests to include in the review. Imports Vitest JSON, SARIF, and native-validator mason-check-json results without executing check commands.\"),\n },\n async ({ dir, mode, host, base, evidence }) => {\n const result = await masonInit(dir, { mode, host, base, evidence });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_automation\",\n \"Inspect installed automation and observed host events, or resume/check retained documentation repair evidence across sessions. status is read-only; check saves local baselines and verification reports without editing source or approving advisories. Returns concise results with a full report path. Works without a map.\",\n {\n dir: z.string().describe(\"Absolute path to the project directory\"),\n action: z.enum([\"status\", \"check\"]).describe(\"Inspect configuration and receipts, or capture/resume and verify original audit evidence.\"),\n },\n async ({ dir, action }) => ({ content: [{ type: \"text\", text: await masonAutomation(dir, action) }] })\n );\n\n server.tool(\n \"mason_repair\",\n \"Track documentation repairs against original audit evidence. prepare saves a local baseline and returns a scoped work order; verify reads that baseline and reports resolved, unresolved, review-required, unverified, and new findings. Suppressed advisories remain unresolved. Does not edit documentation or approve decisions. No map required.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n action: z.enum([\"prepare\", \"verify\"]),\n baselinePath: z.string().optional().describe(\"Original baseline path returned by prepare; required for verify.\"),\n checks: z.array(z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]))\n .min(1).optional().describe(\"Optional audit check subset for prepare. Verification always uses the original checks.\"),\n },\n async ({ dir, action, baselinePath, checks }) => {\n const result = await masonRepair(dir, { action, baselinePath, checks });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_advisory\",\n \"Prepare an assessment of an original repair advisory and its exact repository scope, then record authorized addressed, inapplicable or deferred outcomes with reviewToken, reviewer and note. Relevant changes reopen reviews; unrelated commits preserve them. Records belong in Git. Decision findings route to review_decision; this tool never approves decisions. Recorded identities are assertions, not authenticated approvals.\",\n { dir: z.string().describe(\"Absolute path to the project root\"), ...advisoryReviewRequest.shape },\n async ({ dir, ...request }) => ({ content: [{ type: \"text\", text: await masonReviewAdvisory(dir, request) }] })\n );\n\n server.tool(\n \"mason_complete_init\",\n \"Record assistant instruction setup locally in ignored .mason/local/project.json, with feature settings in shared .mason/config.json. Other tools work without this marker. Repeated calls preserve the original setup time and existing settings; pass confluenceConfigured only to change that setting.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n confluenceConfigured: z\n .boolean()\n .optional()\n .describe(\"Set the Confluence setup status; omit to preserve the existing value\"),\n },\n async ({ dir, confluenceConfigured }) => {\n const result = await masonCompleteInit(dir, { confluenceConfigured });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_set_confluence\",\n \"Configure Confluence credentials. Two-step flow: (1) call without `spaceKey` to validate the credentials and receive a list of available spaces — relay them to the user. (2) call again with the same `baseUrl`/`email`/`apiToken` plus the chosen `spaceKey` to persist. Credentials are stored in `~/.mason/config.json`. Warn the user that the API token will be visible in chat history before they paste it.\",\n {\n baseUrl: z\n .string()\n .describe(\"Confluence base URL. Accepts `acme`, `acme.atlassian.net`, or `https://acme.atlassian.net` (normalized automatically).\"),\n email: z.string().describe(\"User's Atlassian account email\"),\n apiToken: z\n .string()\n .describe(\"API token from id.atlassian.com/manage-profile/security/api-tokens\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Confluence space key. Omit on the first call to list available spaces.\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Optional parent page ID under which Mason's index page is created\"),\n },\n async ({ baseUrl, email, apiToken, spaceKey, parentPageId }) => {\n const result = await masonSetConfluence({\n baseUrl,\n email,\n apiToken,\n spaceKey,\n parentPageId,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"full_analysis\",\n \"One-shot orientation for a project WITHOUT a concept map (get_snapshot returned exists:false). Returns git history stats, project structure with file counts, curated code sample previews (~60 lines each), and test-to-source mapping. On a mapped project, prefer get_snapshot — it is cheaper and answers feature/architecture questions directly.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await fullAnalysis(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"analyze_project\",\n \"Run git history analysis on a codebase. Returns commit convention patterns, stale directories, and frequently changed files. These are aggregate stats across hundreds of commits that would be expensive to compute manually.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await analyzeProject(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_code_samples\",\n \"Get previews (first ~60 lines) of representative source files from the codebase. Includes entry points, config files, hot files (frequently changed), test examples, and one file per directory for breadth. Read files natively for full content.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n count: z\n .number()\n .optional()\n .default(15)\n .describe(\"Maximum number of files to sample (default: 15)\"),\n },\n async ({ dir, count }) => {\n const result = await getCodeSamples(dir, count);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_snapshot\",\n \"Return the optional feature-to-file architecture map with drift and trust evidence. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. If no map exists, returns exists:false plus project structure, Git signals, and test pairs. Decision capture, get_context, and get_impact still work. No initialization required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await getSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_context\",\n \"Assemble task context: matching decisions with rationale, approval, owner, sources, last review, and freshness, plus related tests, file impact, and any available map entries. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. Proposals are suggestions; legacy records are unreviewed; accepted decisions are constraints subject to freshness. No initialization or map required. Pass task and optional files. map.status and diagnostics preserve missing or invalid knowledge. Impact covers up to three unique files, expanding directory anchors.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n task: z\n .string()\n .describe(\"The task, bug, or change request in natural language — e.g. 'add rate limiting to the API client' or a ticket description\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Optional file paths already known to be involved (e.g. from a diff or stack trace). Entries containing them are boosted above pure text matches.\"),\n },\n async ({ dir, task, files }) => {\n const result = await getContext(dir, task, files);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(dir, \"context\");\n if (warning) return { content: [{ type: \"text\", text: result }, { type: \"text\", text: warning }] };\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"generate_snapshot_batch\",\n \"Map step of the concept-map build. Returns one batch of source files (skeletons of every file in the batch plus a few deeper-read bodies for grounding), along with a system prompt instructing you to derive features and flows for ONLY this batch. Call repeatedly with the returned `nextOffset` until it is null, calling `save_partial_snapshot` between each call. Use product-natural feature names so partials merge cleanly in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n offset: z\n .number()\n .int()\n .optional()\n .describe(\"0-indexed file offset to start the batch at. Omit on the first call; pass the `nextOffset` from the previous response for subsequent calls.\"),\n batchSize: z\n .number()\n .int()\n .optional()\n .describe(\"Files per batch. Defaults to 50.\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Scope the batch walk to this explicit file list — e.g. the drift set from mason_check_drift (changedFiles + unmappedFiles). Pass the SAME list on every batch call of one refresh run. Triggers refresh mode: reduce_snapshot will merge the partials into the existing map instead of rebuilding it.\"),\n },\n async ({ dir, offset, batchSize, files }) => {\n const result = await generateSnapshotBatch(dir, offset, batchSize, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_partial_snapshot\",\n \"Persist the partial concept map you derived for one batch. Call this once per batch, with the `batchId` from the `generate_snapshot_batch` response. Partials accumulate in `.mason/partial-snapshots/` and are merged in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n batchId: z\n .string()\n .describe(\"The `batchId` returned by `generate_snapshot_batch`.\"),\n offset: z\n .number()\n .int()\n .describe(\"The `offset` returned by `generate_snapshot_batch`. Used to order partials in the reduce step.\"),\n features: z\n .record(\n z.object({\n description: z.string(),\n files: z.array(z.string()),\n tests: z.array(z.string()).optional(),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n '\"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, config, logging, adapters). Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Partial features for this batch only — files outside the batch will be added by other partials.\"),\n flows: z\n .record(\n z.object({\n description: z.string(),\n chain: z.array(z.string()),\n })\n )\n .describe(\"Partial flows whose entire chain is in this batch. Cross-batch flows are reconstructed in reduce.\"),\n },\n async ({ dir, batchId, offset, features, flows }) => {\n const result = await saveSnapshotPartial(dir, batchId, offset, features, flows);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"reduce_snapshot\",\n \"Reduce step of the concept-map build. Returns every partial snapshot plus a system prompt asking you to merge them into one coherent project-wide map. Resolve platform variants into single product features, dedupe near-duplicates, and ensure no file is dropped. After producing the unified map, call `save_snapshot` to persist it (this also clears the partials).\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await reduceSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_snapshot\",\n \"Save a concept-to-files map as a persistent project snapshot. Maps feature names and data flows to the files that implement them. Persists across conversations — future sessions can call get_snapshot to instantly find relevant files. No API key needed — you are the LLM generating the map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n features: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the feature\"),\n files: z.array(z.string()).describe(\"File paths that implement this feature\"),\n tests: z.array(z.string()).optional().describe(\"Test file paths for this feature\"),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n 'Classification: \"capability\" for user-facing functionality, \"infrastructure\" for internal plumbing with no end user (DI/service wiring, config, logging, adapters). Capabilities are published to Confluence; infrastructure stays in the AI concept map only. Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Map of feature names to their implementing files\"),\n flows: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the flow\"),\n chain: z.array(z.string()).describe(\"Ordered list of file paths showing data/call flow\"),\n })\n )\n .describe(\"Map of flow names to ordered file chains\"),\n removeFeatures: z\n .array(z.string())\n .optional()\n .describe(\"Feature names to delete from the existing map — for features that were renamed or no longer exist. Applied before merging; only meaningful on incremental saves.\"),\n removeFlows: z\n .array(z.string())\n .optional()\n .describe(\"Flow names to delete from the existing map. Applied before merging; only meaningful on incremental saves.\"),\n },\n async ({ dir, features, flows, removeFeatures, removeFlows }) => {\n const result = await saveSnapshotData(\n dir,\n features,\n flows,\n removeFeatures ?? [],\n removeFlows ?? []\n );\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_decision\",\n \"Capture or revise a decision proposal with rationale, anchors, optional owner, sources, and a known actor. Compare matching get_context records and pending proposals before saving. When new evidence changes the same lesson's assumptions, scope, or recommended action, pass its existing id, including for accepted records. Preserve supported rationale and sources and replace obsolete instructions. Create a new record for a genuinely distinct lesson; skip unchanged restatements. No setup or map required. Writes a local record and preserves content history. Changes create a pending proposal while the last accepted revision remains operative; unchanged content does not re-verify or refresh it. Use review_decision for authorized acceptance or reaffirmation. A proposal cannot supersede a record with an operative accepted revision; review its replacement and retire the original separately.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n title: decisionTitleSchema\n .describe(`Short, specific headline (max ${TITLE_MAX_CHARS} characters). Generates a stable id on creation; revising the title keeps the existing id.`),\n body: decisionBodySchema\n .describe(`The knowledge itself: what was tried/decided, why, and what to avoid. Must contain information NOT derivable by reading the code. Aim for ${BODY_RECOMMENDED_CHARS} characters or fewer; up to ${BODY_MAX_CHARS} is accepted with a warning above the target. Matching context and hooks include the full body. Preserve exceptions; use sources for supporting references.`),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Repo-relative files or directory prefixes this applies to. Matching is shared by retrieval, hooks, review, and drift checking; changes flag the decision for re-verification.\"),\n id: z\n .string()\n .optional()\n .describe(\"Pass the matching record's existing id when evidence changes that lesson's assumptions, scope, or recommended action, including for accepted records. Changed content becomes a proposal while the accepted version remains operative; unchanged content leaves review and freshness untouched.\"),\n supersedes: z\n .string()\n .optional()\n .describe(\"Id of an unreviewed record or proposal with no accepted revision to replace. Operative accepted decisions require separate review and retirement.\"),\n owner: attributionSchema.shape.owner.describe(\"Responsible person or team, when known. Null clears it. Required for acceptance.\"),\n sources: attributionSchema.shape.sources.describe(\"Known PR, issue, incident, discussion, or document references. Omit to preserve; [] clears. At least one is required for acceptance.\"),\n actor: attributionSchema.shape.actor.describe(\"Known person or agent recording this revision. Omit if unknown; do not infer from Git identity.\"),\n force: z\n .boolean()\n .optional()\n .describe(\"Save even when a near-duplicate was detected\"),\n },\n async ({ dir, title, body, category, files, id, supersedes, force, owner, sources, actor }) => {\n const result = await saveDecision(dir, {\n title,\n body,\n category,\n files,\n id,\n supersedes,\n force,\n owner,\n sources,\n actor,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_decision\",\n \"Prepare a decision review: returns the full record and history, any operative accepted revision, provenance, changes and previews for both sets of anchors, and a reviewToken. Then record accept, reaffirm, or retire with that token, the authorized reviewer, and a reason. Acceptance replaces the operative revision; retirement withdraws the entire record including its proposal. Acceptance requires owner, source, readable Git HEAD, and committed anchor changes. Changed records or code invalidate the token. Identities and approvals are recorded assertions for normal PR review, not authenticated proof.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/).describe(\"Decision id from get_context or save_decision\"),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).optional().default(\"prepare\")\n .describe(\"Prepare is read-only. Other actions record an explicitly authorized review.\"),\n reviewer: z.string().trim().min(1).max(200).optional().describe(\"Identity of the actual reviewer; required for a verdict. Never invent one.\"),\n note: z.string().trim().min(1).max(1500).optional().describe(\"Review rationale; required for a verdict. Cite evidence for the decision.\"),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional().describe(\"Token from the prepared review; rejects stale record or code revisions\"),\n },\n async ({ dir, ...input }) => {\n const result = await reviewDecision(dir, input);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_check_drift\",\n \"Check how far the concept map has drifted from HEAD. Deterministic (git + filesystem, no LLM). Returns which features/flows are stale and the changed files behind them, new source files not yet mapped, ghost files (mapped but deleted), renames, and a `recommendation`: `up-to-date` (nothing to do), `incremental` (update just the stale entries via save_snapshot), or `full-rebuild` (re-run the Map-Reduce build). Call this before trusting the map in a long session, or periodically to keep the map and any synced wikis fresh.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await checkDrift(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"verify_snapshot\",\n \"Spot-check the concept map's CORRECTNESS (drift checks freshness; this checks entries were right to begin with). Returns a sample of entries — always the never-verified and least-recently-verified first — with skeletons of their claimed files, for you to judge whether the files actually implement what the entry claims. Report verdicts back via save_verification with each entry’s kind and reviewToken. Tokens bind the entry and bounded source evidence; changed evidence requires a fresh review. Run periodically, or after an automated refresh wrote entries no human reviewed.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n sample: z\n .number()\n .int()\n .optional()\n .describe(\"Entries to sample (default 5)\"),\n },\n async ({ dir, sample }) => {\n const result = await verifySnapshot(dir, sample);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"save_verification\",\n \"Record verify_snapshot verdicts using each entry’s kind and reviewToken. Missing tokens request a fresh review; changed or deleted entries return conflicts without being stamped. Entries judged ok are stamped verifiedAt; failures are flagged verificationFailed with your note and surface in get_context, get_snapshot, and mason_check_drift until corrected. Verdict notes are required for failures.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n verdicts: z\n .record(\n z.object({\n kind: z.enum([\"feature\", \"flow\"]).optional().describe(\"Entry kind returned by verify_snapshot; required to record a verdict\"),\n reviewToken: z.string().optional().describe(\"Copy the reviewToken from verify_snapshot after inspecting its evidence; required to record a verdict\"),\n ok: z.boolean(),\n note: z\n .string()\n .optional()\n .describe(\"One line on what's wrong — required when ok is false\"),\n })\n )\n .describe(\"Entry name → verdict, exactly as returned by verify_snapshot\"),\n },\n async ({ dir, verdicts }) => {\n const result = await saveVerification(dir, verdicts);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"get_impact\",\n \"Trace historical co-change partners, related tests, and references with evidence: resolved imports, explicit paths, or uncertain name candidates. Candidates are not proven dependencies. Deterministic and read-only; no initialization or concept map required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n files: z\n .array(z.string())\n .describe(\"File paths or names to analyze (e.g., ['WeatherRepository.kt'] or ['src/services/auth.ts'])\"),\n },\n async ({ dir, files }) => {\n const result = await getImpact(dir, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"export_to_confluence\",\n \"Sync the project's concept map to Confluence as product-readable wiki pages: an index page, one page per feature (PM-language descriptions, no file paths), and a changelog page. Mason replaces managed page bodies; manual edits to those bodies are overwritten. Requires `mason_set_confluence` to have been called first.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Override the configured space key\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Override the configured parent page ID\"),\n indexPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the index page (default: 'Mason — System Map')\"),\n changelogPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the changelog page (default: 'Mason — Changelog')\"),\n featurePagePrefix: z\n .string()\n .optional()\n .describe(\"Prefix for each feature page title (default: 'Feature: ')\"),\n },\n async ({ dir, spaceKey, parentPageId, indexPageTitle, changelogPageTitle, featurePagePrefix }) => {\n const result = await exportToConfluenceTool(dir, {\n spaceKey,\n parentPageId,\n indexPageTitle,\n changelogPageTitle,\n featurePagePrefix,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(): Promise<void> {\n const server = createMcpServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\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 { prepareRepair, verifyRepair } from \"../audit/repair.js\";\nimport { reviewAdvisory, type AdvisoryReviewInput } from \"../audit/advisory-review.js\";\nimport { formatFixPrompt } from \"../audit/cli.js\";\nimport type { CheckName } from \"../audit/types.js\";\n\nconst exec = promisify(execFile);\nimport { runAll } from \"../analyzers/index.js\";\nimport { isGitRepo } from \"../utils/git.js\";\nimport { sampleFiles } from \"./sampler.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { trustHint, type TrustState } from \"../context/trust.js\";\nimport { compactDecisionKnowledge, effectiveDecision, decisionTrust, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport type { UpsertDecisionInput } from \"../decisions/decisions.js\";\nimport { reviewDecision as runDecisionReview, type ReviewDecisionInput } from \"../decisions/review.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport {\n loadSnapshot,\n updateSnapshot,\n getCurrentGitHash,\n prepareSnapshotBatch,\n normalizeFeatureType,\n DEFAULT_BATCH_SIZE,\n type FeatureType,\n} from \"../snapshot/snapshot.js\";\nimport { createSnapshotTrustReader, readSnapshotTrustIndex } from \"../snapshot/trust.js\";\nimport { computeDrift } from \"../drift/drift.js\";\nimport { prepareSnapshotReview, snapshotEntryContent, type SnapshotVerdict } from \"../snapshot/review.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\nimport {\n BATCH_SYSTEM_PROMPT,\n REDUCE_SYSTEM_PROMPT,\n REFRESH_REDUCE_SYSTEM_PROMPT,\n buildBatchPrompt,\n buildReducePrompt,\n buildRefreshReducePrompt,\n} from \"../snapshot/prompt.js\";\nimport {\n batchIdFor,\n clearAllPartials,\n clearScope,\n loadAllPartials,\n loadScope,\n savePartial,\n saveScope,\n} from \"../snapshot/partials.js\";\nimport type { Snapshot, FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\nimport type { AnalyzerContext } from \"../types.js\";\nimport {\n loadProjectMarker, loadProjectFeatures,\n saveProjectMarker,\n setupPlaybook,\n type ProjectMarker,\n type InitMode,\n} from \"./init.js\";\nimport { inspectOnboarding } from \"./onboarding.js\";\n\nasync function buildContext(dir: string): Promise<AnalyzerContext> {\n return {\n rootDir: dir,\n gitAvailable: await isGitRepo(dir),\n };\n}\n\nexport async function analyzeProject(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const context = await buildContext(rootDir);\n const results = await runAll(context);\n\n // Lightweight project snapshot — pure file existence checks, no parsing\n const projectSnapshot = await detectProjectSnapshot(rootDir);\n\n const output = {\n project: projectSnapshot,\n analyzers: results.map((r) => ({\n name: r.analyzer,\n durationMs: r.durationMs,\n findings: r.findings.map((f) => ({\n category: f.category,\n confidence: f.confidence,\n summary: f.summary,\n evidence: f.evidence,\n suggestedRule: f.ruleCandidate,\n })),\n gaps: r.gaps.map((g) => ({\n question: g.question,\n context: g.context,\n })),\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nasync function detectProjectSnapshot(rootDir: string): Promise<Record<string, unknown>> {\n // Build config files present (what exists, not what's in them)\n const access = await createFileAccess(rootDir);\n const buildFiles = [\n \"package.json\", \"tsconfig.json\",\n \"build.gradle.kts\", \"build.gradle\", \"settings.gradle.kts\", \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \"Cargo.toml\", \"go.mod\", \"go.sum\",\n \"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\",\n \"Gemfile\", \"Package.swift\",\n \"Makefile\", \"CMakeLists.txt\",\n \"Dockerfile\", \"docker-compose.yml\", \"docker-compose.yaml\",\n \".github/workflows\", \".gitlab-ci.yml\", \"Jenkinsfile\",\n ];\n\n const present: string[] = [];\n for (const file of buildFiles) {\n try {\n await fs.access(path.join(rootDir, file));\n present.push(file);\n } catch {\n // Not found\n }\n }\n\n // Test directories and file counts\n const testDirs = [\n \"test\", \"tests\", \"__tests__\", \"spec\",\n \"src/test\", \"src/tests\",\n \"**/src/test\", \"**/src/androidTest\", \"**/src/iosTest\",\n ];\n const testInfo: Record<string, number> = {};\n for (const pattern of testDirs) {\n const files = await access.list(`${pattern}/**/*`);\n if (files.length > 0) {\n testInfo[pattern] = files.length;\n }\n }\n\n // Also count test files by naming convention\n const testFilePatterns = [\n { pattern: \"**/*.test.*\", label: \"*.test.*\" },\n { pattern: \"**/*.spec.*\", label: \"*.spec.*\" },\n { pattern: \"**/*Test.kt\", label: \"*Test.kt\" },\n { pattern: \"**/*Test.java\", label: \"*Test.java\" },\n { pattern: \"**/test_*.py\", label: \"test_*.py\" },\n { pattern: \"**/*_test.go\", label: \"*_test.go\" },\n { pattern: \"**/*Tests.swift\", label: \"*Tests.swift\" },\n { pattern: \"**/*_test.rs\", label: \"*_test.rs\" },\n ];\n for (const { pattern, label } of testFilePatterns) {\n const files = await access.list(pattern);\n if (files.length > 0) {\n testInfo[label] = files.length;\n }\n }\n\n // Source file counts by extension\n const sourceFiles = await access.list();\n const fileCounts: Record<string, number> = {};\n for (const file of sourceFiles) {\n const ext = path.extname(file).slice(1);\n fileCounts[ext] = (fileCounts[ext] ?? 0) + 1;\n }\n\n return {\n configFilesPresent: present,\n sourceFileCounts: fileCounts,\n totalSourceFiles: sourceFiles.length,\n testInfo: Object.keys(testInfo).length > 0 ? testInfo : undefined,\n };\n}\n\nexport async function getCodeSamples(\n dir: string,\n count: number = 15\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const samples = await sampleFiles(rootDir, count);\n\n const output = {\n note: \"These are previews (first ~60 lines). Read the file directly with your own tools to see it in full.\",\n files: samples.map((s) => ({\n path: s.path,\n reason: s.reason,\n totalLines: s.totalLines,\n sizeBytes: s.sizeBytes,\n preview: s.preview,\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nconst UNINIT_MAX_DIRECTORIES = 40;\nconst UNINIT_MAX_TEST_PAIRS = 30;\n\n/** Keep architecture requests useful when the optional map is absent. */\nasync function unmappedContextResponse(rootDir: string): Promise<string> {\n const [structureRaw, analyzerResults, testMap] = await Promise.all([\n getProjectStructure(rootDir),\n runAll(await buildContext(rootDir)).catch(() => []),\n import(\"../test-map.js\")\n .then((m) => m.buildTestMap(rootDir))\n .catch(() => null),\n ]);\n\n const structure = JSON.parse(structureRaw);\n structure.directories = (structure.directories ?? [])\n .sort(\n (a: { fileCount: number }, b: { fileCount: number }) =>\n b.fileCount - a.fileCount\n )\n .slice(0, UNINIT_MAX_DIRECTORIES);\n\n const gitSignals = analyzerResults.flatMap((r) =>\n r.findings.map((f) => ({\n category: f.category,\n summary: f.summary,\n evidence: f.evidence.slice(0, 5),\n }))\n );\n\n return JSON.stringify({\n exists: false,\n map: { status: \"missing\" },\n hint:\n `No Mason concept map exists here yet. Use the context below plus your own reads to answer now — ` +\n `get_context, save_decision, and get_impact work without a map. For an optional map, mason_init with mode: \"map\" provides the generate_snapshot_batch workflow.`,\n structure,\n gitSignals,\n testPairs: testMap?.paired?.slice(0, UNINIT_MAX_TEST_PAIRS) ?? [],\n });\n}\n\nexport async function getProjectStructure(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Get all files\n const allFiles = await (await createFileAccess(rootDir)).list(\"**/*\");\n\n // Build directory summary with file counts and extension breakdown\n const dirInfo = new Map<\n string,\n { fileCount: number; extensions: Map<string, number> }\n >();\n\n for (const file of allFiles) {\n const parts = file.split(\"/\");\n // Track up to 2 levels deep\n for (let depth = 1; depth <= Math.min(parts.length, 2); depth++) {\n const dirPath = parts.slice(0, depth).join(\"/\");\n if (!dirInfo.has(dirPath)) {\n dirInfo.set(dirPath, { fileCount: 0, extensions: new Map() });\n }\n const info = dirInfo.get(dirPath)!;\n info.fileCount++;\n const ext = path.extname(file).slice(1);\n if (ext) {\n info.extensions.set(ext, (info.extensions.get(ext) ?? 0) + 1);\n }\n }\n }\n\n // Format directories sorted by path\n const directories = [...dirInfo.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([dirPath, info]) => {\n const extensions: Record<string, number> = {};\n for (const [ext, count] of info.extensions) {\n extensions[ext] = count;\n }\n return { path: dirPath, fileCount: info.fileCount, extensions };\n });\n\n // Top-level files\n const topLevelFiles = allFiles.filter((f) => !f.includes(\"/\"));\n\n const output = {\n totalFiles: allFiles.length,\n topLevelFiles,\n directories,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nexport async function getTestMap(dir: string): Promise<string> {\n const { buildTestMap } = await import(\"../test-map.js\");\n const result = await buildTestMap(dir);\n return JSON.stringify(result, null, 2);\n}\n\nconst STALE_DIFF_PREVIEW_LINES = 60;\nconst STALE_DIFF_MAX_FILES = 25;\n\nasync function buildChangedFilePreviews(\n rootDir: string,\n changedFiles: string[]\n): Promise<Array<{ path: string; totalLines: number; preview: string }>> {\n const access = await createFileAccess(rootDir);\n const capped = changedFiles.slice(0, STALE_DIFF_MAX_FILES);\n const previews: Array<{ path: string; totalLines: number; preview: string }> = [];\n for (const filePath of capped) {\n const full = await access.read(filePath);\n if (!full) continue;\n const lines = full.content.split(\"\\n\");\n previews.push({\n path: full.path,\n totalLines: full.totalLines,\n preview: lines.slice(0, STALE_DIFF_PREVIEW_LINES).join(\"\\n\"),\n });\n }\n return previews;\n}\n\nexport async function getSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const snapshot = await loadSnapshot(rootDir);\n\n if (!snapshot) {\n return unmappedContextResponse(rootDir);\n }\n\n // Staleness is per entry, not just top-level — a partially refreshed map\n // can be pinned to HEAD while individual entries lag behind.\n const drift = await computeDrift(rootDir);\n const isStale = drift?.stale ?? false;\n\n // Return compact format: feature/flow names -> file lists only.\n // Descriptions and metadata stay in the full snapshot on disk.\n // Deduplicate files that appear in multiple features.\n const seenFiles = new Set<string>();\n const compactFeatures: Record<\n string,\n { files: string[]; tests?: string[]; type: FeatureType }\n > = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n const unique = feat.files.filter((f) => !seenFiles.has(f));\n if (unique.length === 0) continue; // Skip fully duplicate features\n for (const f of unique) seenFiles.add(f);\n const entry: { files: string[]; tests?: string[]; type: FeatureType } = {\n files: unique,\n type: normalizeFeatureType(feat.type),\n };\n if (feat.tests && feat.tests.length > 0) {\n entry.tests = feat.tests;\n }\n compactFeatures[name] = entry;\n }\n\n const compactFlows: Record<string, string[]> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n compactFlows[name] = flow.chain; // Flows keep all files (order matters)\n }\n\n const output: Record<string, unknown> = {\n exists: true,\n map: { status: \"available\" },\n updatedAt: snapshot.updatedAt,\n features: compactFeatures,\n flows: compactFlows,\n stale: isStale,\n };\n\n // Compact decision index — titles only, no bodies (up to 150 × 1.5KB is\n // too heavy for the orientation call). Full text via get_context or the\n // record file itself.\n const { loadDecisionStore } = await import(\"../decisions/decisions.js\");\n const store = await loadDecisionStore(rootDir);\n const decisionRecords = store.records;\n const decisionDrift = await computeDecisionDrift(rootDir, decisionRecords);\n const readTrust = createSnapshotTrustReader(rootDir);\n const trust: { features: Record<string, TrustState>; flows: Record<string, TrustState>; decisions: Record<string, TrustState> } = {\n ...await readSnapshotTrustIndex(readTrust, snapshot, drift),\n decisions: Object.fromEntries(decisionRecords.filter(d => d.status === \"active\").map(d => [d.id, decisionTrust(effectiveDecision(d), decisionDrift.freshness?.[d.id] ?? \"unknown\")])),\n };\n output.trust = trust;\n output.workingTree = drift?.workingTree;\n output.diagnostics = store.diagnostics;\n if (decisionRecords.length > 0) {\n const compactDecisions: Record<\n string,\n ReturnType<typeof compactDecisionKnowledge>\n > = {};\n for (const d of decisionRecords) {\n if (d.status !== \"active\") continue;\n compactDecisions[d.id] = compactDecisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\");\n }\n output.decisions = compactDecisions;\n output.decisionsHint =\n DECISION_GUIDANCE + \" Full bodies via get_context; full history via review_decision.\";\n }\n\n if (isStale && drift) {\n output.hint = driftHint(drift);\n output.drift = {\n historyAvailable: drift.historyAvailable,\n staleFeatures: drift.staleFeatures,\n staleFlows: drift.staleFlows,\n unmappedFiles: drift.unmappedFiles,\n ghostFiles: drift.ghostFiles,\n renames: drift.renames,\n recommendation: drift.recommendation,\n };\n if (drift.historyAvailable && drift.changedFiles.length > 0) {\n const samples = await buildChangedFilePreviews(\n rootDir,\n drift.changedFiles\n );\n output.diff = {\n changedFiles: drift.changedFiles,\n samples,\n truncated: drift.changedFiles.length > STALE_DIFF_MAX_FILES,\n };\n }\n }\n\n output.hint = [output.hint, trustHint([...Object.values(trust.features), ...Object.values(trust.flows), ...Object.values(trust.decisions)]), store.diagnostics.length ? \"Some decision records are invalid; consult diagnostics.\" : \"\"].filter(Boolean).join(\" \");\n return JSON.stringify(output);\n}\n\nfunction driftHint(report: DriftReport): string {\n if (!report.stale) {\n return \"No committed changes affect the map. Consult verification and working-tree evidence before relying on it.\";\n }\n if (!report.historyAvailable) {\n return \"Snapshot is stale but its commit is unreachable (shallow clone or rewritten history), so per-feature drift cannot be computed. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.recommendation === \"full-rebuild\") {\n return \"Drift is too large for an incremental update. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.changedFiles.length + report.unmappedFiles.length > STALE_DIFF_MAX_FILES) {\n return \"Many files drifted — use a scoped refresh instead of reading them all inline: call generate_snapshot_batch(dir, files=[...changedFiles, ...unmappedFiles]) repeatedly (same list every call) with save_partial_snapshot per batch, then reduce_snapshot and save_snapshot. Entries untouched by the drift are preserved in the reduce step.\";\n }\n const nothingToRemap =\n Object.keys(report.staleFeatures).length === 0 &&\n Object.keys(report.staleFlows).length === 0 &&\n report.unmappedFiles.length === 0 &&\n report.ghostFiles.length === 0;\n if (nothingToRemap) {\n return \"Changes since the snapshot don't touch any mapped files. Call save_snapshot with empty features/flows to re-pin the snapshot to HEAD.\";\n }\n return \"Read the changed files under staleFeatures/staleFlows, update those entries (fold unmappedFiles into the right features), and call save_snapshot with only the affected entries — unchanged entries are preserved. Drop ghostFiles from any entries that reference them, and delete features/flows that no longer exist via save_snapshot's removeFeatures/removeFlows.\";\n}\n\nexport async function checkDrift(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n\n const report = await computeDrift(rootDir);\n if (!report) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists to check. Decisions and impact work without one; mason_init with mode: \\\"map\\\" provides the optional map workflow.\",\n });\n }\n\n // Report recorded correctness verdicts alongside freshness evidence.\n const snapshot = await loadSnapshot(rootDir);\n let verification: Record<string, unknown> | undefined;\n let hint = driftHint(report);\n if (snapshot) {\n const all = [\n ...Object.values(snapshot.features),\n ...Object.values(snapshot.flows),\n ];\n const failedNames = [\n ...Object.entries(snapshot.features)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ...Object.entries(snapshot.flows)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ];\n verification = {\n neverVerified: all.filter((e) => !e.verifiedAt).length,\n failed: failedNames,\n };\n if (failedNames.length > 0) {\n hint += ` Verification previously FAILED for [${failedNames.join(\", \")}] — re-map those entries before trusting them.`;\n }\n }\n\n return JSON.stringify({ exists: true, ...report, verification, hint });\n}\n\nexport async function generateSnapshotBatch(\n dir: string,\n offset: number = 0,\n batchSize: number = DEFAULT_BATCH_SIZE,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const scoped = files !== undefined && files.length > 0;\n const scopeFiles = scoped ? sanitizePaths(rootDir, files) : undefined;\n const batch = await prepareSnapshotBatch(dir, offset, batchSize, scopeFiles);\n\n if (scoped && batch.totalFiles > 0) {\n // Mark this partial run as a scoped refresh so reduce_snapshot merges\n // into the existing map instead of rebuilding it from partials alone.\n await saveScope(rootDir, scopeFiles!);\n } else if (!scoped) {\n // A full build must never inherit a scope marker left behind by an\n // abandoned refresh run — its reduce step would wrongly merge instead\n // of rebuilding.\n await clearScope(rootDir);\n }\n\n const task = scoped\n ? \"Refresh the concept map for a scoped set of drifted files (batch step).\"\n : \"Build a concept-to-files map for this project (batch step).\";\n\n if (batch.totalFiles === 0) {\n return JSON.stringify(\n {\n task,\n offset: 0,\n nextOffset: null,\n totalFiles: 0,\n batchId: batchIdFor(0),\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: scoped\n ? \"(None of the requested files exist as source files in this project.)\"\n : \"(No source files found to map.)\",\n next: scoped\n ? \"None of the requested files matched project source files. Check the paths passed in `files` — they must be repo-relative.\"\n : \"No source files were found. Skip the rest of the playbook and call mason_complete_init.\",\n },\n null,\n 2\n );\n }\n\n const batchId = batchIdFor(batch.offset);\n const continueCall = scoped\n ? `generate_snapshot_batch(dir, offset=${batch.nextOffset}, files=<the same list>)`\n : `generate_snapshot_batch(dir, offset=${batch.nextOffset})`;\n\n return JSON.stringify(\n {\n task,\n offset: batch.offset,\n nextOffset: batch.nextOffset,\n totalFiles: batch.totalFiles,\n batchId,\n batchSize: batch.batchSize,\n filesInBatch: batch.skeletons.length,\n scoped,\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: buildBatchPrompt(batch),\n next:\n batch.nextOffset === null\n ? `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). This is the last batch — after saving, proceed to reduce_snapshot.`\n : `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). Then call ${continueCall} to continue.`,\n },\n null,\n 2\n );\n}\n\nexport async function saveSnapshotPartial(\n dir: string,\n batchId: string,\n offset: number,\n features: Record<\n string,\n { description: string; files: string[]; tests?: string[]; type?: FeatureType }\n >,\n flows: Record<string, { description: string; chain: string[] }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Sanitize all file paths to prevent path traversal in stored partials, and\n // normalize the capability/infrastructure classification so it survives reduce.\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n await savePartial(rootDir, {\n batchId,\n offset,\n features,\n flows,\n savedAt: new Date().toISOString(),\n });\n\n const all = await loadAllPartials(rootDir);\n return JSON.stringify(\n {\n status: \"stored\",\n batchId,\n partialsStored: all.length,\n hint:\n \"Partial saved. Continue with the next generate_snapshot_batch call, or proceed to reduce_snapshot when nextOffset is null.\",\n },\n null,\n 2\n );\n}\n\nexport async function reduceSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const partials = await loadAllPartials(rootDir);\n\n if (partials.length === 0) {\n return JSON.stringify(\n {\n status: \"error\",\n error:\n \"No partial snapshots found. Run generate_snapshot_batch and save_partial_snapshot at least once before calling reduce_snapshot.\",\n },\n null,\n 2\n );\n }\n\n // A scope marker means these partials re-analyzed only a drifted subset —\n // merge them into the existing map instead of rebuilding from scratch.\n const scope = await loadScope(rootDir);\n const existing =\n scope && scope.length > 0 ? await loadSnapshot(rootDir) : null;\n\n if (scope && existing) {\n // Strip bookkeeping fields — the assistant shouldn't echo them back.\n const cleanFeatures = Object.fromEntries(\n Object.entries(existing.features).map(([name, feat]) => [\n name,\n {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n },\n ])\n );\n const cleanFlows = Object.fromEntries(\n Object.entries(existing.flows).map(([name, flow]) => [\n name,\n { description: flow.description, chain: flow.chain },\n ])\n );\n\n return JSON.stringify(\n {\n task: \"Merge a scoped refresh into the existing concept map.\",\n partialsCount: partials.length,\n refreshedFiles: scope.length,\n instructions: REFRESH_REDUCE_SYSTEM_PROMPT,\n prompt: buildRefreshReducePrompt(\n { features: cleanFeatures, flows: cleanFlows },\n scope,\n partials\n ),\n next: \"Follow `instructions` to produce the COMPLETE updated features/flows (entries untouched by the refresh copied through unchanged), then call save_snapshot(dir, features, flows). Partials and the scope marker are cleaned up automatically after save_snapshot succeeds.\",\n },\n null,\n 2\n );\n }\n\n return JSON.stringify(\n {\n task: \"Merge partial concept maps into one unified map.\",\n partialsCount: partials.length,\n instructions: REDUCE_SYSTEM_PROMPT,\n prompt: buildReducePrompt(partials),\n next: \"Follow `instructions` to produce the unified features/flows, then call save_snapshot(dir, features, flows). Partial files will be cleaned up automatically after save_snapshot succeeds. Finish with mason_complete_init(dir).\",\n },\n null,\n 2\n );\n}\n\nexport async function fullAnalysis(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const [analysis, structure, samples, testMap, snapshot] = await Promise.all([\n analyzeProject(dir),\n getProjectStructure(dir),\n getCodeSamples(dir, 25),\n getTestMap(dir),\n loadSnapshot(rootDir),\n ]);\n\n const output: Record<string, unknown> = {\n note: \"Full project analysis. Code samples are previews (~60 lines). Read files directly with your own tools to see them in full.\",\n analysis: JSON.parse(analysis),\n structure: JSON.parse(structure),\n codeSamples: JSON.parse(samples),\n testMap: JSON.parse(testMap),\n };\n\n if (snapshot) {\n output.conceptMap = {\n updatedAt: snapshot.updatedAt,\n features: snapshot.features,\n flows: snapshot.flows,\n };\n output.note =\n \"Full project analysis with concept map. The concept map shows which files implement each feature and how data flows through them. Use it to jump straight to relevant files instead of exploring, then read them directly with your own tools.\";\n }\n\n return JSON.stringify(output, null, 2);\n}\n\nfunction sanitizePaths(\n rootDir: string,\n files: string[]\n): string[] {\n return sanitizeRepoPaths(files);\n}\n\nexport async function saveSnapshotData(\n dir: string,\n features: Record<\n string,\n {\n description: string;\n files: string[];\n tests?: string[];\n refreshedHash?: string;\n type?: FeatureType;\n }\n >,\n flows: Record<\n string,\n { description: string; chain: string[]; refreshedHash?: string }\n >,\n removeFeatures: string[] = [],\n removeFlows: string[] = []\n): Promise<string> {\n const rootDir = path.resolve(dir);\n return updateSnapshot(rootDir, async previous => {\n const gitHash = await getCurrentGitHash(rootDir);\n const now = new Date().toISOString();\n\n // Sanitize all file paths to prevent path traversal, and normalize the\n // capability/infrastructure classification (defaults to \"capability\").\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n // If partials exist we're consolidating a Map-Reduce run: replace the\n // snapshot wholesale. Merging here would pollute the unified map with any\n // earlier (possibly hallucinated) call to save_snapshot. Outside of\n // Map-Reduce — incremental refresh of one feature — fall back to merge.\n const partials = await loadAllPartials(rootDir);\n const replaceMode = partials.length > 0;\n const existing = replaceMode ? null : previous;\n // Copy-through entries must not silently lose a failed verification during\n // a scoped rebuild. A changed description/path set requires a new verdict.\n const preserveVerification = (next: FeatureEntry | FlowEntry, old?: FeatureEntry | FlowEntry) => {\n delete next.verifiedAt;\n delete next.verifiedHash;\n delete next.verificationToken;\n delete next.verificationFailed;\n delete next.verificationNote;\n if (!old) return;\n if (JSON.stringify(snapshotEntryContent(next)) !== JSON.stringify(snapshotEntryContent(old))) return;\n next.verificationToken = old.verificationToken;\n next.verifiedAt = old.verifiedAt;\n next.verifiedHash = old.verifiedHash;\n next.verificationFailed = old.verificationFailed;\n next.verificationNote = old.verificationNote;\n };\n for (const [name, entry] of Object.entries(features)) preserveVerification(entry, previous?.features[name]);\n for (const [name, entry] of Object.entries(flows)) preserveVerification(entry, previous?.flows[name]);\n\n if (existing) {\n // Entries not re-sent in this call are only verified as of the previous\n // hash — record that before the top-level gitHash moves to HEAD, so\n // drift detection can still see which entries were skipped.\n if (existing.gitHash !== \"unknown\") {\n for (const feat of Object.values(existing.features)) {\n feat.refreshedHash ??= existing.gitHash;\n }\n for (const flow of Object.values(existing.flows)) {\n flow.refreshedHash ??= existing.gitHash;\n }\n }\n\n const removedFeatures = removeFeatures.filter(\n (name) => name in existing.features\n );\n const removedFlows = removeFlows.filter((name) => name in existing.flows);\n for (const name of removedFeatures) delete existing.features[name];\n for (const name of removedFlows) delete existing.flows[name];\n\n if (gitHash !== \"unknown\") {\n for (const feat of Object.values(features)) feat.refreshedHash = gitHash;\n for (const flow of Object.values(flows)) flow.refreshedHash = gitHash;\n }\n\n existing.features = { ...existing.features, ...features };\n existing.flows = { ...existing.flows, ...flows };\n existing.updatedAt = now;\n existing.gitHash = gitHash;\n return { snapshot: existing, afterSave: () => clearAllPartials(rootDir), result: JSON.stringify({\n status: \"updated\",\n mode: \"merged\",\n features: Object.keys(existing.features).length,\n flows: Object.keys(existing.flows).length,\n removedFeatures: removedFeatures.length,\n removedFlows: removedFlows.length,\n }) };\n }\n\n const snapshot: Snapshot = {\n version: 2,\n createdAt: now,\n updatedAt: now,\n gitHash,\n features,\n flows,\n };\n\n return { snapshot, afterSave: () => clearAllPartials(rootDir), result: JSON.stringify({\n status: replaceMode ? \"replaced\" : \"created\",\n mode: replaceMode ? \"replaced-from-partials\" : \"fresh\",\n features: Object.keys(features).length,\n flows: Object.keys(flows).length,\n }) };\n });\n}\n\nexport async function configureProject(\n dir: string,\n config: {\n patterns?: string[];\n alwaysInclude?: string[];\n ignore?: string[];\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = (await readStoreJson(rootDir, \".mason/config.json\") ?? {}) as Record<string, unknown>;\n\n if (config.patterns) existing.patterns = config.patterns;\n if (config.alwaysInclude) existing.alwaysInclude = config.alwaysInclude;\n if (config.ignore) existing.ignore = config.ignore;\n\n await writeStoreJson(rootDir, \".mason/config.json\", existing);\n\n return JSON.stringify({\n status: \"saved\",\n path: path.join(rootDir, \".mason/config.json\"),\n config: existing,\n });\n}\n\nexport async function getImpact(\n dir: string,\n files: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { analyzeImpact } = await import(\"../impact/impact.js\");\n const result = await analyzeImpact(rootDir, files);\n return JSON.stringify(result, null, 2);\n}\n\nconst VERIFY_DEFAULT_SAMPLE = 5;\n\n/**\n * Verification closes the day-one hole drift can't: drift proves the map is\n * current against git, but nothing proves an entry was CORRECT when written.\n * Sample entries weighted toward never-verified, then oldest-verified.\n */\nexport async function verifySnapshot(\n dir: string,\n sample: number = VERIFY_DEFAULT_SAMPLE\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists yet — nothing to verify.\",\n });\n }\n\n const entries = [\n ...Object.entries(snapshot.features).map(([name, e]) => ({\n name,\n kind: \"feature\" as const,\n description: e.description,\n files: e.files,\n verifiedAt: e.verifiedAt,\n })),\n ...Object.entries(snapshot.flows).map(([name, e]) => ({\n name,\n kind: \"flow\" as const,\n description: e.description,\n files: e.chain,\n verifiedAt: e.verifiedAt,\n })),\n ];\n\n entries.sort((a, b) => {\n if (!a.verifiedAt && !b.verifiedAt) return a.name.localeCompare(b.name);\n if (!a.verifiedAt) return -1;\n if (!b.verifiedAt) return 1;\n return a.verifiedAt.localeCompare(b.verifiedAt);\n });\n\n const access = await createFileAccess(rootDir);\n const picked = entries.slice(0, Math.max(1, sample));\n const toVerify = [];\n for (const entry of picked) {\n const stored = entry.kind === \"feature\" ? snapshot.features[entry.name] : snapshot.flows[entry.name];\n toVerify.push({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n lastVerified: entry.verifiedAt ?? \"never\",\n ...await prepareSnapshotReview(access, entry.kind, entry.name, stored),\n });\n }\n\n const neverVerified = entries.filter((e) => !e.verifiedAt).length;\n\n return JSON.stringify({\n exists: true,\n totalEntries: entries.length,\n neverVerified,\n entries: toVerify,\n instructions:\n 'Judge whether the files implement each claimed feature/flow, then call save_verification with verdicts: {\"<entry name>\": {\"kind\": \"<feature|flow from the entry>\", \"reviewToken\": \"<token from the entry>\", \"ok\": true|false, \"note\": \"<required when ok is false>\"}}. Tokens cover the entry and full contents of the previewed files (at most 8), including unavailable-file markers; previews themselves are truncated. This is a spot-check, not proof of unshown files. A conflict requires verify_snapshot and a fresh review; never reuse a verdict for changed content. If a feature and flow share a name, submit their verdicts in separate calls.'\n });\n}\n\nexport async function saveVerification(\n dir: string,\n verdicts: Record<string, SnapshotVerdict>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n return updateSnapshot(rootDir, async snapshot => {\n if (!snapshot) {\n return { snapshot: null, result: JSON.stringify({ exists: false, stamped: [], hint: \"No concept map exists. Build it and run verify_snapshot before recording verdicts.\" }) };\n }\n\n const stamped: string[] = [], unknown: string[] = [], failed: string[] = [];\n const conflicts: string[] = [], reviewRequired: string[] = [], invalid: string[] = [];\n const candidates: Array<{ name: string; verdict: SnapshotVerdict; entry: FeatureEntry | FlowEntry }> = [];\n let access: Awaited<ReturnType<typeof createFileAccess>> | undefined;\n for (const [name, verdict] of Object.entries(verdicts)) {\n if (!verdict.kind || ![\"feature\", \"flow\"].includes(verdict.kind) || !/^[a-f0-9]{64}$/.test(verdict.reviewToken ?? \"\")) {\n reviewRequired.push(name);\n continue;\n }\n if (typeof verdict.ok !== \"boolean\" || (!verdict.ok && !verdict.note?.trim())) {\n invalid.push(name);\n continue;\n }\n const collection = verdict.kind === \"feature\" ? snapshot.features : snapshot.flows;\n if (!Object.hasOwn(collection, name)) {\n unknown.push(name);\n conflicts.push(name);\n continue;\n }\n const entry = collection[name];\n access ??= await createFileAccess(rootDir);\n const current = await prepareSnapshotReview(access, verdict.kind, name, entry);\n if (current.reviewToken !== verdict.reviewToken) conflicts.push(name);\n else candidates.push({ name, verdict, entry });\n }\n\n const verifiedHash = candidates.length ? await getCurrentGitHash(rootDir) : \"unknown\";\n // Refresh the inventory and source reads before committing a multi-entry batch.\n // Editors do not take our lock; the persisted token identifies the evidence\n // actually checked, while normal drift reporting handles later source edits.\n const freshAccess = candidates.length ? await createFileAccess(rootDir) : null;\n const now = new Date().toISOString();\n for (const { name, verdict, entry } of candidates) {\n const current = await prepareSnapshotReview(freshAccess!, verdict.kind!, name, entry);\n if (current.reviewToken !== verdict.reviewToken) {\n conflicts.push(name);\n continue;\n }\n entry.verifiedAt = now;\n entry.verifiedHash = verifiedHash;\n entry.verificationToken = verdict.reviewToken;\n if (verdict.ok) {\n delete entry.verificationFailed;\n delete entry.verificationNote;\n } else {\n entry.verificationFailed = true;\n entry.verificationNote = verdict.note!.trim();\n failed.push(name);\n }\n stamped.push(name);\n }\n\n const rejected = conflicts.length + reviewRequired.length + invalid.length;\n const status = rejected ? (stamped.length ? \"partial\" : conflicts.length ? \"conflict\" : reviewRequired.length ? \"review_required\" : \"invalid\")\n : stamped.length ? \"saved\" : \"unchanged\";\n const hints: string[] = [];\n if (conflicts.length) hints.push(`Entries [${conflicts.join(\", \")}] changed or were deleted after review. Run verify_snapshot and review current evidence before retrying.`);\n if (reviewRequired.length) hints.push(`Entries [${reviewRequired.join(\", \")}] need kind and reviewToken from verify_snapshot. Inspect that evidence before submitting a verdict.`);\n if (invalid.length) hints.push(`Entries [${invalid.join(\", \")}] need a boolean ok and a non-empty note when ok is false.`);\n if (failed.length) hints.push(`Entries [${failed.join(\", \")}] are mis-mapped. Re-map them: read their actual files, correct the entries, and call save_snapshot with only those entries (plus removeFeatures/removeFlows if a concept no longer exists). Then run verify_snapshot for fresh review tokens.`);\n if (!hints.length) hints.push(stamped.length ? \"All submitted entries verified against the reviewed evidence. Re-run verify_snapshot periodically.\" : \"No verdicts submitted; nothing changed.\");\n if (stamped.length) snapshot.updatedAt = now;\n return { snapshot: stamped.length ? snapshot : null, result: JSON.stringify({\n status, stamped, unknown, failed, conflicts, reviewRequired, invalid, hint: hints.join(\" \"),\n }) };\n });\n}\n\nexport async function saveDecision(\n dir: string,\n input: UpsertDecisionInput\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { upsertDecision } = await import(\"../decisions/decisions.js\");\n const result = await upsertDecision(rootDir, input);\n return JSON.stringify(result);\n}\n\nexport async function reviewDecision(dir: string, input: ReviewDecisionInput): Promise<string> {\n return JSON.stringify(await runDecisionReview(path.resolve(dir), input));\n}\n\nexport async function getContext(\n dir: string,\n task: string,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { assembleContext } = await import(\"../context/assemble.js\");\n const bundle = await assembleContext(rootDir, task, files);\n return JSON.stringify(bundle);\n}\n\n// ===== Init MCP tools =====\n\nexport async function masonAutomation(dir: string, action: \"status\" | \"check\"): Promise<string> {\n try {\n const { automate, automationStatus, summarize } = await import(\"../automation/runtime.js\");\n const { installedAutomation } = await import(\"../automation/install.js\");\n if (action === \"status\") {\n const { setupStatus } = await import(\"../setup/status.js\");\n return JSON.stringify({ ...await automationStatus(dir), configured: await installedAutomation(dir), setup: await setupStatus(dir) });\n }\n if (action !== \"check\") throw new Error(\"Expected status or check.\");\n const { report } = await automate(dir, { event: \"task_end\" });\n const { findings, ...summary } = report;\n return JSON.stringify({ ...summary, findings: findings.slice(0, 5), truncated: findings.length > 5, summary: summarize(report) });\n } catch (error) {\n const { automationFailure } = await import(\"../automation/execution.js\");\n const failure = automationFailure(error);\n return JSON.stringify({ version: 1, status: \"unavailable\", error: failure.message, failure });\n }\n}\n\nexport async function masonReviewAdvisory(dir: string, options: AdvisoryReviewInput): Promise<string> {\n try { return JSON.stringify(await reviewAdvisory(dir, options), null, 2); }\n catch (error) { return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) }); }\n}\n\nexport async function masonRepair(dir: string, options: { action: \"prepare\" | \"verify\"; baselinePath?: string; checks?: CheckName[] }): Promise<string> {\n try {\n if (options.action === \"verify\") {\n if (!options.baselinePath || options.checks) throw new Error(\"Verification requires baselinePath and uses the original checks; do not pass checks.\");\n return JSON.stringify(await verifyRepair(dir, options.baselinePath), null, 2);\n }\n if (options.action !== \"prepare\" || options.baselinePath) throw new Error(\"Preparation accepts checks, not an existing baselinePath.\");\n const result = await prepareRepair(dir, options.checks);\n return JSON.stringify({ ...result, workOrder: formatFixPrompt(result.report, result.baselinePath) }, null, 2);\n } catch (error) {\n return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nexport async function masonInit(dir: string, options: { mode?: InitMode; host?: \"codex\" | \"claude\"; base?: string; evidence?: string[] } = {}): Promise<string> {\n if (options.mode === \"setup\") {\n const { setupProject } = await import(\"../setup/setup.js\");\n return JSON.stringify(await setupProject(dir, options), null, 2);\n }\n if (options.host) throw new Error(\"host applies only to mode: setup.\");\n const rootDir = path.resolve(dir);\n const marker = await loadProjectMarker(rootDir);\n const { loadSetup } = await import(\"../setup/model.js\");\n const setup = await loadSetup(rootDir);\n const mode = options.mode ?? \"quickstart\";\n const findings = await inspectOnboarding(rootDir, options.base, options.evidence);\n return JSON.stringify(\n {\n initialized: marker !== null || setup !== null,\n ...(marker ? { initializedAt: marker.initializedAt } : {}),\n confluenceConfigured: (await loadProjectFeatures(rootDir)).confluence === true,\n mode,\n ...findings,\n playbook: setupPlaybook(mode),\n },\n null,\n 2\n );\n}\n\nexport async function masonCompleteInit(\n dir: string,\n options: { confluenceConfigured?: boolean } = {}\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = await loadProjectMarker(rootDir);\n const features = await loadProjectFeatures(rootDir);\n const marker: ProjectMarker = {\n version: 1,\n initializedAt: existing?.initializedAt ?? new Date().toISOString(),\n features: {\n ...features,\n ...(options.confluenceConfigured === undefined ? {} : { confluence: options.confluenceConfigured }),\n },\n };\n await saveProjectMarker(rootDir, marker);\n return JSON.stringify(\n {\n status: \"initialized\",\n marker,\n hint: \"Assistant setup recorded. Save decisions as you learn, review and commit them, and retrieve them with get_context. A concept map is optional.\",\n },\n null,\n 2\n );\n}\n\n// ===== Confluence MCP tools =====\n\nexport async function masonSetConfluence(input: {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey?: string;\n parentPageId?: string;\n}): Promise<string> {\n const { createConfluenceClient } = await import(\"../confluence/client.js\");\n const { saveConfluenceConfig } = await import(\"../llm/config.js\");\n const { normalizeAtlassianBaseUrl } = await import(\"../confluence/url.js\");\n\n let baseUrl: string;\n try {\n baseUrl = normalizeAtlassianBaseUrl(input.baseUrl);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n if (!input.email.includes(\"@\")) {\n return JSON.stringify({\n status: \"error\",\n error: `Email looks invalid: \"${input.email}\".`,\n });\n }\n if (!input.apiToken.trim()) {\n return JSON.stringify({\n status: \"error\",\n error: \"API token is required.\",\n });\n }\n\n const probeConfig = {\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey ?? \"\",\n parentPageId: input.parentPageId,\n };\n const client = createConfluenceClient(probeConfig);\n\n let spaces;\n try {\n spaces = await client.listSpaces();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"401\") || msg.includes(\"403\")) {\n return JSON.stringify({\n status: \"error\",\n error:\n \"Credentials rejected by Confluence. Re-check the email and that the API token hasn't expired or been revoked.\",\n });\n }\n return JSON.stringify({\n status: \"error\",\n error: `Confluence validation failed: ${msg}`,\n });\n }\n\n if (!input.spaceKey) {\n // Step 1 — return spaces for the assistant to relay to the user.\n return JSON.stringify(\n {\n status: \"spaces_listed\",\n baseUrl,\n spaces: spaces.map((s) => ({ key: s.key, name: s.name })),\n hint:\n spaces.length === 0\n ? \"Authenticated, but no spaces are visible to this account. Create one in Confluence first, then re-run mason_set_confluence.\"\n : \"Ask the user which space to use, then call mason_set_confluence again with the same baseUrl/email/apiToken plus the chosen spaceKey.\",\n },\n null,\n 2\n );\n }\n\n const match = spaces.find((s) => s.key === input.spaceKey);\n if (!match) {\n return JSON.stringify({\n status: \"error\",\n error: `Space key \"${input.spaceKey}\" was not found among the spaces visible to this account. Available keys: ${spaces.map((s) => s.key).join(\", \") || \"(none)\"}.`,\n });\n }\n\n await saveConfluenceConfig({\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey,\n parentPageId: input.parentPageId,\n });\n\n return JSON.stringify(\n {\n status: \"saved\",\n spaceKey: input.spaceKey,\n spaceName: match.name,\n hint:\n \"Confluence is configured. The credentials are stored in ~/.mason/config.json. Call export_to_confluence to sync the concept map.\",\n },\n null,\n 2\n );\n}\n\nexport async function exportToConfluenceTool(\n dir: string,\n overrides?: {\n spaceKey?: string;\n parentPageId?: string;\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const { loadConfig } = await import(\"../llm/config.js\");\n const { exportToConfluence } = await import(\"../confluence/sync.js\");\n\n const config = await loadConfig();\n if (!config?.confluence) {\n return JSON.stringify({\n status: \"error\",\n error:\n 'No Confluence credentials configured. Call mason_set_confluence first.',\n });\n }\n\n const merged = {\n ...config,\n confluence: {\n ...config.confluence,\n spaceKey: overrides?.spaceKey ?? config.confluence.spaceKey,\n parentPageId: overrides?.parentPageId ?? config.confluence.parentPageId,\n },\n };\n\n try {\n const summary = await exportToConfluence(rootDir, merged, {\n indexPageTitle: overrides?.indexPageTitle,\n changelogPageTitle: overrides?.changelogPageTitle,\n featurePagePrefix: overrides?.featurePagePrefix,\n });\n return JSON.stringify({ status: \"ok\", ...summary }, null, 2);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","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\";\nimport { findingId } from \"./findings.js\";\nimport { runAdvisoryCli } from \"./advisory-cli.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits README.md and agent instruction files at any depth, preserving filename case\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\nUse mason audit review --help to prepare and record an authorized advisory assessment.\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 reviewed = new Set(report.advisoryReviews?.filter(review => review.status === \"current\").map(review => review.id));\n const open = report.advisories.filter(finding => !reviewed.has(findingId(finding)));\n const suppressed = (report.suppressedAdvisories ?? []).filter(finding => !reviewed.has(findingId(finding)));\n const reviewCount = open.length + suppressed.length;\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 (open.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of open) {\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 if (reviewed.size) lines.push(`${reviewed.size} advisories have recorded assessments covering current evidence (see --json).`);\n for (const review of report.advisoryReviews ?? []) if (review.status !== \"current\") lines.push(` [${review.status}] ${review.reason}`);\n for (const advisory of suppressed) {\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: review whether the directory needs documenting; an omission alone does not establish a defect. Preserve scope and describe only what you verified.\"\n );\n lines.push(\n \"- Historical ADVISORIES require a separate authorized assessment using review_advisory with the baselinePath and findingId from verification. Prepare and inspect evidence first; record addressed, inapplicable or deferred with the actual reviewer, note and reviewToken. Decision findings use review_decision. Candidates marked resolution: recheck can be rerun to see whether the condition remains; this does not establish semantic approval. Report what remains unknown.\"\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 documents and supported claims; application behavior and code examples 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 if (argv[0] === \"review\") return runAdvisoryCli(argv.slice(1), io);\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 README.md or agent instruction files 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 path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { reviewAdvisory, type AdvisoryReviewInput } from \"./advisory-review.js\";\n\nconst USAGE = `Usage: mason audit review --baseline <path> --finding <id> [options]\n\nPrepare an advisory assessment against retained evidence (read-only by default).\n --dir <path> Repository root (default: current directory)\n --baseline <path> Original repair baseline\n --finding <id> findingId from repair verification or automation\n --outcome <value> Record addressed, inapplicable, or deferred\n --reviewer <name> Actual authorized reviewer\n --note <reason> Assessment reason\n --token <token> reviewToken returned by preparation\n --json Full evidence and review history\n\nRecording requires prior preparation and committed relevant edits. Review records\nbelong in Git under .mason/reviews/advisories/. Deferral remains outstanding.\nDecision findings use review_decision; this command never approves decisions.\nExit 0: prepared/recorded; 2: unavailable, conflict, or decision review required.`;\n\nexport async function runAdvisoryCli(args: string[], io = { out: (text: string) => console.log(text), err: (text: string) => console.error(text) }): Promise<number> {\n if (args.includes(\"--help\") || args.includes(\"-h\")) { io.out(USAGE); return 0; }\n try {\n const flags: Record<string, string> = {}; let json = false;\n for (let i = 0; i < args.length; i++) {\n const flag = args[i];\n if (flag === \"--json\") { json = true; continue; }\n if (![\"--dir\", \"--baseline\", \"--finding\", \"--outcome\", \"--reviewer\", \"--note\", \"--token\"].includes(flag) || flags[flag]) throw new Error(\"Unexpected or repeated argument: \" + flag);\n const value = args[++i]; if (!value || value.startsWith(\"--\")) throw new Error(flag + \" requires a value.\");\n flags[flag] = value;\n }\n if (!flags[\"--outcome\"] && [\"--reviewer\", \"--note\", \"--token\"].some(key => flags[key])) throw new Error(\"Use --outcome to record an assessment.\");\n const input = { baselinePath: flags[\"--baseline\"], findingId: flags[\"--finding\"],\n action: flags[\"--outcome\"] ?? \"prepare\", reviewer: flags[\"--reviewer\"], note: flags[\"--note\"], reviewToken: flags[\"--token\"] } as AdvisoryReviewInput;\n const result = await reviewAdvisory(path.resolve(flags[\"--dir\"] ?? process.cwd()), input);\n if (json) io.out(JSON.stringify(result, null, 2));\n else {\n const lines = [`Advisory review: ${result.status}.`];\n if (\"finding\" in result && result.finding && result.evidence) lines.push(`[${result.finding.type}] ${result.finding.anchor.doc}: ${result.finding.message}`,\n `Finding: ${result.findingId}`, `Prepared against commit ${result.evidence.head.slice(0, 12)}.`,\n result.evidence.dirty ? \"Relevant files have uncommitted edits; commit them and prepare again before recording.\" : \"Relevant files are committed.\",\n `Review token: ${result.reviewToken}`, ...(result.diff ? [\"Scoped changes:\", result.diff] : []), ...(result.diffNote ? [result.diffNote] : []));\n if (\"event\" in result) lines.push(`${result.event.outcome} — ${result.event.reviewer}: ${result.event.note}`, `Record: ${result.recordPath}`);\n lines.push(result.hint);\n io.out(stripVTControlCharacters(lines.join(\"\\n\")));\n }\n return result.status === \"decision-review-required\" ? 2 : 0;\n } catch (error) { io.err(stripVTControlCharacters(error instanceof Error ? error.message : String(error))); return 2; }\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { BaseAnalyzer } from \"./base.js\";\nimport type { AnalyzerContext, AnalyzerResult, Finding, Gap } from \"../types.js\";\n\nconst exec = promisify(execFile);\n\nexport class GitHistoryAnalyzer extends BaseAnalyzer {\n name = \"git-history\";\n\n async analyze(context: AnalyzerContext): Promise<AnalyzerResult> {\n const startTime = Date.now();\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n if (!context.gitAvailable) {\n return this.createResult([], [], startTime);\n }\n\n const [staleFindings, staleGaps] = await this.findStaleDirectories(context);\n findings.push(...staleFindings);\n gaps.push(...staleGaps);\n\n const hotFindings = await this.findHotFiles(context);\n findings.push(...hotFindings);\n\n const commitFindings = await this.analyzeCommitPatterns(context);\n findings.push(...commitFindings);\n\n return this.createResult(findings, gaps, startTime);\n }\n\n private async git(\n args: string[],\n cwd: string\n ): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", args, { cwd, maxBuffer: 10_000_000 });\n return stdout.trim();\n } catch {\n return \"\";\n }\n }\n\n private async findStaleDirectories(\n context: AnalyzerContext\n ): Promise<[Finding[], Gap[]]> {\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n // Get top-level directories with their last commit date\n const output = await this.git(\n [\"log\", \"--all\", \"--format=%ci\", \"--name-only\", \"--diff-filter=AMCR\", \"-n\", \"500\"],\n context.rootDir\n );\n\n if (!output) return [findings, gaps];\n\n const dirLastTouch = new Map<string, Date>();\n let currentDate: Date | null = null;\n\n for (const line of output.split(\"\\n\")) {\n if (!line) continue;\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(line)) {\n currentDate = new Date(line);\n } else if (currentDate) {\n const topDir = line.split(\"/\")[0];\n if (\n topDir &&\n !topDir.startsWith(\".\") &&\n !topDir.includes(\"node_modules\")\n ) {\n const existing = dirLastTouch.get(topDir);\n if (!existing || currentDate > existing) {\n dirLastTouch.set(topDir, currentDate);\n }\n }\n }\n }\n\n const sixMonthsAgo = new Date();\n sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);\n\n for (const [dir, lastTouch] of dirLastTouch) {\n if (lastTouch < sixMonthsAgo) {\n const monthsStale = Math.floor(\n (Date.now() - lastTouch.getTime()) / (1000 * 60 * 60 * 24 * 30)\n );\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.7,\n summary: `Directory \"${dir}\" hasn't been modified in ${monthsStale} months`,\n evidence: [\n { filePath: dir, detail: `Last commit: ${lastTouch.toISOString().split(\"T\")[0]}` },\n ],\n ruleCandidate: `Do not refactor or modify files in \"${dir}/\" unless explicitly asked — this area has been stable for ${monthsStale} months and may be legacy code.`,\n })\n );\n gaps.push({\n analyzer: this.name,\n question: `Directory \"${dir}\" hasn't been touched in ${monthsStale} months. Is it deprecated, stable, or legacy?`,\n context: `Last modified: ${lastTouch.toISOString().split(\"T\")[0]}`,\n answerKey: `stale-dir-${dir}`,\n });\n }\n }\n\n return [findings, gaps];\n }\n\n private async findHotFiles(context: AnalyzerContext): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n // Most frequently changed files in the last 3 months\n const output = await this.git(\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const fileCounts = new Map<string, number>();\n for (const line of output.split(\"\\n\")) {\n if (!line || line.startsWith(\".\") || line.includes(\"node_modules\")) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const sorted = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10);\n\n if (sorted.length > 0 && sorted[0][1] >= 5) {\n const hotFiles = sorted.filter(([, count]) => count >= 5);\n if (hotFiles.length > 0) {\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.8,\n summary: `${hotFiles.length} files changed frequently in the last 3 months`,\n evidence: hotFiles.map(([file, count]) => ({\n filePath: file,\n detail: `${count} commits`,\n })),\n ruleCandidate: `These files change frequently and are high-risk for conflicts: ${hotFiles.map(([f]) => f).join(\", \")}. Take extra care when modifying them.`,\n })\n );\n }\n }\n\n return findings;\n }\n\n private async analyzeCommitPatterns(\n context: AnalyzerContext\n ): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n const output = await this.git(\n [\"log\", \"--format=%s\", \"-n\", \"100\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const messages = output.split(\"\\n\").filter(Boolean);\n\n // Check for conventional commits\n const conventionalPattern = /^(feat|fix|chore|docs|style|refactor|test|perf|ci|build|revert)(\\(.+\\))?:/;\n const conventionalCount = messages.filter((m) =>\n conventionalPattern.test(m)\n ).length;\n const conventionalRatio = conventionalCount / messages.length;\n\n if (conventionalRatio > 0.5) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: Math.min(conventionalRatio + 0.1, 1),\n summary: `${Math.round(conventionalRatio * 100)}% of recent commits use conventional commit format`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${conventionalCount} of ${messages.length} commits match`,\n },\n ],\n ruleCandidate:\n \"Use conventional commit format: type(scope): description (e.g., feat(auth): add login endpoint)\",\n })\n );\n }\n\n // Check for ticket/issue references\n const ticketPattern = /[A-Z]+-\\d+|#\\d+/;\n const ticketCount = messages.filter((m) => ticketPattern.test(m)).length;\n const ticketRatio = ticketCount / messages.length;\n\n if (ticketRatio > 0.3) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: ticketRatio,\n summary: `${Math.round(ticketRatio * 100)}% of commits reference issue/ticket IDs`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${ticketCount} of ${messages.length} commits have ticket refs`,\n },\n ],\n ruleCandidate:\n \"Include issue/ticket references in commit messages when applicable.\",\n })\n );\n }\n\n return findings;\n }\n}\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport type {\n AnalyzerContext,\n AnalyzerResult,\n Finding,\n FindingCategory,\n} from \"../types.js\";\n\nexport abstract class BaseAnalyzer {\n abstract name: string;\n abstract analyze(context: AnalyzerContext): Promise<AnalyzerResult>;\n\n protected async findFiles(\n patterns: string[],\n root: string\n ): Promise<string[]> {\n return fg(patterns, {\n cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/.git/**\"],\n absolute: true,\n });\n }\n\n protected async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, \"utf-8\");\n }\n\n protected createFinding(partial: {\n category: FindingCategory;\n confidence: number;\n summary: string;\n evidence?: Finding[\"evidence\"];\n ruleCandidate?: string | null;\n }): Finding {\n return {\n analyzer: this.name,\n category: partial.category,\n confidence: partial.confidence,\n summary: partial.summary,\n evidence: partial.evidence ?? [],\n ruleCandidate: partial.ruleCandidate ?? null,\n };\n }\n\n protected createResult(\n findings: Finding[],\n gaps: AnalyzerResult[\"gaps\"],\n startTime: number\n ): AnalyzerResult {\n return {\n analyzer: this.name,\n findings,\n gaps,\n durationMs: Date.now() - startTime,\n };\n }\n}\n","import type { AnalyzerContext, AnalyzerResult } from \"../types.js\";\nimport type { BaseAnalyzer } from \"./base.js\";\nimport { GitHistoryAnalyzer } from \"./git-history.js\";\n\nconst analyzers: BaseAnalyzer[] = [new GitHistoryAnalyzer()];\n\nexport async function runAll(\n context: AnalyzerContext\n): Promise<AnalyzerResult[]> {\n return Promise.all(analyzers.map((a) => a.analyze(context)));\n}\n","import { execGit } from \"./git-read.js\";\n\n\nexport async function isGitRepo(dir: string): Promise<boolean> {\n try {\n await execGit([\"rev-parse\", \"--git-dir\"], { cwd: dir });\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_EXTENSIONS } from \"../utils/files.js\";\nexport type { ProjectConfig } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\n\nconst CONFIG_FILES = [\n // Build & project config\n \"package.json\",\n \"tsconfig.json\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"Gemfile\",\n \"*.csproj\",\n // Version catalogs & dependency locks\n \"gradle/libs.versions.toml\",\n // Code quality & formatting\n \".editorconfig\",\n \".eslintrc.*\",\n \"eslint.config.*\",\n \".prettierrc\",\n \"rustfmt.toml\",\n \".swiftlint.yml\",\n // CI/CD\n \".github/workflows/*.yml\",\n \".gitlab-ci.yml\",\n \"Jenkinsfile\",\n // Containerization\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n];\n\nconst ENTRY_POINT_PATTERNS = [\n \"src/main.*\",\n \"src/index.*\",\n \"src/app.*\",\n \"main.*\",\n \"index.*\",\n \"app.*\",\n \"App.*\",\n \"**/Main.kt\",\n \"**/Application.kt\",\n \"**/main.py\",\n \"**/main.go\",\n \"**/main.rs\",\n \"**/lib.rs\",\n \"**/Program.cs\",\n];\n\n// Filename patterns that reveal architectural patterns and conventions.\n// These are language-agnostic — the suffixes appear across ecosystems.\n// Ordered by architectural importance — most distinctive patterns first.\nconst ARCHITECTURAL_PATTERNS = [\n // State/data flow\n { glob: \"**/*ViewModel.*\", category: \"state\", reason: \"viewmodel (state management)\" },\n { glob: \"**/*Store.*\", category: \"state\", reason: \"store (state management)\" },\n { glob: \"**/*Reducer.*\", category: \"state\", reason: \"reducer (state management)\" },\n // Data layer — interface\n { glob: \"**/*Repository.*\", category: \"data-interface\", reason: \"repository interface (data layer contract)\" },\n { glob: \"**/*Dao.*\", category: \"data-interface\", reason: \"DAO (data access)\" },\n { glob: \"**/*DataSource.*\", category: \"data-interface\", reason: \"data source\" },\n // Data layer — implementation (where actual patterns live: mappers, retry, IO dispatchers)\n { glob: \"**/*RepositoryImpl.*\", category: \"data-impl\", reason: \"repository implementation (data layer patterns)\" },\n { glob: \"**/*ServiceImpl.*\", category: \"data-impl\", reason: \"service implementation\" },\n { glob: \"**/*Impl.*\", category: \"data-impl\", reason: \"implementation (concrete patterns)\" },\n // Data transformation\n { glob: \"**/*Mapper.*\", category: \"transform\", reason: \"mapper (data transformation)\" },\n { glob: \"**/*Converter.*\", category: \"transform\", reason: \"converter (data transformation)\" },\n { glob: \"**/*Adapter.*\", category: \"transform\", reason: \"adapter (interface adaptation)\" },\n // Dependency injection / wiring\n { glob: \"**/*Module.*\", category: \"di\", reason: \"module (DI/wiring)\" },\n { glob: \"**/*Provider.*\", category: \"di\", reason: \"provider (DI/wiring)\" },\n { glob: \"**/*Container.*\", category: \"di\", reason: \"container (DI/wiring)\" },\n { glob: \"**/*Factory.*\", category: \"di\", reason: \"factory (object creation)\" },\n // API / network\n { glob: \"**/*Service.*\", category: \"api\", reason: \"service (business/API layer)\" },\n { glob: \"**/*Client.*\", category: \"api\", reason: \"client (API/network layer)\" },\n { glob: \"**/*Api.*\", category: \"api\", reason: \"API interface definition\" },\n // Interface contracts / protocols\n { glob: \"**/*Interface.*\", category: \"contract\", reason: \"interface definition\" },\n { glob: \"**/*Protocol.*\", category: \"contract\", reason: \"protocol definition\" },\n { glob: \"**/*Trait.*\", category: \"contract\", reason: \"trait definition\" },\n // Routing / navigation\n { glob: \"**/*Router.*\", category: \"routing\", reason: \"router (navigation/routing)\" },\n { glob: \"**/*Route.*\", category: \"routing\", reason: \"route definition\" },\n { glob: \"**/*NavHost.*\", category: \"routing\", reason: \"navigation host\" },\n { glob: \"**/*Controller.*\", category: \"routing\", reason: \"controller (request handling)\" },\n { glob: \"**/*Handler.*\", category: \"routing\", reason: \"handler (request handling)\" },\n // Middleware / interceptors\n { glob: \"**/*Middleware.*\", category: \"middleware\", reason: \"middleware (request pipeline)\" },\n { glob: \"**/*Interceptor.*\", category: \"middleware\", reason: \"interceptor (cross-cutting)\" },\n { glob: \"**/*Plugin.*\", category: \"middleware\", reason: \"plugin (extensibility)\" },\n // Models / types\n { glob: \"**/*Model.*\", category: \"model\", reason: \"model (domain types)\" },\n { glob: \"**/*Entity.*\", category: \"model\", reason: \"entity (persistence types)\" },\n { glob: \"**/*Dto.*\", category: \"model\", reason: \"DTO (data transfer types)\" },\n { glob: \"**/*Schema.*\", category: \"model\", reason: \"schema (data validation)\" },\n // Use cases / commands\n { glob: \"**/*UseCase.*\", category: \"usecase\", reason: \"use case (business logic)\" },\n { glob: \"**/*Interactor.*\", category: \"usecase\", reason: \"interactor (business logic)\" },\n { glob: \"**/*Command.*\", category: \"usecase\", reason: \"command (CQRS pattern)\" },\n];\n\nconst PREVIEW_LINES = 60;\n\nexport interface SampledFile {\n path: string;\n preview: string;\n totalLines: number;\n sizeBytes: number;\n reason: string;\n}\n\nexport async function sampleFiles(\n rootDir: string,\n maxFiles: number = 25\n): Promise<SampledFile[]> {\n const selected = new Map<string, string>(); // path -> reason\n const access = await createFileAccess(rootDir);\n const projectConfig = access.config;\n\n // 0. Always-include files from project config (highest priority)\n for (const filePath of projectConfig.alwaysInclude ?? []) {\n if (selected.size >= maxFiles) break;\n // Validate path stays within project root\n const resolvedPath = path.resolve(rootDir, filePath);\n if (!resolvedPath.startsWith(path.resolve(rootDir))) continue;\n selected.set(filePath, \"always-include (project config)\");\n }\n\n // 1. Config files (cap at 5)\n let configCount = 0;\n for (const pattern of CONFIG_FILES) {\n if (configCount >= 5) break;\n const matches = await access.list(pattern, {\n deep: 3,\n });\n for (const match of matches) {\n if (configCount >= 5 || selected.size >= maxFiles) break;\n selected.set(match, \"config file\");\n configCount++;\n }\n }\n\n // 2. Module build/config files — build files from subdirectories reveal dependency graph\n const moduleBuildPatterns = [\n // Gradle\n \"**/build.gradle.kts\",\n \"**/build.gradle\",\n // Cargo workspace members\n \"**/Cargo.toml\",\n // Node workspaces\n \"**/package.json\",\n // Go sub-modules\n \"**/go.mod\",\n ];\n let moduleBuildCount = 0;\n for (const pattern of moduleBuildPatterns) {\n const matches = await access.list(pattern, {\n deep: 4,\n });\n // Skip root-level files (already captured as config)\n const subMatches = matches.filter((m) => m.includes(\"/\"));\n for (const match of subMatches) {\n if (moduleBuildCount >= 4 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"module build file (reveals dependency graph)\");\n moduleBuildCount++;\n }\n }\n if (moduleBuildCount >= 4) break;\n }\n\n // 3. Entry points (cap at 2)\n let entryCount = 0;\n for (const pattern of ENTRY_POINT_PATTERNS) {\n if (entryCount >= 2) break;\n const matches = await access.list(pattern, {\n deep: 5,\n });\n for (const match of matches) {\n if (entryCount >= 2 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"entry point\");\n entryCount++;\n }\n }\n }\n\n // 4. Hot files from git (up to 5)\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const fileCounts = new Map<string, number>();\n for (const line of stdout.split(\"\\n\")) {\n if (!line) continue;\n if (\n line.includes(\"node_modules\") ||\n line.includes(\"/build/\") ||\n line.includes(\".gradle\") ||\n line.includes(\"/generated/\")\n )\n continue;\n const ext = path.extname(line).slice(1);\n if (!SOURCE_EXTENSIONS.includes(ext)) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const hotFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n for (const [file, count] of hotFiles) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, `frequently changed (${count} commits in 3 months)`);\n }\n }\n } catch {\n // No git\n }\n\n // 5. Architectural pattern files — one per category (cap at 8)\n const seenCategories = new Set<string>();\n let patternCount = 0;\n for (const pattern of ARCHITECTURAL_PATTERNS) {\n if (patternCount >= 8 || selected.size >= maxFiles) break;\n if (seenCategories.has(pattern.category)) continue;\n\n const matches = await access.list(pattern.glob, {\n });\n\n if (matches.length > 0) {\n for (const match of matches) {\n if (!selected.has(match)) {\n selected.set(match, pattern.reason);\n seenCategories.add(pattern.category);\n patternCount++;\n break;\n }\n }\n }\n }\n\n // 5b. Custom patterns from project config\n for (const customGlob of projectConfig.patterns ?? []) {\n if (selected.size >= maxFiles) break;\n const matches = await access.list(customGlob, {\n });\n for (const match of matches) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"custom pattern (project config)\");\n break; // one per pattern\n }\n }\n }\n\n // 6. Test examples — diverse across file types (cap at 3)\n const testPatternGroups = [\n // JS/TS tests\n { patterns: [\"**/*.test.*\", \"**/*.spec.*\"], label: \"JS/TS test\" },\n // JVM tests\n { patterns: [\"**/*Test.kt\", \"**/*Test.java\"], label: \"JVM test\" },\n // Python tests\n { patterns: [\"**/test_*.py\", \"**/*_test.py\"], label: \"Python test\" },\n // Go tests\n { patterns: [\"**/*_test.go\"], label: \"Go test\" },\n // Swift tests\n { patterns: [\"**/*Tests.swift\", \"**/*Test.swift\"], label: \"Swift test\" },\n // Rust tests\n { patterns: [\"**/*_test.rs\"], label: \"Rust test\" },\n ];\n let testCount = 0;\n for (const group of testPatternGroups) {\n if (testCount >= 3 || selected.size >= maxFiles) break;\n const testFiles = await access.list(group.patterns, {\n });\n if (testFiles.length > 0) {\n for (const file of testFiles) {\n if (!selected.has(file)) {\n selected.set(file, `test example (${group.label})`);\n testCount++;\n break;\n }\n }\n }\n }\n\n // 7. Directory breadth — fill remaining slots with one file per top-level dir\n const sourceGlobs = SOURCE_EXTENSIONS.map((ext) => `**/*.${ext}`);\n const allSourceFiles = await access.list(sourceGlobs, {\n });\n\n const dirRepresentatives = new Map<string, string>();\n const boringFiles = /\\.(gradle|gradle\\.kts|json|toml|yaml|yml|xml|properties)$/;\n for (const file of allSourceFiles) {\n const topDir = file.split(\"/\")[0];\n if (!dirRepresentatives.has(topDir) && !boringFiles.test(file)) {\n dirRepresentatives.set(topDir, file);\n }\n }\n\n for (const [, file] of dirRepresentatives) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, \"directory representative\");\n }\n }\n\n // Read file previews\n const results: SampledFile[] = [];\n for (const [filePath, reason] of selected) {\n try {\n const full = await access.read(filePath);\n if (!full || Buffer.byteLength(full.content) > 100_000) continue;\n const lines = full.content.split(\"\\n\");\n const preview = lines.slice(0, PREVIEW_LINES).join(\"\\n\");\n\n results.push({\n path: filePath,\n preview,\n totalLines: lines.length,\n sizeBytes: Buffer.byteLength(full.content),\n reason,\n });\n } catch {\n // Skip\n }\n }\n\n return results;\n}\n\nexport async function readFullFile(\n rootDir: string,\n filePath: string\n): Promise<{ path: string; content: string; totalLines: number } | null> {\n return (await createFileAccess(rootDir)).read(filePath);\n}\n","import { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { loadDecisionStore, saveDecisionRecord, withDecisionWrite } from \"./decisions.js\";\nimport { decisionApproval, decisionAnchors, decisionContent, decisionProvenance, effectiveDecision, importLegacy, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { anchorMatches, matchingPaths } from \"../utils/paths.js\";\nimport { createFileAccess } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\nconst requestSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).default(\"prepare\"),\n reviewer: z.string().trim().min(1).max(200).optional(),\n note: z.string().trim().min(1).max(1500).optional(),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n});\nexport type ReviewDecisionInput = z.input<typeof requestSchema>;\n\nasync function reviewState(root: string, record: DecisionRecord) {\n const [headHash, workingTree, changes] = await Promise.all([\n getCurrentGitHash(root), getWorkingTree(root), getChangesWithStatus(root, record.refreshedHash),\n ]);\n const anchors = decisionAnchors(record);\n const committed = (changes ?? []).filter(c => [c.path, ...(c.previousPath ? [c.previousPath] : [])].some(file => anchors.some(anchor => anchorMatches(anchor, file))));\n const evidence = {\n baseHash: record.refreshedHash, headHash, historyAvailable: changes !== null,\n changedFiles: touchedPaths(committed), localChanges: matchingPaths(anchors, workingTree.changedFiles),\n };\n const reviewToken = createHash(\"sha256\").update(JSON.stringify({ record, evidence, workingTreeAvailable: workingTree.available })).digest(\"hex\");\n return { reviewToken, evidence, committed, workingTreeAvailable: workingTree.available };\n}\n\nasync function previews(root: string, record: DecisionRecord, state: Awaited<ReturnType<typeof reviewState>>) {\n const access = await createFileAccess(root);\n const anchors = decisionAnchors(record);\n const candidates = [...new Set([...state.evidence.changedFiles, ...state.evidence.localChanges, ...anchors,\n ...(await access.list()).filter(file => anchors.some(anchor => anchorMatches(anchor, file))),\n ])];\n const files: Array<{ path: string; preview: string; totalLines: number }> = [];\n const omittedFiles: string[] = [];\n const diffPaths: string[] = [];\n for (const file of candidates) {\n if (files.length >= 6) { omittedFiles.push(file); continue; }\n const source = await access.read(file);\n if (!source) { omittedFiles.push(file); continue; }\n files.push({ path: source.path, preview: source.content.slice(0, 2000), totalLines: source.totalLines });\n if (state.evidence.changedFiles.includes(file)) diffPaths.push(file);\n }\n let diff: string | null = null;\n let diffUnavailable: string | undefined;\n if (state.evidence.historyAvailable && diffPaths.length) {\n try {\n const { stdout } = await exec(\"git\", [\"--literal-pathspecs\", \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", record.refreshedHash, state.evidence.headHash, \"--\", ...diffPaths], { cwd: root, maxBuffer: 1024 * 1024 });\n diff = stdout.slice(0, 16000);\n if (stdout.length > diff.length) diffUnavailable = \"Diff preview was truncated; inspect the full diff before reviewing.\";\n } catch { diffUnavailable = \"Diff preview could not be read within its size bound; inspect the diff separately.\"; }\n }\n return { files, diff, diffUnavailable, omittedFiles, hint: \"Bounded source and diff previews only. Deleted, excluded, sensitive, oversized, or additional files may be omitted. Inspect relevant evidence beyond these previews before recording a verdict.\" };\n}\n\n/** Prepare first, then attest to that exact record and committed code revision. */\nexport async function reviewDecision(root: string, input: ReviewDecisionInput) {\n const parsed = requestSchema.safeParse(input);\n if (!parsed.success) return { status: \"error\", error: parsed.error.message };\n const request = parsed.data;\n const read = async () => {\n const store = await loadDecisionStore(root);\n return { ...store, record: store.records.find(record => record.id === request.id) };\n };\n if (request.action === \"prepare\") {\n const { record, diagnostics } = await read();\n if (!record) return { status: \"error\", error: `No readable decision with id \"${request.id}\"`, diagnostics };\n const state = await reviewState(root, record);\n const operativeDecision = effectiveDecision(record);\n return {\n status: \"prepared\", record, ...(operativeDecision !== record ? { operativeDecision } : {}), provenance: decisionProvenance(record), ...state, diagnostics,\n previews: await previews(root, record, state),\n hint: \"Inspect the proposed content, operativeDecision, sources, history, and code changes. A pending proposal leaves the prior accepted revision operative; accepting it replaces that revision, and retirement withdraws the entire decision including its proposal. Evidence covers both revisions' anchors. Only record acceptance or reaffirmation when the user or cited team review has authorized it. Supply that reviewer's identity, a reason, and this reviewToken. Do not invent identities or infer agreement from unchanged code. Acceptance and reaffirmation require committed anchor changes; retirement is available independently. Missing old history remains visible in the event even if a reviewer establishes a new baseline at HEAD. Saved reviews are local assertions for normal PR review, not authenticated approvals.\",\n };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) return { status: \"error\", error: \"Prepare the review first, then provide reviewToken, reviewer, and note.\" };\n return withDecisionWrite(root, async () => {\n const { record: original, diagnostics } = await read();\n if (diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before recording a review.\", diagnostics };\n if (!original) return { status: \"error\", error: `No decision with id \"${request.id}\"` };\n const state = await reviewState(root, original);\n if (state.reviewToken !== request.reviewToken) return { status: \"conflict\", error: \"The decision or code revision changed after preparation. Prepare and inspect a new review.\" };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived decisions cannot be reviewed again; create a new proposal.\" };\n const approval = decisionApproval(original);\n if (request.action === \"accept\" && approval === \"accepted\") return { status: \"error\", error: \"This decision is already accepted. Use reaffirm to record a new review.\" };\n if (request.action === \"reaffirm\" && approval !== \"accepted\") return { status: \"error\", error: \"Only accepted decisions can be reaffirmed. Review and accept this proposal or legacy record first.\" };\n const now = new Date().toISOString();\n const record = importLegacy(original, now);\n if (request.action !== \"retire\") {\n if (!record.owner || !record.sources.length) return { status: \"error\", error: \"Acceptance requires an owner and at least one source. Add them with save_decision, then prepare a new review.\" };\n if (state.evidence.headHash === \"unknown\" || !state.workingTreeAvailable || state.evidence.localChanges.length) return { status: \"error\", error: \"Acceptance requires readable Git HEAD and working-tree evidence with no uncommitted anchor changes. Commit the anchor changes and prepare a new review.\", evidence: state.evidence };\n }\n const status = request.action === \"retire\" ? \"retired\" : \"active\";\n const nextApproval = request.action === \"retire\" ? record.approval : \"accepted\";\n const refreshedHash = request.action === \"retire\" ? record.refreshedHash : state.evidence.headHash;\n const event = { kind: request.action === \"accept\" ? \"accepted\" : request.action === \"reaffirm\" ? \"reaffirmed\" : \"retired\",\n at: now, actor: request.reviewer, note: request.note, revision: record.revision, content: decisionContent(record),\n approval: nextApproval, status, refreshedHash, evidence: state.evidence,\n } as const;\n const updated: ReviewedDecisionRecord = { ...record, status, approval: nextApproval, refreshedHash, updatedAt: now, history: [...record.history, event] };\n // Detect an external Git operation during review preparation, too.\n if ((await reviewState(root, original)).reviewToken !== state.reviewToken) return { status: \"conflict\", error: \"Code changed while the review was being recorded. Prepare a new review.\" };\n await saveDecisionRecord(root, updated);\n return { status: event.kind, id: record.id, event, hint: \"Review recorded locally. Review and commit the decision file through the normal project workflow.\" };\n });\n}\n","export const BATCH_SYSTEM_PROMPT = `You are Mason, building one piece of a larger concept-to-files map via a Map-Reduce pattern.\n\nYou are seeing ONE batch of files from this project — not the whole codebase. Other batches will be processed separately and merged with yours in a final reduce step.\n\nYour job for this batch: identify the features and flows that involve the files in this batch, and return a partial concept map.\n\nRespond with ONLY a JSON object. No markdown, no explanation, no code fences. Just the raw JSON. Same shape as the full map (\\`{\"features\": {...}, \"flows\": {...}}\\`).\n\nCRITICAL: name features in PRODUCT-NATURAL language (e.g., \"home screen\", \"authentication\", \"checkout\"). Do NOT add platform or layer suffixes — call both the Android and iOS home-screen files part of a feature named \"home screen\". This is what lets the reduce step merge platform variants from other batches into a single product feature.\n\nOther rules:\n- Only include files that you see in this batch. Don't predict files in other batches.\n- Use the FULL relative file paths exactly as given.\n- Classify each feature with a \"type\": \"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, configuration, logging, adapters, build tooling). When unsure, use \"capability\".\n- Each feature should have 1–8 files from this batch — partials can be narrow.\n- Flows in a partial only make sense if all their chain steps are in this batch. Skip flows that span batches; the reduce step will assemble them.\n- Include test files in \"tests\" when present in this batch.\n- Two views of the batch: FILE HEADERS (every file in the batch, skeleton-level) and REPRESENTATIVE BODIES (deeper read of a few for grounding). Use the bodies to learn the codebase's domain vocabulary; use the headers to know which files exist.`;\n\nexport const REDUCE_SYSTEM_PROMPT = `You are Mason, merging partial concept maps from a Map-Reduce pass into a single unified map.\n\nYou will receive an array of \\`partials\\`, each produced from one batch of files. Your job: merge them into one coherent concept-to-files map for the whole project.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\`. No markdown, no preamble.\n\nMerge rules:\n- If two partials use the same feature name (e.g., both have \"home screen\"), MERGE them — combine their \\`files\\` and \\`tests\\` arrays (dedupe), and reconcile descriptions by picking the more product-natural wording or merging the two.\n- If two partials use *near-duplicate* feature names that clearly refer to the same product concept (\"home screen\" vs \"home view\", \"auth\" vs \"authentication\"), merge them under the more product-natural name.\n- If a partial split what should be one feature by platform (\"home Android\" + \"home iOS\"), merge into a single platform-agnostic feature (\"home screen\").\n- Preserve each feature's \"type\" (\"capability\" or \"infrastructure\"). When merged partials disagree on a feature's type, prefer \"capability\". If a partial omitted the type, infer it: user-facing functionality is \"capability\"; internal plumbing with no end user (DI/service wiring, config, logging, adapters) is \"infrastructure\".\n- For flows that were skipped by partials because they span batches, reconstruct them when you can see the full chain across multiple partials.\n- Every file that appears in any partial MUST end up in some feature in the unified map. Don't silently drop files.\n- Feature descriptions in the final map should be 1–2 sentences, written for a product/PM audience — concrete and specific, but free of code-level detail.\n- Each feature should have 2–8 files. If merging produces a feature with 20+ files, consider whether it should be split into sub-features.`;\n\nexport function buildBatchPrompt(\n batch: {\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): string {\n const skeletonBlocks = batch.skeletons\n .map(\n (f) =>\n `--- ${f.path} ---\\n${f.content}${f.content.length >= 500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const sampleBlocks = batch.samples\n .map(\n (f) =>\n `=== ${f.path} (deeper read) ===\\n${f.content}${f.content.length >= 1500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const batchInfo = `Batch ${Math.floor(batch.offset / batch.batchSize) + 1}: files ${batch.offset + 1}–${batch.offset + batch.skeletons.length} of ${batch.totalFiles}.`;\n\n let prompt = `${batchInfo}\n\n=== FILE HEADERS (every file in this batch) ===\n\n${skeletonBlocks}\n\n=== REPRESENTATIVE BODIES (for grounding) ===\n\n${sampleBlocks}`;\n\n if (batch.testPairs && batch.testPairs.length > 0) {\n const testBlock = batch.testPairs\n .map((p) => `${p.test} → ${p.source}`)\n .join(\"\\n\");\n prompt += `\\n\\n=== TEST → SOURCE MAPPINGS (for this batch) ===\\n\\n${testBlock}`;\n }\n\n return prompt;\n}\n\nexport function buildReducePrompt(\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge the following ${partials.length} partial concept maps into a single unified map.\n\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\nexport const REFRESH_REDUCE_SYSTEM_PROMPT = `You are Mason, merging a scoped refresh into an existing concept-to-files map.\n\nOnly a subset of the project's files was re-analyzed (they changed since the map was built). You receive the existing full map, the list of re-analyzed file paths, and partial concept maps derived from ONLY those files.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\` — the COMPLETE updated map. No markdown, no preamble.\n\nMerge rules:\n- Entries in the existing map that reference none of the re-analyzed files: copy them through UNCHANGED.\n- Entries that reference re-analyzed files: update them using the partials — adjust descriptions, add new files, drop files that moved elsewhere.\n- Merge partial features into existing features when they're the same product concept, even if named slightly differently (\"auth\" vs \"authentication\") — keep the existing name unless the new one is clearly more product-natural.\n- Features whose files were all deleted or renamed away: remove them by omitting them from your output.\n- Every file that appears in any partial MUST end up in some feature. Don't silently drop files.\n- Do not invent or alter entries for files you haven't seen.`;\n\nexport function buildRefreshReducePrompt(\n existingMap: {\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n },\n refreshedFiles: string[],\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge this scoped refresh into the existing concept map.\n\n=== EXISTING MAP ===\n${JSON.stringify(existingMap, null, 2)}\n\n=== RE-ANALYZED FILES ===\n${refreshedFiles.join(\"\\n\")}\n\n=== PARTIALS (derived from the re-analyzed files only) ===\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\n","import { withSnapshotWrite } from \"./lock.js\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\nimport { featureSchema, flowSchema } from \"./snapshot.js\";\nimport type { FeatureEntry, FlowEntry } from \"./snapshot.js\";\n\nexport interface Partial {\n batchId: string;\n offset: number;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n savedAt: string;\n}\n\nconst DIRECTORY = \".mason/partial-snapshots\";\nconst partialSchema = z.object({\n batchId: z.string().regex(/^[a-zA-Z0-9_-]+$/), offset: z.number().int().nonnegative(),\n features: z.record(featureSchema), flows: z.record(flowSchema), savedAt: z.string(),\n});\nconst scopeSchema = z.object({ files: z.array(z.string()), savedAt: z.string() });\n\nexport async function savePartial(rootDir: string, partial: Partial): Promise<void> {\n if (!/^[a-zA-Z0-9_-]+$/.test(partial.batchId)) throw new Error(`Invalid batchId: ${partial.batchId}`);\n await withSnapshotWrite(rootDir, () => writeStoreJson(rootDir, `${DIRECTORY}/${partial.batchId}.json`, partialSchema.parse(partial)));\n}\n\nexport async function loadAllPartials(rootDir: string): Promise<Partial[]> {\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, DIRECTORY)); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n const partials: Partial[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry === \"scope.json\") continue;\n const partial = partialSchema.parse(await readStoreJson(rootDir, `${DIRECTORY}/${entry}`));\n if (entry !== `${partial.batchId}.json`) throw new Error(`Invalid partial filename: ${entry}`);\n partials.push(partial);\n }\n return partials.sort((a, b) => a.offset - b.offset);\n}\n\nexport async function saveScope(rootDir: string, files: string[]): Promise<void> {\n await withSnapshotWrite(rootDir, () => writeStoreJson(rootDir, `${DIRECTORY}/scope.json`, { files, savedAt: new Date().toISOString() }));\n}\n\nexport async function loadScope(rootDir: string): Promise<string[] | null> {\n const raw = await readStoreJson(rootDir, `${DIRECTORY}/scope.json`);\n return raw === null ? null : scopeSchema.parse(raw).files;\n}\n\nexport async function clearScope(rootDir: string): Promise<void> {\n await withSnapshotWrite(rootDir, async () => {\n await fs.rm(await storePath(rootDir, `${DIRECTORY}/scope.json`), { force: true });\n });\n}\n\n/** Called only after a snapshot commit, while updateSnapshot holds the write lock. */\nexport async function clearAllPartials(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, DIRECTORY), { recursive: true, force: true });\n}\n\nexport function batchIdFor(offset: number): string {\n return `batch-${String(offset).padStart(6, \"0\")}`;\n}\n","import { startMcpServer } from \"../src/mcp/server.js\";\n\nstartMcpServer().catch((err) => {\n process.stderr.write(`Mason MCP server error: ${err}\\n`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAMlC,eAAsB,aAAgB,OAAe,KAAmC;AACtF,QAAM,SAAS,SAAS,SAAS;AACjC,MAAI,CAAC,OAAQ,QAAO,IAAI;AACxB,QAAM,QAAQ,YAAY,IAAI;AAC9B,MAAI;AAAE,WAAO,MAAM,IAAI;AAAA,EAAG,UAC1B;AACE,UAAM,SAAS,OAAO,KAAK,MAAM,EAAE,OAAO,GAAG,SAAS,EAAE;AACxD,WAAO;AACP,WAAO,WAAW,YAAY,IAAI,IAAI;AAAA,EACxC;AACF;AAhBA,IAGM;AAHN;AAAA;AAAA;AAGA,IAAM,WAAW,IAAI,kBAA0C;AAAA;AAAA;;;ACH/D,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAQnB,SAAS,QAAQ,MAAgB,SAAyB;AAC/D,QAAM,UAAU,KAAK,KAAK,SAAO,CAAC,IAAI,WAAW,GAAG,CAAC,KAAK;AAC1D,SAAO,aAAa,UAAU,SAAS,IAAI,OAAO,IAAI,UAAU,UAAU,YAAY;AACpF,UAAM,EAAE,OAAO,GAAG,eAAe,IAAI;AACrC,UAAM,YAAY,QAAQ,OAAO,MAAM,cAAc;AACrD,QAAI,UAAU,QAAW;AACvB,gBAAU,MAA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OAAO,EACP,SAAS,EACT,SAAS,8DAAyD;AAAA,MACrE,oBAAoBA,IACjB,OAAO,EACP,SAAS,EACT,SAAS,iEAA4D;AAAA,MACxE,mBAAmBA,IAChB,OAAO,EACP,SAAS,EACT,SAAS,2DAA2D;AAAA,IACzE;AAAA,IACA,OAAO,EAAE,KAAK,UAAU,cAAc,gBAAgB,oBAAoB,kBAAkB,MAAM;AAChG,YAAM,SAAS,MAAM,uBAAuB,KAAK;AAAA,QAC/C;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AACD,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC,EAAE;AAAA,IACrD;AAAA,EACF;AAEA,SAAO;AACT;AAEA,eAAsB,iBAAgC;AACpD,QAAM,SAAS,gBAAgB;AAC/B,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;;;AYtkBA,eAAe,EAAE,MAAM,CAAC,QAAQ;AAC9B,UAAQ,OAAO,MAAM,2BAA2B,GAAG;AAAA,CAAI;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["text","hash","content","commands","path","path","configPath","resolve","content","AsyncLocalStorage","path","fs","path","fs","path","fg","readdir","lstat","count","fs","path","fg","priority","index","content","fs","path","fs","reason","resolve","path","count","path","fs","path","count","hash","path","message","fg","fs","path","text","count","path","content","path","message","text","scopes","path","text","z","index","content","message","fs","path","z","record","content","path","init_drift","init_drift","createHash","z","z","fs","z","git","evidenceSchema","record","events","event","loadRepairBaseline","eventSchema","commitSchema","init_drift","fs","path","hash","fs","path","randomUUID","z","content","head","count","fs","path","createHash","fg","z","git","text","commands","index","z","execFile","promisify","fs","createHash","hash","content","reason","init_trust","fs","path","randomUUID","text","file","init_files","os","fs","randomUUID","z","message","randomUUID","z","git","verifications","text","fs","path","z","z","text","init_files","recordSchema","z","ancillaryEdits","applyEdit","ownershipEdit","completedHookOwnership","edit","init_files","parse","z","text","config","servers","index","planAutomationInstall","init_files","z","ancillaryEdits","configPath","init_files","execFile","promisify","exec","index","init_paths","message","init_types","z","index","count","init_paths","init_types","z","schema","resolve","rule","init_paths","init_types","z","schema","index","location","init_paths","init_types","path","z","index","checkSchema","previews","init_evidence","init_types","fs","path","execFile","promisify","exec","init_review","init_drift","init_evidence","MAX_FINDINGS","init_review","init_evidence","path","content","path","execFile","promisify","exec","count","path","fs","decisions","impact","relatedTests","stale","init_trust","init_drift","fs","z","isDeepStrictEqual","message","randomUUID","init_files","path","text","config_exports","fs","path","os","execFile","promisify","exec","init_config","escape","text","fs","path","createHash","execFile","promisify","resolve","exec","init_config","text","hash","hash","z","fs","path","execFile","promisify","path","path","execFile","promisify","fs","fg","promisify","execFile","count","path","execFile","promisify","exec","count","reason","createHash","execFile","promisify","z","exec","reviewToken","init_drift","init_trust","fs","z","scopeSchema","exec","promisify","execFile","path","fs","count","buildTestMap","previews","loadDecisionStore","path","analyzeImpact","upsertDecision","reviewDecision","assembleContext","automate","automationStatus","summarize","installedAutomation","setupStatus","automationFailure","setupProject","loadSetup","createConfluenceClient","saveConfluenceConfig","normalizeAtlassianBaseUrl","loadConfig","exportToConfluence","z","count","observeActivation","reviewDecision"]}
1
+ {"version":3,"sources":["../src/utils/profile.ts","../src/utils/git-read.ts","../src/audit/commands.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/utils/paths.ts","../src/utils/files.ts","../src/audit/inspection.ts","../src/audit/git.ts","../src/utils/storage.ts","../src/audit/inputs.ts","../src/audit/docs.ts","../src/audit/scope.ts","../src/utils/store-lock.ts","../src/snapshot/lock.ts","../src/test-map.ts","../src/snapshot/snapshot.ts","../src/drift/drift.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/context/lexical.ts","../src/context/trust.ts","../src/decisions/provenance.ts","../src/decisions/decisions.ts","../src/decisions/drift.ts","../src/audit/checks/decision-anchor.ts","../src/audit/checks/index.ts","../src/audit/findings.ts","../src/automation/store.ts","../src/audit/advisory-review.ts","../src/audit/audit.ts","../src/audit/repair.ts","../src/automation/evidence.ts","../src/setup/model.ts","../src/setup/launcher.ts","../src/snapshot/review.ts","../src/snapshot/trust.ts","../src/setup/files.ts","../src/automation/execution.ts","../src/automation/runtime.ts","../src/automation/hook-root.ts","../src/automation/adapters.ts","../src/setup/ownership.ts","../src/automation/install.ts","../src/setup/config.ts","../src/mcp/init.ts","../src/review/cochange.ts","../src/review/evidence/paths.ts","../src/review/evidence/types.ts","../src/review/evidence/vitest.ts","../src/review/evidence/sarif.ts","../src/review/evidence/check.ts","../src/review/evidence.ts","../src/review/review.ts","../src/mcp/onboarding.ts","../src/impact/references.ts","../src/impact/impact.ts","../src/context/assemble.ts","../src/setup/observations.ts","../src/setup/status.ts","../src/setup/setup.ts","../src/confluence/client.ts","../src/llm/config.ts","../src/confluence/url.ts","../src/confluence/renderer.ts","../src/confluence/diff.ts","../src/llm/providers.ts","../src/confluence/rewrite.ts","../src/confluence/sync.ts","../src/mcp/server.ts","../src/mcp/tools.ts","../src/audit/cli.ts","../src/audit/advisory-cli.ts","../src/analyzers/git-history.ts","../src/analyzers/base.ts","../src/analyzers/index.ts","../src/utils/git.ts","../src/mcp/sampler.ts","../src/decisions/review.ts","../src/snapshot/prompt.ts","../src/snapshot/partials.ts","../src/distribution/updates.ts","../src/distribution/state.ts","../src/distribution/path.ts","../src/distribution/bundle.ts","../src/distribution/runtime.ts","../src/distribution/install.ts","../src/distribution/sessions.ts","../bin/mason-mcp.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype Timing = { calls: number; totalMs: number };\nconst profiles = new AsyncLocalStorage<Record<string, Timing>>();\n\n/** Opt-in, invocation-local timings. Labels are fixed in source; no repository data. */\nexport async function profilePhase<T>(label: string, run: () => Promise<T>): Promise<T> {\n const phases = profiles.getStore();\n if (!phases) return run();\n const start = performance.now();\n try { return await run(); }\n finally {\n const timing = phases[label] ??= { calls: 0, totalMs: 0 };\n timing.calls++;\n timing.totalMs += performance.now() - start;\n }\n}\n\nexport async function withProfile<T>(run: () => Promise<T>, emit: (json: string) => void): Promise<T> {\n const phases: Record<string, Timing> = {};\n const start = performance.now();\n return profiles.run(phases, async () => {\n try { return await run(); }\n finally {\n emit(JSON.stringify({ kind: \"mason-profile\", version: 1, totalMs: performance.now() - start, phases }));\n }\n });\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { profilePhase } from \"./profile.js\";\n\nconst execute = promisify(execFile);\nconst commands = new Set([\"rev-parse\", \"symbolic-ref\", \"for-each-ref\", \"ls-files\", \"check-ignore\", \"status\", \"log\", \"diff\", \"ls-tree\", \"show\", \"merge-base\"]);\nexport interface GitReadOptions { cwd: string; maxBuffer?: number; timeout?: number; input?: string }\n\n/** Fixed command labels only: profiling never includes arguments or repository paths. */\nexport function execGit(args: string[], options: GitReadOptions) {\n const command = args.find(arg => !arg.startsWith(\"-\")) ?? \"other\";\n return profilePhase(\"git.\" + (commands.has(command) ? command : \"other\"), async () => {\n const { input, ...processOptions } = options;\n const operation = execute(\"git\", args, processOptions);\n if (input !== undefined) {\n operation.child.stdin!.on(\"error\", () => { /* The child exit reports a failed query. */ });\n operation.child.stdin!.end(input);\n }\n return operation;\n });\n}\n","import path from \"node:path\";\nimport type { CommandClaim } from \"./types.js\";\n\nconst TOKEN = `(?:\"[^\"\\\\n]*\"|'[^'\\\\n]*'|[^\\\\s\\x60;&|]+)`;\nconst COMMAND = new RegExp(`\\\\b(npm|pnpm|yarn)((?:[ \\\\t]+${TOKEN})*?)[ \\\\t]+run[ \\\\t]+([A-Za-z0-9:_.-]+)`, \"g\");\nconst literal = (value: string) => {\n const unquoted = value.replace(/^([\"'])(.*)\\1$/, \"$2\");\n return /[$`*?\\[\\]{}~\\\\\\x00-\\x1f]/.test(unquoted) || path.posix.isAbsolute(unquoted) ? null : unquoted;\n};\n\nfunction splitCommands(line: string): string[] {\n const parts: string[] = [];\n let quote = \"\", start = 0;\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n if (char === \"\\\\\") { i++; continue; }\n if (quote) { if (char === quote) quote = \"\"; continue; }\n if (char === \"'\" || char === '\"') { quote = char; continue; }\n if (char === \";\" || line.slice(i, i + 2) === \"&&\") {\n parts.push(line.slice(start, i));\n if (char === \"&\") i++;\n start = i + 1;\n }\n }\n parts.push(line.slice(start));\n return parts;\n}\n\n/** Deliberately small shell subset: literal cd and npm-family run invocations. */\nexport function commandClaims(line: string, lineNo: number, cwd?: string | null, shell = false): { claims: CommandClaim[]; cwd: string | null | undefined } {\n const claims: CommandClaim[] = [];\n const segments = splitCommands(line);\n for (const segment of segments) {\n const text = segment.trim().replace(/^\\$\\s+/, \"\");\n if (text.startsWith(\"#\") || /^(?:echo|printf)\\b/.test(text)) continue;\n const cd = text.match(/^cd\\s+(.+)$/);\n if (cd) {\n const directory = literal(cd[1]);\n cwd = directory === null || cwd === null || /\\s/.test(directory) && !/^[\"']/.test(cd[1])\n ? null : path.posix.join(cwd ?? \".\", directory);\n continue;\n }\n for (const match of text.matchAll(COMMAND)) {\n const flags = match[2].trim();\n const selector = flags.match(/^(?:--prefix|--dir|-C)(?:\\s+|=)(.+)$/);\n let directory = cwd;\n let scopeUnknown: string | undefined;\n if ((shell && match.index !== 0) || match[3].startsWith(\"-\")) scopeUnknown = \"Unsupported shell wrapper or options before the script.\";\n if (selector) {\n const selected = literal(selector[1]);\n directory = selected === null || cwd === null ? null : path.posix.join(cwd ?? \".\", selected);\n } else if (flags) scopeUnknown = \"Unsupported package-manager options before run: \" + flags;\n const tail = text.slice(match.index! + match[0].length).split(/\\s--(?:\\s|$)/)[0];\n if (/(?:^|\\s)(?:--workspace(?:s)?|-w|--filter|-F|--prefix|--dir|-C|--if-present)(?:\\s|=|$)/.test(tail)) {\n scopeUnknown = \"Package selection or conditional options after the script need review.\";\n }\n if (/[|()]/.test(text) || /\\b(?:pushd|popd|if|for|while)\\b/.test(text) || directory === null) {\n scopeUnknown = \"The command's working directory or shell control flow could not be resolved.\";\n }\n claims.push({ scriptName: match[3], invocation: match[0], excerpt: match[0], line: lineNo,\n ...(directory !== undefined && directory !== null ? { directory } : {}), ...(scopeUnknown ? { scopeUnknown } : {}) });\n }\n // An unresolved directory change must not leave later commands apparently scoped.\n if (/\\b(?:cd|pushd|popd)\\b/.test(text)) cwd = null;\n }\n return { claims, cwd };\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 MarkdownIt from \"markdown-it\";\nimport { commandClaims } from \"./commands.js\";\nimport 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 markdown = new MarkdownIt(\"commonmark\", { html: false });\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 const key = [claim.relativeTo ?? \"scope\", claim.path].join(\":\");\n if (!paths.has(key)) paths.set(key, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n const key = JSON.stringify([claim.scriptName, claim.directory, claim.scopeUnknown]);\n if (!commands.has(key)) commands.set(key, claim);\n };\n\n // A real Markdown parser distinguishes reference links, images and escaped\n // destinations from code examples. Ignore markers preserve source line offsets.\n const parsed = markdown.parse(lines.map((line, i) => ignored[i] ? \"\" : line).join(\"\\n\"), {});\n for (const token of parsed) {\n if (token.type !== \"inline\" || !token.map) continue;\n let line = token.map[0] + 1;\n for (const child of token.children ?? []) {\n const target = child.type === \"link_open\" ? child.attrGet(\"href\") : child.type === \"image\" ? child.attrGet(\"src\") : null;\n if (target && !/^(?:[a-z][a-z0-9+.-]*:|[\\/#~])/i.test(target)) {\n let pathname: string | null = null;\n try { pathname = decodeURIComponent(target.split(/[?#]/)[0]); } catch { /* Unsupported URL encoding. */ }\n if (pathname && !/[$*?{}<>\\\\\\x00-\\x1f]/.test(pathname)) {\n addPath({ path: pathname, line, excerpt: target, relativeTo: \"document\" });\n }\n }\n if (child.type === \"softbreak\" || child.type === \"hardbreak\") line++;\n else line += child.content.split(\"\\n\").length - 1;\n }\n }\n\n let shellCwd: string | null | undefined;\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 shellCwd = undefined;\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 const scanned = commandClaims(line, lineNo, shellCwd, true);\n shellCwd = scanned.cwd;\n for (const claim of scanned.claims) addCommand(claim);\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 match of line.matchAll(/`([^`]+)`/g)) {\n for (const claim of commandClaims(match[1], lineNo, undefined, true).claims) addCommand(claim);\n }\n for (const claim of commandClaims(line.replace(/`[^`]+`/g, \"\"), lineNo).claims) addCommand(claim);\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 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 { execGit } from \"./git-read.js\";\nimport fs from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\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 execGit([\"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 execGit([\"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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport path from \"node:path\";\nimport { execGit, type GitReadOptions } from \"../utils/git-read.js\";\nimport { SOURCE_EXTENSIONS } from \"../utils/files.js\";\n\ninterface Inspection { root: string; reads: Map<string, Promise<unknown>> }\nconst inspections = new AsyncLocalStorage<Inspection>();\n\n/** Always start fresh. In particular, final validation must not reuse initial reads. */\nexport function withRepositoryInspection<T>(root: string, run: () => Promise<T>): Promise<T> {\n return inspections.run({ root: path.resolve(root), reads: new Map() }, run);\n}\n\n/** Read observations are shared only inside an explicit inspection, never across hooks. */\nexport function inspectionRead<T>(root: string, key: string, read: () => Promise<T>): Promise<T> {\n const inspection = inspections.getStore();\n if (!inspection || inspection.root !== path.resolve(root)) return read();\n if (!inspection.reads.has(key)) {\n const pending = read();\n inspection.reads.set(key, pending);\n // A failed query must be retried, not turned into a reusable unavailable result.\n void pending.catch(() => { if (inspection.reads.get(key) === pending) inspection.reads.delete(key); });\n }\n return inspection.reads.get(key)! as Promise<T>;\n}\n\n/** Exact arguments and limits preserve each history query's semantics. */\nexport function inspectionGit(args: string[], options: GitReadOptions) {\n return inspectionRead(options.cwd, \"git:\" + JSON.stringify([args, options]), () => execGit(args, options));\n}\n\nconst sourceSpecs = SOURCE_EXTENSIONS.map(extension => `:(glob)**/*.${extension}`);\nconst docSpecs = [\":(icase,glob)**/readme.md\", \":(icase,glob)**/agents.md\", \":(icase,glob)**/claude.md\"];\nconst sourceSuffixes = new Set(SOURCE_EXTENSIONS.map(extension => \".\" + extension));\n\n/** Git still prunes ignored trees; unrelated generated files are never inventoried. */\nexport async function auditGitPaths(root: string, kind: \"documents\" | \"sources\"): Promise<string[]> {\n const shared = inspections.getStore()?.root === path.resolve(root);\n const specs = shared ? [...docSpecs, ...sourceSpecs] : kind === \"documents\" ? docSpecs : sourceSpecs;\n const limit = kind === \"documents\" ? 16 * 1024 * 1024 : 32 * 1024 * 1024;\n const { stdout } = await inspectionGit([\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\", \"--\", ...specs],\n { cwd: root, maxBuffer: shared ? 48 * 1024 * 1024 : limit, timeout: 10000 });\n const paths = [...new Set(stdout.split(\"\\0\").filter(Boolean))].filter(file => kind === \"documents\"\n ? /^(readme|agents|claude)\\.md$/i.test(path.posix.basename(file))\n // Git's *.ts also matches a file named .ts, unlike path.extname().\n : sourceSuffixes.has(file.slice(file.lastIndexOf(\".\"))));\n if (Buffer.byteLength(paths.join(\"\\0\")) > limit) throw new Error(\"Git \" + kind + \" inventory exceeds its bounded read limit.\");\n return paths.sort();\n}\n","import { inspectionGit } from \"./inspection.js\";\nimport type { CommitRef } from \"./types.js\";\n\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 inspectionGit(\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", `:(literal)${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 inspectionGit(\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n `:(literal)${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 inspectionGit(\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", `:(literal)${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 inspectionGit(\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 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 fs from \"node:fs/promises\";\nimport * as nativeFs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport fg from \"fast-glob\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { storePath } from \"../utils/storage.js\";\nimport { execGit } from \"../utils/git-read.js\";\nimport { auditGitPaths } from \"./inspection.js\";\n\nconst MAX_INPUTS = 100_000;\n\n/** Check the paths a particular audit actually reads, including their parents. */\nexport async function auditInputPath(root: string, file: string): Promise<string> {\n if (file === \".\") return fs.realpath(root);\n try { return await storePath(root, file); }\n catch (error) {\n if (error instanceof Error && error.message.startsWith(\"Symlink\")) {\n throw new Error(`Audit input contains a symbolic link: ${file}. Its evidence could not be verified.`, { cause: error });\n }\n throw error;\n }\n}\n\nexport async function readAuditInput(root: string, file: string): Promise<string | null> {\n try {\n const value = await readBoundedFile(await auditInputPath(root, file), 10 * 1024 * 1024);\n if (value === null) throw new Error(`Unreadable or oversized audit input: ${file}`);\n return value;\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return null;\n throw error;\n }\n}\n\n/** Bound relevant results and directory traversal, without counting unrelated files. */\nexport async function auditGlob(root: string, patterns: string | string[], options: {\n ignore?: string[]; onlyDirectories?: boolean; followSymbolicLinks?: boolean; label: string; select?: (file: string) => boolean;\n}): Promise<string[]> {\n if (Array.isArray(patterns) && !patterns.length) return [];\n const directories = new Set<string>();\n // fast-glob may stat a link, but must never enumerate a linked directory.\n // Validate each traversal and each selected result instead of scanning the\n // entire repository just to reject unrelated symlinks.\n const readdir = ((directory: string, opts: unknown, callback: (error: unknown, entries?: unknown) => void) => {\n const relative = path.relative(root, directory).split(path.sep).join(\"/\") || \".\";\n directories.add(relative);\n if (directories.size > MAX_INPUTS) {\n callback(new Error(`${options.label} exceeds ${MAX_INPUTS.toLocaleString(\"en-US\")} directories while inspecting ${relative}. Narrow this check's inputs.`));\n return;\n }\n auditInputPath(root, relative).then(() => {\n nativeFs.readdir(directory, opts as { withFileTypes: true }, callback as (error: NodeJS.ErrnoException | null, entries: nativeFs.Dirent[]) => void);\n }, callback);\n }) as typeof nativeFs.readdir;\n // Literal workspace patterns use lstat instead of readdir. Validate them\n // before fast-glob can silently discard a dangling link as a missing file.\n const lstat = ((file: string, callback: (error: unknown, stat?: nativeFs.Stats) => void) => {\n const relative = path.relative(root, file).split(path.sep).join(\"/\") || \".\";\n auditInputPath(root, relative).then(() => nativeFs.lstat(file, callback), callback);\n }) as typeof nativeFs.lstat;\n const stream = fg.stream(patterns, { cwd: root, ignore: options.ignore,\n onlyFiles: false, onlyDirectories: options.onlyDirectories, objectMode: true,\n followSymbolicLinks: options.followSymbolicLinks ?? true, fs: { readdir, lstat }, concurrency: 16 }) as Readable;\n const matches: string[] = [];\n try {\n for await (const value of stream) {\n const entry = value as fg.Entry;\n const file = entry.path;\n if (options.select && !options.select(file)) continue;\n await auditInputPath(root, file);\n if (!options.onlyDirectories && !entry.dirent.isFile()) continue;\n matches.push(file);\n if (matches.length > MAX_INPUTS) {\n const largest = [...matches.reduce((counts, item) => {\n const dir = item.split(\"/\")[0]; counts.set(dir, (counts.get(dir) ?? 0) + 1); return counts;\n }, new Map<string, number>())].sort((a, b) => b[1] - a[1]).slice(0, 3);\n throw new Error(`${options.label} exceeds ${MAX_INPUTS.toLocaleString(\"en-US\")} relevant paths. Largest directories: ${largest.map(([dir, count]) => `${dir} (${count})`).join(\", \")}. Narrow this check's inputs.`);\n }\n }\n } finally { stream.destroy(); }\n return matches.sort();\n}\n\n/** Git prunes ignored trees before discovery; tracked source remains visible. */\nexport async function gitSourcePaths(root: string): Promise<string[]> {\n return auditGitPaths(root, \"sources\");\n}\n\n/** Small directory batches, never a repository-wide inventory of ignored files. */\nexport async function gitIgnoredPaths(root: string, files: string[]): Promise<Set<string>> {\n if (!files.length) return new Set();\n const ignored = new Set<string>();\n for (let offset = 0; offset < files.length; offset += 1000) {\n try {\n const { stdout } = await execGit([\"check-ignore\", \"-z\", \"--stdin\"], {\n cwd: root, maxBuffer: 4 * 1024 * 1024, timeout: 10_000, input: files.slice(offset, offset + 1000).join(\"\\0\") + \"\\0\",\n });\n for (const file of stdout.split(\"\\0\").filter(Boolean)) ignored.add(file);\n } catch (error) {\n if ((error as { code?: number }).code !== 1) throw error;\n }\n }\n return ignored;\n}\n","import { execGit } from \"../utils/git-read.js\";\nimport { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport fg from \"fast-glob\";\nimport { auditGlob, auditInputPath, readAuditInput } from \"./inputs.js\";\nimport { loadProjectConfig } from \"../utils/files.js\";\nimport { auditGitPaths } from \"./inspection.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\n\n/**\n * Instruction entry points written by setup. Audit discovery is broader and\n * preserves actual filename casing; setup/teardown must not edit every README.\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 /** Directory whose instructions this document describes, not a proven shell cwd. */\n scope: string;\n kind: \"instructions\" | \"readme\";\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 dirtyDocs(resolvedRoot: string, files: string[]): Promise<Set<string>> {\n if (!files.length) return new Set();\n try {\n const dirty = new Set<string>();\n for (let offset = 0; offset < files.length; offset += 256) {\n const { stdout } = await execGit(\n [\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...files.slice(offset, offset + 256).map(file => `:(literal)${file}`)],\n { cwd: resolvedRoot, maxBuffer: 16 * 1024 * 1024, timeout: 10000 }\n );\n const entries = stdout.split(\"\\0\");\n for (let i = 0; i < entries.length; i++) {\n if (!entries[i]) continue;\n const status = entries[i].slice(0, 2);\n dirty.add(entries[i].slice(3));\n // Porcelain -z emits destination first, then the original rename/copy path.\n if (/[RC]/.test(status) && entries[i + 1]) dirty.add(entries[++i]);\n }\n }\n return dirty;\n } catch {\n return new Set(files);\n }\n}\n\n/** Readme/instruction discovery shares the exact inventory used by automation. */\nexport async function discoverDocPaths(root: string): Promise<string[]> {\n let candidates: string[] = [];\n try {\n candidates = await auditGitPaths(root, \"documents\");\n } catch (error) {\n // Outside Git we still discover documents so the audit can report Git unavailable.\n try { await execGit([\"rev-parse\", \"--git-dir\"], { cwd: root }); }\n catch { return localDocPaths(root); }\n throw error;\n }\n candidates.push(...await localDocPaths(root));\n const config = await loadProjectConfig(root);\n const excluded = [\"**/node_modules/**\", \"**/vendor/**\", \"**/dist/**\", \"**/build/**\", \"**/target/**\",\n \"**/.git/**\", \"**/.venv/**\", \"**/venv/**\", \".mason/**\", ...(config.ignore ?? [])];\n // Static patterns preserve literal metacharacters and reject selected symlinks.\n const paths: string[] = [];\n const unique = [...new Set(candidates)].sort();\n for (let offset = 0; offset < unique.length; offset += 256) {\n paths.push(...await auditGlob(root, unique.slice(offset, offset + 256).map(p => fg.escapePath(p)), {\n ignore: excluded, followSymbolicLinks: false, label: \"Documentation discovery\",\n }));\n if (paths.length > 10000) throw new Error(\"Documentation discovery exceeds 10,000 relevant files; narrow .mason/config.json ignore patterns.\");\n }\n const priority = (file: string) => {\n const index = (DOC_CANDIDATES as readonly string[]).findIndex(p => p.toLowerCase() === file.toLowerCase());\n return index < 0 ? DOC_CANDIDATES.length : index;\n };\n return paths.sort((a, b) => priority(a) - priority(b) || a.localeCompare(b));\n}\n\n/** Explicit local entry points may be ignored; preserve their real spelling. */\nasync function localDocPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n for (const dir of [\".\", \".claude\"]) {\n let entries;\n try { entries = await fs.readdir(await auditInputPath(root, dir), { withFileTypes: true }); }\n catch (error) { if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue; throw error; }\n for (const entry of entries) if (/^(?:agents|claude|readme)\\.md$/i.test(entry.name)) {\n paths.push(path.posix.join(dir, entry.name));\n }\n }\n return paths;\n}\n\nexport function documentScope(file: string): string {\n const parent = path.posix.dirname(file);\n return path.posix.basename(parent).toLowerCase() === \".claude\" ? path.posix.dirname(parent) : parent;\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n return profilePhase(\"audit.documents\", () => readDocs(resolvedRoot));\n}\n\nasync function readDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs: AuditDoc[] = [];\n const files = await discoverDocPaths(resolvedRoot);\n const dirty = await dirtyDocs(resolvedRoot, files);\n // Bound concurrent Git processes even when discovery reaches thousands of docs.\n for (let offset = 0; offset < files.length; offset += 4) {\n docs.push(...await Promise.all(files.slice(offset, offset + 4).map(async (candidate): Promise<AuditDoc> => {\n const [content, lastCommit] = await Promise.all([readAuditInput(resolvedRoot, candidate),\n profilePhase(\"audit.document-history\", () => lastCommitOf(resolvedRoot, candidate))]);\n if (content === null) throw new Error(\"Document disappeared during discovery: \" + candidate);\n return { path: candidate, content, scope: documentScope(candidate),\n kind: /^readme\\.md$/i.test(path.posix.basename(candidate)) ? \"readme\" : \"instructions\",\n lineCount: content.split(\"\\n\").length, lastCommit, dirty: dirty.has(candidate), claims: extractClaims(content) };\n })));\n }\n return docs;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { auditInputPath } from \"./inputs.js\";\nimport { documentScope } from \"./docs.js\";\nimport type { ClaimScope, PathClaim } from \"./types.js\";\n\n/** Lexical containment, before inspecting any path from documentation. */\nexport function scopedPath(directory: string, value: string): string | null {\n if (path.posix.isAbsolute(value) || value.includes(\"\\\\\") || /[\\x00-\\x1f]/.test(value)) return null;\n const resolved = path.posix.normalize(path.posix.join(directory, value));\n return resolved === \"..\" || resolved.startsWith(\"../\") ? null : resolved;\n}\n\nexport function pathClaimScope(doc: string, claim: PathClaim): ClaimScope | null {\n const directory = claim.relativeTo === \"document\" ? path.posix.dirname(doc) : documentScope(doc);\n const local = scopedPath(directory, claim.path);\n if (!local) return null;\n const candidates = claim.relativeTo === \"document\" || directory === \".\" ? [local]\n : [...new Set([local, scopedPath(\".\", claim.path)].filter((p): p is string => p !== null))];\n return { basis: claim.relativeTo === \"document\" ? \"document-link\" : directory === \".\" ? \"repository\" : \"document\",\n directory, candidates };\n}\n\n/** Missing is distinct from unreadable/unsafe; cache and checks use the same observation. */\nexport async function pathExists(root: string, file: string): Promise<boolean> {\n try { await fs.access(await auditInputPath(root, file)); return true; }\n catch (error) {\n // A child of a regular file cannot exist either. Keep symlink and access\n // failures distinct: neither establishes that a reference is missing.\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) return false;\n throw error;\n }\n}\n\nexport function gitMetadataPath(file: string): boolean {\n return file.split(\"/\").includes(\".git\");\n}\n\nexport function optionalMasonPath(file: string): boolean {\n return file.split(\"/\").includes(\".mason\");\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { storePath } from \"./storage.js\";\n\nasync function lockDiagnostic(file: string): Promise<string> {\n let reason: string;\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (!owner || typeof owner.host !== \"string\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n reason = \"Lock owner data is incomplete or malformed.\";\n } else if (owner.host !== os.hostname()) {\n reason = \"The lock belongs to another host; its process cannot be checked locally.\";\n } else {\n try { process.kill(owner.pid, 0); reason = `Local owner PID ${owner.pid} is still running.`; }\n catch (error) {\n reason = (error as NodeJS.ErrnoException).code === \"ESRCH\"\n ? `Local owner PID ${owner.pid} has exited, but lock recovery has not completed.`\n : `Local owner PID ${owner.pid} could not be checked.`;\n }\n }\n } catch (error) {\n reason = error instanceof SyntaxError ? \"Lock owner data is incomplete or malformed.\" : \"Lock owner data could not be read; the lock may have changed.\";\n }\n if (await fs.lstat(file + \".reclaim\").then(() => true, () => false)) {\n reason += \" A recovery guard also needs inspection: \" + file + \".reclaim.\";\n }\n return reason + \" Retry if a writer is active. For manual recovery, stop all Mason writers for this checkout, confirm they have exited (including other hosts), then remove only confirmed abandoned lock and lock.reclaim files. See docs/reference.md#snapshot-repairs-and-verification.\";\n}\n\n/** Cross-process lock: a killed writer's lock is reclaimed only after its local PID is gone. */\nexport async function withStoreLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000, label = \"Mason store\"): Promise<T> {\n const file = await storePath(root, directory + \"/lock\", true);\n const deadline = Date.now() + waitMs;\n let handle;\n while (!handle) {\n try {\n handle = await fs.open(file, \"wx\", 0o600);\n try { await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname() })); }\n catch (error) {\n await handle.close().catch(() => {});\n handle = undefined;\n await fs.rm(file, { force: true }).catch(() => {});\n throw error;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n // Do not steal malformed, remote, or live locks on a time-based guess.\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (owner.host === os.hostname() && Number.isInteger(owner.pid) && owner.pid > 0) {\n try { process.kill(owner.pid, 0); }\n catch (probe) {\n if ((probe as NodeJS.ErrnoException).code === \"ESRCH\") {\n // A separate guard arbitrates reclamation; recheck the owner before unlinking.\n const reclaim = file + \".reclaim\";\n let guard;\n try {\n guard = await fs.open(reclaim, \"wx\", 0o600);\n const current = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (current.pid === owner.pid && current.host === owner.host) await fs.unlink(file);\n } finally { if (guard) { await guard.close(); await fs.rm(reclaim, { force: true }); } }\n }\n }\n }\n } catch { /* Another writer may be creating/releasing/reclaiming it. */ }\n if (Date.now() >= deadline) throw new Error(label + \" is busy or its lock needs inspection: \" + file + \". \" + await lockDiagnostic(file));\n await new Promise(resolve => setTimeout(resolve, 40));\n }\n }\n try { return await run(); }\n finally { await handle.close(); await fs.unlink(file); }\n}\n","import { withStoreLock } from \"../utils/store-lock.js\";\n\n/** Each checkout has its own snapshot and partials, shared by all MCP processes. */\nexport function withSnapshotWrite<T>(root: string, run: () => Promise<T>, waitMs = 5000): Promise<T> {\n return withStoreLock(root, \".mason/local/snapshot-write\", run, waitMs, \"Snapshot store\");\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 { execGit } from \"../utils/git-read.js\";\nimport path from \"node:path\";\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 { withSnapshotWrite } from \"./lock.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { buildTestMap } from \"../test-map.js\";\n\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 /** Digest of the entry and bounded source evidence reviewed for this verdict. */\n verificationToken?: 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 /** Digest of the entry and bounded source evidence reviewed for this verdict. */\n verificationToken?: 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(), verificationToken: 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\n/** Read and commit under one cross-process lock; a null snapshot means no write. */\nexport async function updateSnapshot<T>(rootDir: string, update: (current: Snapshot | null) => Promise<{\n snapshot: Snapshot | null;\n result: T;\n afterSave?: () => Promise<void>;\n}>): Promise<T> {\n return withSnapshotWrite(rootDir, async () => {\n const change = await update(await loadSnapshot(rootDir));\n if (change.snapshot) {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(change.snapshot));\n await change.afterSave?.();\n }\n return change.result;\n });\n}\n\nexport async function getCurrentGitHash(rootDir: string): Promise<string> {\n try {\n const { stdout } = await execGit([\"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 { execGit } from \"../utils/git-read.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\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\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 execGit([\"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 execGit([\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n execGit([\"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 execGit(\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 execGit([\"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 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\" | IssueType;\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 is absent from a resolved manifest). \"likely\" is\n * retained for older reports. Inferred scope and speculative omissions are\n * advisory; even a certain mismatch needs semantic review before repair.\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 interface ClaimScope {\n basis: \"repository\" | \"document\" | \"document-link\" | \"explicit\";\n directory: string;\n /** Exact repository-relative paths/manifests considered by the check. */\n candidates: string[];\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 resolvedPath?: string;\n scope?: ClaimScope;\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 scope?: ClaimScope;\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 require judgment and never drive the ordinary audit exit code.\n * Historical advisories require a separate review. Explicitly recheckable\n * candidates can cease to be detected without asserting semantic approval.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n resolution?: \"recheck\";\n}\n\nexport interface AuditDocInfo {\n path: string;\n scope?: string;\n kind?: \"instructions\" | \"readme\";\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 /** Additive assessment status; original advisory evidence remains intact. */\n advisoryReviews?: import(\"./advisory-review.js\").AdvisoryReviewSummary[];\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n /** Markdown links resolve against the physical document directory. */\n relativeTo?: \"document\";\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 /** A literal cd/directory flag, relative to the document's assumed cwd. */\n directory?: string;\n scopeUnknown?: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport { gitMetadataPath, optionalMasonPath, pathClaimScope, pathExists } from \"../scope.js\";\nimport type { Evidence } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Prove removed references only when their scope is resolved. */\nexport async function checkDeletedReferences(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map((changes ?? []).filter(c => c.status === \"renamed\" && c.previousPath)\n .map(c => [c.previousPath!, c.path]));\n for (const claim of doc.claims.paths) {\n const scope = pathClaimScope(doc.path, claim);\n if (!scope) {\n result.skipped.push({ check: \"deleted-reference\", doc: doc.path,\n reason: `Reference ${claim.excerpt} is outside the repository or has an unsupported path.` });\n continue;\n }\n if (scope.candidates.some(optionalMasonPath)) continue;\n if (scope.candidates.some(gitMetadataPath)) {\n result.skipped.push({ check: \"deleted-reference\", doc: doc.path,\n reason: `Reference ${claim.path} names Git metadata, whose layout varies between checkouts; it was not verified as a repository file.` });\n continue;\n }\n if ((await Promise.all(scope.candidates.map(file => pathExists(ctx.root, file)))).some(Boolean)) continue;\n\n const candidates = await Promise.all(scope.candidates.map(async file => ({ file,\n tracked: await lastCommitOf(ctx.root, file), parent: await pathExists(ctx.root, path.posix.dirname(file)) })));\n const candidate = candidates.find(c => c.tracked || renames.has(c.file)) ?? candidates.find(c => c.parent);\n // No history/parent for a bare path is usually an illustrative example.\n if (!candidate && claim.relativeTo !== \"document\") continue;\n const resolvedPath = candidate?.file ?? scope.candidates[0];\n const renamedTo = renames.get(resolvedPath) ?? null;\n const deletedInCommit = candidate?.tracked && !renamedTo ? await deletingCommitOf(ctx.root, resolvedPath) : null;\n const evidence: Evidence = { kind: \"missing-path\", claimed: claim.path, resolvedPath, scope,\n renamedTo, deletedInCommit, everTracked: !!candidate?.tracked || !!renamedTo, parentDirExists: candidate?.parent ?? false };\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const message = renamedTo ? `\\`${resolvedPath}\\` was renamed to \\`${renamedTo}\\``\n : `\\`${resolvedPath}\\` does not exist` + (deletedInCommit\n ? ` – deleted in ${deletedInCommit.hash.slice(0, 7)} \"${deletedInCommit.subject}\" (${deletedInCommit.date.slice(0, 10)})` : \"\");\n if (scope.basis !== \"document\" && (renamedTo || candidate?.tracked)) {\n result.issues.push({ type: \"deleted-reference\", message, anchor, confidence: \"certain\", evidence });\n } else {\n result.advisories.push({ resolution: \"recheck\", type: \"deleted-reference\", message: message + (scope.basis === \"document\"\n ? \"; the bare path's document/repository scope needs review.\"\n : \"; no tracked history establishes it as a required file. Review for a typo, generated output, or example.\"), anchor, evidence });\n }\n }\n }\n return result;\n}\n","import { inspectionRead } from \"../inspection.js\";\nimport fg from \"fast-glob\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { loadProjectConfig, SOURCE_IGNORE } from \"../../utils/files.js\";\nimport { auditGlob, auditInputPath, gitIgnoredPaths, gitSourcePaths } from \"../inputs.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\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = moduleDocumentation(ctx.docs);\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.advisories.push({\n resolution: \"recheck\",\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in the discovered documentation; review whether it needs documenting`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\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/** Nested documentation establishes a directory is documented without requiring\n * every package README to repeat its full repository path. */\nexport function moduleDocumentation(docs: Array<{ path: string; content: string }>): string {\n return docs.map(doc => doc.content + \"\\n\" + (path.posix.dirname(doc.path) === \".\" ? \"\" : path.posix.dirname(doc.path) + \"/\")).join(\"\\n\");\n}\n\n/** Shared dependency witness: cache exactly the module candidates the audit observes. */\nexport function moduleCandidates(root: string, combinedDocs: string) {\n return inspectionRead(root, \"modules:\" + combinedDocs, () => collectModuleCandidates(root, combinedDocs));\n}\n\nasync function collectModuleCandidates(root: string, combinedDocs: string) {\n const [config, sourcePaths] = await Promise.all([loadProjectConfig(root), gitSourcePaths(root)]);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n const sources = sourcePaths.filter(file => !file.split(\"/\").some(part => part.startsWith(\".\")));\n const listSubdirs = async (parents: string[]): Promise<Map<string, string[]>> => {\n const byParent = new Map<string, string[]>();\n // Gather one level before asking Git about ignores, with bounded directory reads.\n for (let offset = 0; offset < parents.length; offset += 16) {\n await Promise.all(parents.slice(offset, offset + 16).map(async dir => {\n const entries = await fs.readdir(await auditInputPath(root, dir), { withFileTypes: true });\n // An unrelated directory alias is not a source module. Selected links\n // still pass through auditGlob's path and parent validation.\n const dirs = entries.filter(entry => (entry.isDirectory() || entry.isSymbolicLink()\n && sources.some(file => file.startsWith(path.posix.join(dir, entry.name) + \"/\")))\n && !entry.name.startsWith(\".\") && !DIR_DENYLIST.has(entry.name))\n .map(entry => path.posix.join(dir, entry.name));\n byParent.set(dir, dirs);\n }));\n }\n const ignored = await gitIgnoredPaths(root, [...byParent.values()].flat());\n const result = new Map<string, string[]>();\n for (const dir of parents) {\n // An ignore rule does not remove already tracked source from the audit.\n const visible = new Set(byParent.get(dir)!.filter(candidate => !ignored.has(candidate)\n || sources.some(file => file.startsWith(candidate + \"/\"))));\n result.set(dir, (await auditGlob(root, dir === \".\" ? \"*\" : `${fg.escapePath(dir)}/*`, {\n ignore, onlyDirectories: true, label: \"Module directory discovery\", select: file => visible.has(file),\n })).map(file => path.posix.basename(file)));\n }\n return result;\n };\n const countSourceFiles = async (dir: string): Promise<number> => {\n const files = sources.filter(file => file.startsWith(dir + \"/\"));\n let count = 0;\n // Literal path batches avoid compiling one enormous glob pattern set in a\n // genuinely large source module. Apply exclusions before counting results.\n for (let offset = 0; offset < files.length; offset += 256) {\n count += (await auditGlob(root, files.slice(offset, offset + 256).map(file => fg.escapePath(file)), {\n ignore, followSymbolicLinks: false, label: `Source discovery in ${dir}`,\n })).length;\n if (count > 100000) throw new Error(`Source discovery in ${dir} exceeds 100,000 relevant files. Exclude generated source with .mason/config.json ignore patterns or narrow this audit's checks.`);\n }\n return count;\n };\n const candidates: Array<{ dir: string; sourceFileCount: number }> = [];\n const topDirs = (await listSubdirs([\".\"])).get(\".\")!;\n const nested = await listSubdirs(topDirs.filter(dir => isMentioned(combinedDocs, dir)));\n for (const topDir of topDirs) {\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(topDir);\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 = nested.get(topDir)!;\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(`${topDir}/${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 path from \"node:path\";\nimport { documentScope } from \"../docs.js\";\nimport { auditGlob, readAuditInput } from \"../inputs.js\";\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 countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readAuditInput(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 readAuditInput(root, \"package.json\");\n if (pkgRaw !== null) {\n let globs: string[] = [];\n try {\n const pkg = JSON.parse(pkgRaw);\n globs = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n } catch {\n // Malformed package.json — nothing provable here.\n }\n if (globs.length > 0) {\n const matched = await auditGlob(root,\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { ignore: [\"**/node_modules/**\"], label: \"npm workspace discovery\" }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n\n const pnpmRaw = await readAuditInput(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 auditGlob(root,\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { ignore: [\"**/node_modules/**\"], label: \"pnpm workspace discovery\" }\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 readAuditInput(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 auditGlob(root, `${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n ignore: [\"**/target/**\"],\n label: \"Cargo workspace discovery\",\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readAuditInput(root, path.posix.join(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\n/** Nested documents cannot assert the root workspace's count implicitly. */\nexport async function resolveDocCountSource(root: string, doc: string, claim: CountClaim): Promise<CountSource | null> {\n const scope = documentScope(doc);\n const source = await resolveCountSource(path.join(root, scope), claim);\n if (!source || scope === \".\") return source;\n return { ...source, countedFrom: scope + \"/\" + source.countedFrom,\n members: source.members.map(member => scope + \"/\" + member) };\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 resolveDocCountSource(ctx.root, doc.path, 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 path from \"node:path\";\nimport { auditGlob, readAuditInput } from \"../inputs.js\";\nimport { documentScope } from \"../docs.js\";\nimport { scopedPath } from \"../scope.js\";\nimport type { ClaimScope, CommandClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\nfunction scriptsOf(raw: string): string[] | null {\n try {\n const pkg = JSON.parse(raw);\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) return null;\n if (pkg.scripts === undefined) return [];\n return pkg.scripts && typeof pkg.scripts === \"object\" && !Array.isArray(pkg.scripts)\n && Object.values(pkg.scripts).every(value => typeof value === \"string\") ? Object.keys(pkg.scripts) : null;\n } catch { return null; }\n}\n\ninterface Resolution {\n doc: string; claim: CommandClaim; scope: ClaimScope; manifest: string | null;\n scripts: string[]; elsewhere: string[]; problem?: string;\n}\n\n/** Shared dependency resolver: the cache records every manifest actually consulted. */\nexport async function commandInputs(root: string, docs: Array<{ path: string; claims: { commands: CommandClaim[] } }>) {\n const contents = new Map<string, string | null>();\n const read = async (file: string) => {\n if (!contents.has(file)) contents.set(file, await readAuditInput(root, file));\n return contents.get(file)!;\n };\n await read(\"package.json\");\n let inventory: string[] | undefined;\n const resolutions: Resolution[] = [];\n for (const doc of docs) for (const claim of doc.claims.commands) {\n const base = documentScope(doc.path);\n const directory = scopedPath(base, claim.directory ?? \".\");\n const scope: ClaimScope = { basis: claim.directory === undefined ? \"document\" : \"explicit\",\n directory: directory ?? base, candidates: [] };\n const resolution: Resolution = { doc: doc.path, claim, scope, manifest: null, scripts: [], elsewhere: [] };\n resolutions.push(resolution);\n if (claim.scopeUnknown || directory === null) {\n resolution.problem = claim.scopeUnknown ?? \"The command's directory leaves the repository.\";\n continue;\n }\n let cursor = directory;\n while (true) {\n const manifest = path.posix.join(cursor, \"package.json\");\n scope.candidates.push(manifest);\n const raw = await read(manifest);\n if (raw !== null) {\n resolution.manifest = manifest;\n const scripts = scriptsOf(raw);\n if (scripts === null) resolution.problem = \"Invalid package manifest: \" + manifest;\n else resolution.scripts = scripts;\n break;\n }\n // An explicit directory is a declared execution scope, never silently use a sibling.\n if (claim.directory !== undefined || cursor === \".\") break;\n cursor = path.posix.dirname(cursor);\n }\n if (!resolution.manifest && !resolution.problem) {\n resolution.problem = `No package.json for the command's scope (${directory}).`;\n }\n if (resolution.problem || resolution.scripts.includes(claim.scriptName) || claim.directory !== undefined) continue;\n inventory ??= await commandManifests(root);\n for (const manifest of [...new Set([\"package.json\", ...inventory])].sort()) {\n if (scope.candidates.includes(manifest)) continue;\n scope.candidates.push(manifest);\n const raw = await read(manifest);\n if (raw === null) continue;\n const scripts = scriptsOf(raw);\n if (scripts === null) resolution.problem = \"Cannot establish script availability: invalid manifest \" + manifest;\n else if (scripts.includes(claim.scriptName)) resolution.elsewhere.push(manifest);\n }\n }\n return { manifests: [...contents].sort(([a], [b]) => a.localeCompare(b)), resolutions };\n}\n\nexport async function checkDeadCommands(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n const { resolutions } = await commandInputs(ctx.root, ctx.docs);\n for (const { doc, claim, scope, scripts, elsewhere, problem, manifest } of resolutions) {\n if (problem) {\n result.skipped.push({ check: \"dead-command\", doc, reason: problem });\n continue;\n }\n if (scripts.includes(claim.scriptName)) continue;\n const evidence = { kind: \"missing-script\" as const, scriptName: claim.scriptName, invocation: claim.invocation,\n manifestsChecked: scope.candidates, availableScripts: scripts.slice(0, AVAILABLE_SCRIPTS_CAP), scope };\n const anchor = { doc, line: claim.line, excerpt: claim.excerpt };\n const message = `\\`${claim.invocation}\\` names script \"${claim.scriptName}\", which is absent from ${manifest}`;\n // Nested docs imply a package, but may describe commands run from another cwd.\n const certain = documentScope(doc) === \".\" && (scope.basis === \"explicit\" || !elsewhere.length);\n if (certain) result.issues.push({ type: \"dead-command\", message, anchor, confidence: \"certain\", evidence });\n else result.advisories.push({ resolution: \"recheck\", type: \"dead-command\", message: message + (elsewhere.length\n ? `; it exists in ${elsewhere.join(\", \")}. Clarify the intended working directory.`\n : \"; the intended working directory needs review.\"), anchor, evidence });\n }\n return result;\n}\n\n/** Ignored workspace manifests may still be explicit command dependencies. */\nexport function commandManifests(root: string): Promise<string[]> {\n return auditGlob(root, \"**/package.json\", {\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \".mason/reports/**\", \"package.json\"],\n label: \"Command manifest discovery\",\n });\n}\n","import { execGit } from \"../utils/git-read.js\";\nimport type { RangeCommits } from \"./git.js\";\n\nasync function git(root: string, args: string[]) {\n return (await execGit(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 { documentScope } from \"../docs.js\";\nimport { releaseMetadataOnly } from \"../release-metadata.js\";\nimport { commitsTouchingSince } from \"../git.js\";\nimport { inspectionGit } from \"../inspection.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MANIFEST_COMMITS_CAP = 10;\n\n/** A relevance filter, not semantic validation of a dependency or its version. */\nexport function hasDependencyContent(content: string): boolean {\n const text = content.replace(/<!-- mason:start -->[\\s\\S]*?<!-- mason:end -->/g, \"\")\n .replace(/<!--[\\s\\S]*?-->/g, \"\");\n return /\\b(?:dependenc(?:y|ies)|librar(?:y|ies)|frameworks?|tech(?:nology)? stack|prerequisites|requirements)\\b/i.test(text)\n || /\\b(?:package\\.json|build\\.gradle(?:\\.kts)?|settings\\.gradle(?:\\.kts)?|libs\\.versions\\.toml|Cargo\\.toml|go\\.mod|pyproject\\.toml|requirements\\.txt|Gemfile|composer\\.json)\\b/i.test(text)\n || /\\b(?:node(?:\\.js)?|npm|pnpm|yarn|bun|deno|python|ruby|rust|go|java|jdk|kotlin|gradle|swift|php|react|vue|angular|compose|ktor|room)\\s*(?:version\\s*)?[`*:=>~^v\\s-]*\\d+(?:\\.\\d+)*\\b/i.test(text)\n || /\\b(?:npm|pnpm|yarn|pip3?|cargo|gem|composer)\\s+(?:install|add|require)\\b/i.test(text);\n}\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/** Share exact dependency scope with persisted advisory assessments. */\nexport function manifestPathspecs(doc: string): string[] {\n const scope = documentScope(doc);\n if (scope === \".\") return MANIFEST_PATHSPECS;\n const escaped = scope.replace(/[\\\\*?\\[\\]]/g, \"\\\\$&\");\n return MANIFEST_PATHSPECS.map(spec => spec.startsWith(\":(glob)\")\n ? \":(glob)\" + escaped + \"/\" + spec.slice(\":(glob)\".length) : \":(literal)\" + scope + \"/\" + spec);\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 // Local edits must not erase the dependency evidence we are preparing to\n // retain. Inspect the committed document for dirty inputs, including setup.\n let content = doc.content;\n if (doc.dirty) {\n try {\n content = (await inspectionGit([\"show\", `${doc.lastCommit.hash}:${doc.path}`],\n { cwd: ctx.root, maxBuffer: 10 * 1024 * 1024, timeout: 10000 })).stdout;\n } catch {\n result.skipped.push({ check: \"deps-changed\", doc: doc.path, reason: `${doc.path}: committed dependency content is unavailable` });\n continue;\n }\n }\n if (!hasDependencyContent(content)) continue;\n\n const range = await commitsTouchingSince(\n ctx.root,\n doc.lastCommit.hash,\n manifestPathspecs(doc.path)\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\";\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","export type Freshness = \"current\" | \"changed\" | \"unknown\";\nexport interface TrustState {\n freshness: Freshness;\n verification: \"unverified\" | \"passed\" | \"failed\" | \"stale\" | \"unknown\";\n /** Historical map verdict, retained even when its evidence no longer applies. */\n recordedVerdict?: \"passed\" | \"failed\";\n verifiedAt?: string;\n verifiedHash?: string;\n reasons: string[];\n}\n\nexport function assessTrust(entry: { verifiedAt?: string; verifiedHash?: string; verificationFailed?: boolean; verificationNote?: string }, freshness: Freshness): TrustState {\n const verification = entry.verificationFailed ? \"failed\" : entry.verifiedAt ? \"passed\" : \"unverified\";\n const reasons: string[] = [];\n if (freshness === \"unknown\") reasons.push(\"Anchors, history, or working-tree evidence are unavailable; verify before relying on this entry.\");\n if (freshness === \"changed\") reasons.push(\"Anchored files changed; verify against current code before relying on this entry.\");\n if (verification === \"failed\") reasons.push(`Verification failed: ${entry.verificationNote ?? \"re-map this entry before relying on it\"}`);\n if (verification === \"unverified\") reasons.push(\"No correctness verification has been recorded.\");\n return { freshness, verification, verifiedAt: entry.verifiedAt, verifiedHash: entry.verifiedHash, reasons };\n}\n\nexport function trustHint(states: TrustState[]): string {\n const parts: string[] = [];\n if (states.some(s => s.verification === \"failed\" || s.recordedVerdict === \"failed\")) parts.push(\"Verification failed for returned entries; do not rely on those descriptions until corrected.\");\n if (states.some(s => s.verification === \"stale\")) parts.push(\"Recorded verification evidence changed; use verify_snapshot and review the current evidence before reusing those verdicts.\");\n if (states.some(s => s.verification === \"unknown\")) parts.push(\"Recorded verification evidence cannot be confirmed; inspect the files and obtain a fresh review before relying on those verdicts.\");\n if (states.some(s => s.freshness === \"unknown\")) parts.push(\"Freshness is unknown for some returned entries; inspect their files before relying on them.\");\n if (states.some(s => s.freshness === \"changed\")) parts.push(\"Some returned entries have changed files, including possible local edits; verify against the current code.\");\n if (!parts.length) parts.push(\"No changes detected in the returned anchors. This does not prove the descriptions are correct.\");\n if (states.some(s => s.verification === \"unverified\")) parts.push(\"Some entries have never been verified; read their evidence or use verify_snapshot for map descriptions.\");\n return parts.join(\" \");\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 fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\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_RECOMMENDED_CHARS = 1500;\nexport const BODY_MAX_CHARS = 2500;\nexport const MAX_ACTIVE_DECISIONS = 150;\n\n// Share validation with MCP so rejected tool calls include the actual length.\nconst boundedText = (field: string, max: number, hint: string) => z.string({\n errorMap: (issue, ctx) => ({ message: issue.code === \"too_big\"\n ? `${field} has ${ctx.data.length} characters; maximum is ${max} (${ctx.data.length - max} over). ${hint}`\n : ctx.defaultError }),\n}).trim().min(1, `${field} must be non-empty`).max(max);\n\nexport const decisionTitleSchema = boundedText(\"title\", TITLE_MAX_CHARS, \"Tighten it to a specific headline.\");\nexport const decisionBodySchema = boundedText(\"body\", BODY_MAX_CHARS,\n `Aim for ${BODY_RECOMMENDED_CHARS} characters or fewer. Preserve the rule, reason, and exceptions; put supporting references in sources.`);\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: base slug ≤60 chars, ending at a word\n * boundary when possible. A single longer word is cut to fit.\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 fullSlug = title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n let slug = fullSlug.slice(0, 60);\n if (fullSlug.length > 60 && fullSlug[60] !== \"-\") {\n const boundary = slug.lastIndexOf(\"-\");\n if (boundary > 0) slug = slug.slice(0, boundary);\n }\n slug = slug.replace(/-+$/, \"\") || \"decision\";\n if (!existingIds.has(slug)) return slug;\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 parsedTitle = decisionTitleSchema.safeParse(input.title), parsedBody = decisionBodySchema.safeParse(input.body);\n if (!parsedTitle.success) return { status: \"error\", error: parsedTitle.error.issues[0].message };\n if (!parsedBody.success) return { status: \"error\", error: parsedBody.error.issues[0].message };\n const title = parsedTitle.data, body = parsedBody.data;\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 if (body.length > BODY_RECOMMENDED_CHARS) warnings.push(`body has ${body.length} characters, above the recommended ${BODY_RECOMMENDED_CHARS}; matching context and hooks include it in full. Keep the rule, reason, and exceptions concise; use sources for supporting references.`);\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\";\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 { 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 { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { AuditIssue, AuditAdvisory } from \"./types.js\";\nexport type Finding = AuditIssue | AuditAdvisory;\nexport const digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\nexport const checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nexport const 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 scopeSchema = z.object({ basis: z.enum([\"repository\", \"document\", \"document-link\", \"explicit\"]),\n directory: z.string(), candidates: z.array(z.string()) });\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(), resolvedPath: z.string().optional(), scope: scopeSchema.optional() }),\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()), scope: scopeSchema.optional() }),\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 });\nexport const issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nexport const advisorySchema = findingSchema.extend({ type: checkSchema, resolution: z.literal(\"recheck\").optional() });\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});\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.resolvedPath && e.resolvedPath !== e.claimed ? [e.claimed, e.resolvedPath] : 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.scope && e.scope.directory !== \".\" ? [e.scriptName, e.scope.directory] : 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}\n","import { z } from \"zod\";\nimport { withStoreLock } from \"../utils/store-lock.js\";\n\nexport const hostSchema = z.enum([\"claude\", \"codex\"]);\nexport type Host = z.infer<typeof hostSchema>;\nexport const events = [\"session_start\", \"turn_start\", \"before_tool\", \"after_tool\", \"task_end\"] as const;\nexport type Event = typeof events[number];\nexport const stateSchema = z.object({\n version: z.literal(1), root: z.string(), gitDir: z.string(), branch: z.string(),\n baselines: z.array(z.object({ path: z.string(), at: z.string(), event: z.string(), fingerprint: z.string() })).max(128),\n sessions: z.record(z.object({\n host: hostSchema, seen: z.string().nullable(), continued: z.boolean(),\n initialIssues: z.array(z.string()), initialDocs: z.record(z.string().nullable()),\n lastUsed: z.string(), mutationObserved: z.boolean(),\n pending: z.record(z.string()), coverageGaps: z.array(z.string()),\n events: z.record(z.object({ at: z.string(), count: z.number().int().positive() })),\n })),\n updatedAt: z.string(), fingerprint: z.string().nullable(),\n latest: z.string().nullable(),\n analysis: z.object({ id: z.string(), fingerprint: z.string(), completedAt: z.number(), path: z.string() }).optional(),\n});\nexport type State = z.infer<typeof stateSchema>;\nexport function parseState(raw: unknown): State {\n try { return stateSchema.parse(raw); }\n catch (error) { throw new Error(\"Invalid automation state; original evidence was retained.\", { cause: error }); }\n}\n\n/** Preserve the automation lock location and diagnostics for existing callers. */\nexport function withLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000): Promise<T> {\n return withStoreLock(root, directory, run, waitMs, \"Automation\");\n}\n","import { inspectionGit } from \"./inspection.js\";\nimport { execGit } from \"../utils/git-read.js\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { advisorySchema, digest, findingId, type Finding } from \"./findings.js\";\nimport { manifestPathspecs } from \"./checks/deps-changed.js\";\nimport { readAuditInput } from \"./inputs.js\";\nimport { pathExists } from \"./scope.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { withLock } from \"../automation/store.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst git = async (root: string, ...args: string[]) => (await (\n [\"log\", \"ls-tree\", \"ls-files\", \"merge-base\"].includes(args[0]) ? inspectionGit : execGit\n)(args, { cwd: root, timeout: 10_000, maxBuffer: 8 * 1024 * 1024 })).stdout;\nconst hashSchema = z.string().regex(/^[a-f0-9]{64}$/);\nconst commitSchema = z.string().regex(/^[a-f0-9]{40,64}$/);\nconst evidenceSchema = z.object({\n head: commitSchema, fingerprint: hashSchema, scope: z.array(z.string()).min(1).max(1000),\n tree: z.string().max(2 * 1024 * 1024), lastScopeCommit: commitSchema,\n paths: z.array(z.object({ path: z.string(), exists: z.boolean() })).max(1000),\n});\nconst eventSchema = z.object({\n at: z.string().datetime(), reviewer: z.string().trim().min(1).max(200), note: z.string().trim().min(1).max(2500),\n outcome: z.enum([\"addressed\", \"inapplicable\", \"deferred\"]),\n finding: advisorySchema.refine(finding => finding.evidence.kind !== \"decision-anchor\", \"Decision findings use decision reviews\"), evidence: evidenceSchema,\n});\nconst recordSchema = z.object({ version: z.literal(1), id: hashSchema, events: z.array(eventSchema).min(1).max(200), digest: hashSchema });\ntype ReviewRecord = z.infer<typeof recordSchema>;\nexport const reviewSummarySchema = z.object({\n id: hashSchema, status: z.enum([\"current\", \"reopened\", \"deferred\", \"unverified\"]), reason: z.string(),\n recordPath: z.string().optional(), reviewer: z.string().optional(), note: z.string().optional(),\n outcome: z.enum([\"addressed\", \"inapplicable\", \"deferred\", \"accepted\", \"reaffirmed\", \"retired\"]).optional(),\n reviewedHead: z.string().optional(),\n});\nexport type AdvisoryReviewSummary = z.infer<typeof reviewSummarySchema>;\nexport const advisoryReviewRequest = z.object({\n baselinePath: z.string().min(1), findingId: hashSchema,\n action: z.enum([\"prepare\", \"addressed\", \"inapplicable\", \"deferred\"]).default(\"prepare\"),\n reviewer: eventSchema.shape.reviewer.optional(), note: eventSchema.shape.note.optional(), reviewToken: hashSchema.optional(),\n});\nexport type AdvisoryReviewInput = z.input<typeof advisoryReviewRequest>;\nconst recordPath = (id: string) => `.mason/reviews/advisories/${hashSchema.parse(id)}.json`;\n\nasync function readRecord(root: string, id: string): Promise<ReviewRecord | null> {\n const raw = await readStoreJson(root, recordPath(id));\n if (raw === null) return null;\n const record = recordSchema.parse(raw);\n const { digest: stored, ...payload } = record;\n if (record.id !== id || digest(payload) !== stored || record.events.some(event => findingId(event.finding as Finding) !== id\n || event.evidence.fingerprint !== digest([event.evidence.scope, event.evidence.tree, event.evidence.lastScopeCommit, event.evidence.paths]))) {\n throw new Error(\"Advisory review record is inconsistent or modified; inspect its history.\");\n }\n return record;\n}\n\nfunction scopes(finding: Finding): string[] {\n const files = [finding.anchor.doc], e = finding.evidence;\n if (e.kind === \"decision-anchor\") throw new Error(\"Use review_decision for decision acceptance, reaffirmation or retirement.\");\n if (e.kind === \"doc-behind-manifests\") return [`:(literal)${finding.anchor.doc}`, ...manifestPathspecs(finding.anchor.doc)];\n if (e.kind === \"missing-path\") files.push(...(e.scope?.candidates ?? [e.resolvedPath ?? e.claimed]));\n else if (e.kind === \"missing-script\") files.push(...e.manifestsChecked, ...(e.scope?.candidates ?? []));\n else if (e.kind === \"unmentioned-dir\") files.push(e.dir, ...e.checkedDocs);\n else throw new Error(\"This advisory has no supported review scope.\");\n return [...new Set(files)].map(file => {\n if (normalizeRepoPath(file) !== file) throw new Error(\"Advisory contains an invalid scoped path: \" + file);\n return `:(literal)${file}`;\n }).sort();\n}\n\n/** Committed, scoped Git evidence survives unrelated and review-record-only commits. */\nasync function reviewEvidence(root: string, finding: Finding) {\n if (normalizeRepoPath(finding.anchor.doc) !== finding.anchor.doc) throw new Error(\"Invalid advisory document path.\");\n const scope = scopes(finding);\n const head = (await git(root, \"rev-parse\", \"HEAD\")).trim();\n const tracked = (await git(root, \"ls-files\", \"--cached\", \"-z\", \"--\", ...scope)).split(\"\\0\").filter(Boolean);\n if (tracked.length > 20_000) throw new Error(\"Advisory scope exceeds 20,000 tracked files.\");\n const [tree, status, lastScopeCommit, document] = await Promise.all([\n tracked.length ? git(root, \"ls-tree\", \"-r\", \"-z\", \"HEAD\", \"--\", ...tracked.map(file => `:(literal)${file}`)) : \"\",\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...scope),\n git(root, \"log\", \"-1\", \"--format=%H\", \"HEAD\", \"--\", ...scope).then(value => value.trim()),\n readAuditInput(root, finding.anchor.doc),\n ]);\n if (!document?.trim()) throw new Error(\"Original advisory document is missing, empty or unreadable.\");\n if (tree.length > 2 * 1024 * 1024 || tree.split(\"\\0\").length > 20_000) throw new Error(\"Advisory scope is too large for a complete review; narrow the documentation scope.\");\n // Reject symlinks rather than trusting a blob that describes an external target.\n for (const entry of tree.split(\"\\0\").filter(Boolean)) {\n const tab = entry.indexOf(\"\\t\"), file = entry.slice(tab + 1);\n if (entry.startsWith(\"120000 \") || entry.startsWith(\"160000 \")) throw new Error(\"Symlink or submodule in advisory review scope: \" + file);\n await storePath(root, file);\n }\n // Path checks observe presence even for explicitly documented ignored\n // outputs. Git alone cannot detect those appearing or disappearing.\n const paths = finding.evidence.kind === \"missing-path\" ? await Promise.all(\n (finding.evidence.scope?.candidates ?? [finding.evidence.resolvedPath ?? finding.evidence.claimed])\n .map(async file => ({ path: file, exists: await pathExists(root, file) }))) : [];\n let dirty = status.length > 0;\n if (finding.evidence.kind === \"missing-script\") {\n for (const file of [...finding.evidence.manifestsChecked, ...(finding.evidence.scope?.candidates ?? [])]) {\n if (!tracked.includes(file) && await pathExists(root, file)) dirty = true;\n }\n }\n const fingerprint = digest([scope, tree, lastScopeCommit, paths]);\n if ((await git(root, \"rev-parse\", \"HEAD\")).trim() !== head) throw new Error(\"HEAD changed while collecting review evidence.\");\n return { ...evidenceSchema.parse({ head, scope, tree, lastScopeCommit, paths, fingerprint }), dirty,\n documentDigest: digest(document) };\n}\n\nasync function decisionAssessment(root: string, finding: Finding, baselineHead: string): Promise<AdvisoryReviewSummary | null> {\n const evidence = finding.evidence;\n if (evidence.kind !== \"decision-anchor\") return null;\n const id = findingId(finding);\n const store = await loadDecisionStore(root);\n if (store.diagnostics.length) throw new Error(\"Decision records have unavailable or malformed evidence; review cannot be confirmed.\");\n const record = store.records.find(record => record.id === evidence.decisionId);\n if (!record || record.version !== 2) return null;\n const events = record.history.filter(event => [\"accepted\", \"reaffirmed\", \"retired\"].includes(event.kind));\n const event = events.at(-1);\n if (!event?.evidence || !event.actor || !event.note || !event.evidence.historyAvailable || event.evidence.localChanges.length) return null;\n try { await git(root, \"merge-base\", \"--is-ancestor\", baselineHead, event.evidence.headHash); }\n catch { return null; }\n const drift = await computeDecisionDrift(root, [record]);\n if (!drift.historyAvailable) throw new Error(\"Decision review history is unavailable.\");\n const retired = record.status === \"retired\" && event.kind === \"retired\";\n const current = retired || record.status === \"active\" && record.approval === \"accepted\"\n && drift.freshness?.[record.id] === \"current\" && !drift.pendingProposals?.[record.id];\n return { id, status: current ? \"current\" : \"reopened\", outcome: event.kind as \"accepted\" | \"reaffirmed\" | \"retired\",\n reviewer: event.actor, note: event.note, reviewedHead: event.evidence.headHash,\n recordPath: `.mason/decisions/${record.id}.json`, reason: current\n ? \"The existing decision review records acceptance, reaffirmation or retirement covering the original finding.\"\n : \"Decision content or anchor evidence changed after its review; review the decision again.\" };\n}\n\nexport async function assessAdvisory(root: string, finding: Finding, baselineHead: string): Promise<AdvisoryReviewSummary | null> {\n if (\"confidence\" in finding) return null;\n const id = findingId(finding);\n try {\n if (finding.evidence.kind === \"decision-anchor\") return await decisionAssessment(root, finding, baselineHead);\n const record = await readRecord(root, id);\n if (!record) return null;\n const event = record.events.at(-1)!;\n // Use the reviewed scope, not a newly shortened finding's preview of that scope.\n const current = await reviewEvidence(root, event.finding as Finding);\n await git(root, \"merge-base\", \"--is-ancestor\", event.evidence.head, current.head);\n const base = { id, recordPath: recordPath(id), reviewer: event.reviewer, note: event.note,\n outcome: event.outcome, reviewedHead: event.evidence.head };\n if (current.dirty || current.fingerprint !== event.evidence.fingerprint || digest(scopes(finding)) !== digest(event.evidence.scope)) return { ...base, status: \"reopened\", reason: \"Relevant document or repository evidence changed after the assessment; prepare a new review.\" };\n return { ...base, status: event.outcome === \"deferred\" ? \"deferred\" : \"current\", reason: event.outcome === \"deferred\"\n ? \"The review was deferred and remains outstanding.\" : \"An explicit assessment covers the current committed scope. This does not approve an engineering decision or certify correctness.\" };\n } catch (error) { return { id, status: \"unverified\", reason: error instanceof Error ? error.message : String(error) }; }\n}\n\n/** Fingerprint receipt content so concurrent automation cannot publish an older assessment. */\nexport async function advisoryReviewInventory(root: string) {\n let names: string[];\n try { names = await fs.readdir(await storePath(root, \".mason/reviews/advisories\")); }\n catch (error) { if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return []; throw error; }\n if (names.length > 5000) throw new Error(\"Advisory review inventory exceeds 5,000 records.\");\n return Promise.all(names.filter(name => name.endsWith(\".json\")).sort().map(async name => [name, await readAuditInput(root, \".mason/reviews/advisories/\" + name)]));\n}\n\nexport async function reviewAdvisory(rootDir: string, input: AdvisoryReviewInput) {\n const root = await fs.realpath(rootDir), request = advisoryReviewRequest.parse(input);\n const { loadRepairBaseline } = await import(\"./repair.js\");\n const baseline = await loadRepairBaseline(root, request.baselinePath);\n const finding = [...baseline.original.advisories, ...(baseline.original.suppressedAdvisories ?? [])].find(f => findingId(f) === request.findingId);\n if (!finding) throw new Error(\"No advisory with this findingId in the original baseline. Provable issues must be repaired and rechecked.\");\n if (finding.evidence.kind === \"decision-anchor\") return { status: \"decision-review-required\", decisionId: finding.evidence.decisionId,\n hint: \"Use review_decision to prepare evidence and record authorized acceptance, reaffirmation or retirement, then verify this original repair baseline. An advisory assessment cannot approve a decision.\" };\n const prepare = async () => {\n const record = await readRecord(root, request.findingId);\n const evidence = await reviewEvidence(root, finding);\n await git(root, \"merge-base\", \"--is-ancestor\", baseline.original.headHash!, evidence.head);\n const token = digest({ baseline: baseline.original, finding, evidence, record });\n return { record, evidence, token };\n };\n if (request.action === \"prepare\") {\n const state = await prepare();\n let diff: string | null = null, diffNote: string | undefined;\n const from = finding.evidence.kind === \"doc-behind-manifests\" ? finding.evidence.docLastCommit.hash : baseline.original.headHash!;\n try {\n const full = await git(root, \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", from, state.evidence.head, \"--\", ...state.evidence.scope);\n diff = full.slice(0, 16000); if (full.length > diff.length) diffNote = \"Diff preview truncated; inspect the full scoped diff before reviewing.\";\n } catch { diffNote = \"Diff preview unavailable; inspect the original cited evidence directly before reviewing.\"; }\n if ((await prepare()).token !== state.token) throw new Error(\"Review evidence changed during preparation; retry.\");\n return { status: \"prepared\", findingId: request.findingId, finding, evidence: state.evidence,\n history: state.record?.events ?? [], reviewToken: state.token, diff, diffNote,\n hint: \"Inspect the original finding, scoped document and relevant code changes. Record addressed, inapplicable or deferred only when the user or cited project review authorizes that assessment. Supply the actual reviewer, reason in note and reviewToken. Relevant edits must be committed first. Deferral remains outstanding. Review identities are recorded assertions, not authenticated approvals.\" };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) throw new Error(\"Prepare first; recording an assessment requires reviewToken, reviewer and note.\");\n return withLock(root, \".mason/reports/advisory-review-locks/\" + request.findingId, async () => {\n const state = await prepare();\n if (state.token !== request.reviewToken) throw new Error(\"Review conflict: evidence or review history changed since preparation. Prepare and inspect a new review.\");\n if (state.evidence.dirty) throw new Error(\"Commit relevant document and repository edits before recording the assessment. Unrelated local work may remain.\");\n if ((state.record?.events.length ?? 0) >= 200) throw new Error(\"Review history limit reached; existing events were retained.\");\n const { dirty, documentDigest, ...evidence } = state.evidence;\n const event = eventSchema.parse({ at: new Date().toISOString(), reviewer: request.reviewer, note: request.note,\n outcome: request.action, finding, evidence });\n const payload = { version: 1 as const, id: request.findingId, events: [...(state.record?.events ?? []), event] };\n if ((await prepare()).token !== state.token) throw new Error(\"Review conflict: evidence changed while recording the assessment.\");\n await writeStoreJson(root, recordPath(request.findingId), { ...payload, digest: digest(payload) });\n return { status: \"recorded\", recordPath: recordPath(request.findingId), event,\n hint: \"Review and commit this assessment record through the normal project workflow, then verify the original repair baseline. Relevant changes reopen the assessment; deferral remains outstanding.\" };\n });\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport 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 { assessAdvisory } from \"./advisory-review.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 discovered instruction files and READMEs\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 return profilePhase(\"audit.current\", () => auditCurrent(rootDir, options));\n}\n\nasync function auditCurrent(rootDir: string, options: AuditOptions): 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 scope: d.scope,\n kind: d.kind,\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 const changesByCommit = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n const hash = doc.lastCommit?.hash;\n if (hash && !changesByCommit.has(hash)) changesByCommit.set(hash, await getChangesWithStatus(resolvedRoot, hash));\n changesSinceDoc.set(doc.path, hash ? changesByCommit.get(hash)! : null);\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 const reviews = (await Promise.all([...report.advisories, ...report.suppressedAdvisories!]\n .map(finding => assessAdvisory(resolvedRoot, finding, headHash)))).filter(review => review !== null);\n if (reviews.length) report.advisoryReviews = reviews;\n return report;\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit, type AuditOptions } from \"./audit.js\";\nimport { discoverDocPaths } 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, normalizeRepoPath } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { checkSchema, commitSchema, issueSchema, advisorySchema, digest, findingId, type Finding } from \"./findings.js\";\nimport { assessAdvisory, advisoryReviewInventory, reviewSummarySchema, type AdvisoryReviewSummary } from \"./advisory-review.js\";\nexport { checkResultSchema, findingId } from \"./findings.js\";\nconst count = z.number().int().nonnegative();\n\nexport const 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.string().refine(value => normalizeRepoPath(value) === value), scope: z.string().optional(),\n kind: z.enum([\"instructions\", \"readme\"]).optional(), 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});\n\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\n\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n review?: AdvisoryReviewSummary;\n}\nexport const repairFindingSchema = z.object({\n id: z.string(), original: z.union([issueSchema, advisorySchema]),\n status: z.enum([\"resolved\", \"unresolved\", \"review-required\", \"unverified\"]), reason: z.string(),\n current: z.union([issueSchema, advisorySchema]).optional(),\n review: reviewSummarySchema.optional(),\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\nfunction recheckable(finding: Finding): boolean {\n return !(\"confidence\" in finding) && finding.resolution === \"recheck\"\n && [\"deleted-reference\", \"dead-command\", \"new-module\"].includes(finding.type)\n && [\"missing-path\", \"missing-script\", \"unmentioned-dir\"].includes(finding.evidence.kind);\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 await discoverDocPaths(root)) {\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 = {}): Promise<AuditReport | null> {\n return profilePhase(\"repair.audit\", () => readStableAudit(root, checks, options));\n}\n\nasync function readStableAudit(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 return prepareOriginal(rootDir, checks, options);\n}\n\ninterface RepairSession {\n audit: (checks: CheckName[]) => Promise<AuditReport | null>;\n document: (file: string) => Promise<string | null>;\n history: (head: string) => ReturnType<typeof getChangesWithStatus>;\n assessment: typeof assessAdvisory;\n}\n\n/** Automation shares one inspection across its audit and original baselines.\n * Its required validator re-reads the full input inventory before this returns.\n * Standalone prepare/verify retain their own stability guards below.\n */\nexport async function withRepairSession<T>(root: string, options: AuditOptions, run: (session: {\n prepare: () => ReturnType<typeof prepareRepair>;\n verify: (baselinePath: string) => Promise<RepairVerification>;\n currentAudit: () => Promise<AuditReport | null>;\n}) => Promise<T>, validate: () => Promise<void>, cachedAudit?: AuditReport): Promise<T> {\n const head = await getCurrentGitHash(root);\n const audits = new Map<string, Promise<AuditReport | null>>();\n const documents = new Map<string, Promise<string | null>>();\n const history = new Map<string, ReturnType<typeof getChangesWithStatus>>();\n const assessments = new Map<string, ReturnType<typeof assessAdvisory>>();\n const memo = <T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> => {\n if (!cache.has(key)) cache.set(key, read());\n return cache.get(key)!;\n };\n const session: RepairSession = {\n audit: checks => memo(audits, [...checks].sort().join(\",\"), async () => {\n if (cachedAudit && cachedAudit.headHash === head && cachedAudit.root === root &&\n digest([...checks].sort()) === digest([...(cachedAudit.checksRun ?? [])].sort())) {\n // Raw audit results are cached, never their approval assessments. Original\n // baselines may refer to scopes no longer mentioned in the current docs.\n const current = structuredClone(cachedAudit);\n const reviews = (await Promise.all(allFindings(current).map(f => assessAdvisory(root, f, head)))).filter(r => r !== null);\n delete current.advisoryReviews;\n if (reviews.length) current.advisoryReviews = reviews;\n return current;\n }\n return computeAudit(root, { ...options, checks });\n }),\n document: file => memo(documents, file, async () => readBoundedFile(await storePath(root, file), 10 * 1024 * 1024)),\n history: head => memo(history, head, () => getChangesWithStatus(root, head)),\n assessment: (dir, finding, head) => memo(assessments, digest([dir, finding, head]), () => assessAdvisory(dir, finding, head)),\n };\n const result = await run({\n prepare: () => prepareOriginal(root, ALL_CHECKS, options, session),\n verify: baseline => profilePhase(\"repair.verify\", () => verifyOriginal(root, baseline, options, session)),\n currentAudit: () => session.audit(ALL_CHECKS),\n });\n await validate();\n return result;\n}\n\nasync function prepareOriginal(rootDir: string, checks: CheckName[], options: AuditOptions, session?: RepairSession) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await (session ? session.audit(selected) : 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 loadRepairBaseline(rootDir: string, baselinePath: string) {\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 return { root, relative, original };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string, options: AuditOptions = {}): Promise<RepairVerification> {\n return profilePhase(\"repair.verify\", () => verifyOriginal(rootDir, baselinePath, options));\n}\n\nasync function verifyOriginal(rootDir: string, baselinePath: string, options: AuditOptions, session?: RepairSession): Promise<RepairVerification> {\n const { root, relative, original } = await loadRepairBaseline(rootDir, baselinePath);\n const diagnostics: string[] = [];\n let reviewDigest: string | undefined;\n let current: AuditReport | null = null;\n try {\n if (!session) reviewDigest = digest(await advisoryReviewInventory(root));\n current = await (session ? session.audit(original.checksRun!) : 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 (!allFindings(original).some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await (session ? session.document(doc.path) : 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 (session ? session.history(original.headHash!) : 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 = await Promise.all(originalFindings.map(async (finding): Promise<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 (now && (\"confidence\" in finding || \"confidence\" in 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 const review = await (session?.assessment ?? assessAdvisory)(root, now ?? finding, original.headHash!);\n if (review) {\n if (review.status === \"unverified\") return { ...base, review, status: \"unverified\", reason: review.reason };\n if (review.status === \"current\") return { ...base, review, status: \"resolved\", reason: review.reason };\n return { ...base, review, status: \"review-required\", reason: review.reason };\n }\n if (!(\"confidence\" in finding) && (!recheckable(finding) || now)) {\n return { ...base, status: \"review-required\",\n reason: (now ? \"The current check still reports this advisory. \" : finding.type === \"deps-changed\"\n ? \"The current check no longer reports this condition; the historical advisory remains awaiting assessment. \"\n : \"The current check no longer reports the original finding; retained evidence still requires assessment. \") +\n \"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 if (!session) try {\n if (reviewDigest !== digest(await advisoryReviewInventory(root)) || current?.headHash !== await getCurrentGitHash(root)) {\n diagnostics.push(\"HEAD or advisory review records changed during verification; repeat against stable evidence.\");\n for (const finding of findings) { finding.status = \"unverified\"; finding.reason = diagnostics.at(-1)!; }\n }\n } catch (error) {\n diagnostics.push(String(error));\n for (const finding of findings) { finding.status = \"unverified\"; finding.reason = \"Advisory review evidence became unavailable during verification.\"; }\n }\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const reviewedIds = new Set(current?.advisoryReviews?.filter(review => review.status === \"current\").map(review => review.id));\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) && !reviewedIds.has(findingId(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 the check or covered by an explicit assessment of current evidence; inspect each finding's reason and 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 findingId: \" + f.id),\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 { execGit } from \"../utils/git-read.js\";\nimport { profilePhase } from \"../utils/profile.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport fg from \"fast-glob\";\nimport { z } from \"zod\";\nimport { discoverDocPaths } from \"../audit/docs.js\";\nimport { pathClaimScope, pathExists, optionalMasonPath, gitMetadataPath } from \"../audit/scope.js\";\nimport { extractClaims } from \"../audit/claims.js\";\nimport { checkResultSchema } from \"../audit/repair.js\";\nimport { CHECKS, type CheckResult } from \"../audit/checks/index.js\";\nimport type { AuditOptions } from \"../audit/audit.js\";\nimport type { CheckName } from \"../audit/types.js\";\nimport { readAuditInput } from \"../audit/inputs.js\";\nimport { moduleCandidates, moduleDocumentation } from \"../audit/checks/new-module.js\";\nimport { resolveDocCountSource } from \"../audit/checks/stale-count.js\";\nimport { commandInputs } from \"../audit/checks/dead-command.js\";\nimport { storePath } from \"../utils/storage.js\";\nimport { advisoryReviewInventory } from \"../audit/advisory-review.js\";\n\ndeclare const PKG_VERSION: string;\nconst engineVersion = typeof PKG_VERSION === \"string\" ? PKG_VERSION : \"development\";\nexport const hash = (value: unknown): string => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\nexport async function git(root: string, ...args: string[]): Promise<string> {\n return profilePhase(\"automation.git\", async () => (await execGit(args, { cwd: root, maxBuffer: 16 * 1024 * 1024, timeout: 10000 })).stdout);\n}\n\nexport async function workspace(dir: string) {\n const root = await fs.realpath((await git(dir, \"rev-parse\", \"--show-toplevel\")).trim());\n const [gitDir, branch] = await Promise.all([\n git(root, \"rev-parse\", \"--absolute-git-dir\").then(value => fs.realpath(value.trim())),\n git(root, \"symbolic-ref\", \"--quiet\", \"HEAD\").then(value => value.trim(), () => \"detached\"),\n ]);\n return { root, gitDir, branch, directory: \".mason/reports/automation/\" + hash([root, gitDir, branch]).slice(0, 24) };\n}\n\nconst content = readAuditInput;\n\nexport interface Inputs {\n fingerprint: string;\n head: string;\n docs: Record<string, string | null>;\n keys: Record<CheckName, string>;\n}\n\nexport async function readInputs(root: string): Promise<Inputs> {\n return profilePhase(\"automation.inputs\", () => collectInputs(root));\n}\n\nasync function collectInputs(root: string): Promise<Inputs> {\n const docPaths = await discoverDocPaths(root);\n const [headText, docStatus, shallowPath, replacements] = await Promise.all([\n git(root, \"rev-parse\", \"HEAD\"),\n docPaths.length ? git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...docPaths.map(p => `:(literal)${p}`)) : \"\",\n git(root, \"rev-parse\", \"--git-path\", \"shallow\"),\n git(root, \"for-each-ref\", \"--format=%(refname) %(objectname)\", \"refs/replace\"),\n ]);\n const head = headText.trim();\n let shallow: string | null = null;\n try { shallow = await fs.readFile(path.resolve(root, shallowPath.trim()), \"utf8\"); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n const docs: Record<string, string | null> = {};\n const docContents: Array<[string, string | null]> = [];\n const parsedDocs = [];\n const claims: Array<[string, boolean, boolean]> = [];\n const presence = new Map<string, Promise<boolean>>();\n const exists = (file: string) => {\n if (!presence.has(file)) presence.set(file, pathExists(root, file));\n return presence.get(file)!;\n };\n for (const file of docPaths) {\n const text = await content(root, file);\n docs[file] = text === null ? null : hash(text);\n docContents.push([file, text]);\n const parsed = { path: file, content: text ?? \"\", claims: extractClaims(text ?? \"\") };\n parsedDocs.push(parsed);\n for (const claim of parsed.claims.paths) {\n const scope = pathClaimScope(file, claim);\n if (scope?.candidates.some(gitMetadataPath)) continue;\n for (const candidate of scope?.candidates ?? []) {\n if (optionalMasonPath(candidate)) continue;\n const [filePresent, parentPresent] = await Promise.all([exists(candidate), exists(path.posix.dirname(candidate))]);\n claims.push([candidate, filePresent, parentPresent]);\n }\n }\n }\n const combinedDocs = moduleDocumentation(parsedDocs);\n const countClaims = parsedDocs.flatMap(doc => doc.claims.counts.map(claim => ({ doc: doc.path, claim })));\n const decisionDirectory = await storePath(root, \".mason/decisions\");\n const decisionPresence = await fs.lstat(decisionDirectory).then(stat => stat.isDirectory() ? \"directory\" : \"file\", error => {\n if (error.code === \"ENOENT\") return \"absent\";\n throw error;\n });\n const [modules, counts, commands, decisionFiles] = await Promise.all([\n combinedDocs ? moduleCandidates(root, combinedDocs) : [],\n Promise.all(countClaims.map(({ doc, claim }) => resolveDocCountSource(root, doc, claim))),\n commandInputs(root, parsedDocs),\n fg(\".mason/decisions/*.json\", { cwd: root, dot: true, onlyFiles: false, followSymbolicLinks: false }),\n ]);\n const decisions = await Promise.all(decisionFiles.sort().map(async file => {\n await storePath(root, file);\n return [file, await content(root, file)];\n }));\n // Decision freshness observes tracked and local anchor changes; other checks\n // do not need a repository-wide status or index scan.\n const [status, index] = decisions.length ? await Promise.all([\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", \".\", \":(exclude).mason/reports\"),\n git(root, \"ls-files\", \"--stage\", \"-z\", \"--\", \".\", \":(exclude).mason/reports\"),\n ]) : [\"\", \"\"];\n const common = [6, engineVersion, head, shallow, replacements, docContents];\n const keys: Record<CheckName, string> = {\n \"deleted-reference\": hash([common, claims, docStatus]),\n \"new-module\": hash([common, modules]),\n \"stale-count\": hash([common, counts]),\n \"dead-command\": hash([common, commands]),\n \"deps-changed\": hash([common, docStatus]),\n \"decision-anchor-drift\": hash([common, decisionPresence, decisions, status, index]),\n };\n return { fingerprint: hash([keys, await advisoryReviewInventory(root)]), head, docs, keys };\n}\n\nconst cacheSchema = z.object({ version: z.literal(1), entries: z.record(z.object({ key: z.string(), result: checkResultSchema })), digest: z.string() });\nexport function checkCache(raw: unknown, inputs: Inputs) {\n let entries: Record<string, { key: string; result: CheckResult }> = {};\n let diagnostic: string | null = null;\n if (raw !== null) {\n const parsed = cacheSchema.safeParse(raw);\n if (parsed.success && parsed.data.digest === hash(parsed.data.entries)) entries = parsed.data.entries as Record<string, { key: string; result: CheckResult }>;\n else diagnostic = \"Discarded an invalid automation cache; checks are being recomputed.\";\n }\n const ran = new Set<CheckName>(), reused = new Set<CheckName>();\n const options: AuditOptions = { runCheck: async (name, ctx) => {\n if (entries[name]?.key === inputs.keys[name]) {\n reused.add(name);\n return structuredClone(entries[name].result);\n }\n const result = await profilePhase(\"check.\" + name, () => CHECKS[name](ctx));\n ran.add(name);\n // An unavailable check must be retried even if the file inputs match.\n if (!result.skipped.length) entries[name] = { key: inputs.keys[name], result };\n else delete entries[name];\n return result;\n } };\n return { options, ran, reused, diagnostic,\n has: (name: CheckName) => entries[name]?.key === inputs.keys[name] && !entries[name].result.skipped.length,\n serialize: () => {\n const canonical = cacheSchema.shape.entries.parse(entries);\n return { version: 1, entries: canonical, digest: hash(canonical) };\n } };\n}\n","import { z } from \"zod\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { git } from \"../automation/evidence.js\";\nimport { readStoreJson } from \"../utils/storage.js\";\n\nexport const setupHostSchema = z.object({\n configuredVersion: z.string(), revision: z.string().uuid(), fingerprint: z.string(), mcpFingerprint: z.string(),\n instructions: z.array(z.string()),\n});\nexport const setupSchema = z.object({ version: z.literal(2), hosts: z.object({\n codex: setupHostSchema.optional(), claude: setupHostSchema.optional(),\n}) });\nexport const SETUP_PATH = \".mason/local/setup.json\";\nexport const INACTIVE_HOSTS_PATH = \".mason/local/inactive-hosts.json\";\nexport const inactiveHostsSchema = z.object({ version: z.literal(1), hosts: z.array(z.enum([\"claude\", \"codex\"])) });\nexport type SetupConfig = z.infer<typeof setupSchema>;\nexport async function loadSetup(root: string): Promise<SetupConfig | null> {\n const raw = await readStoreJson(root, SETUP_PATH);\n if (raw === null) return null;\n return setupSchema.parse(raw);\n}\n\n/** Share activation with linked worktrees, never their audit evidence or ownership. */\nexport async function effectiveSetup(root: string): Promise<{ root: string; setup: SetupConfig | null }> {\n const local = await loadSetup(root);\n // Even an empty local record is authoritative (including after teardown).\n if (local) return { root, setup: local };\n const common = await fs.realpath(path.resolve(root, (await git(root, \"rev-parse\", \"--git-common-dir\")).trim()));\n const own = await fs.realpath((await git(root, \"rev-parse\", \"--absolute-git-dir\")).trim());\n if (common === own) return { root, setup: null };\n // Git's first worktree identifies the primary checkout. Bare repositories\n // have no primary checkout from which to inherit activation.\n const primary = (await git(root, \"worktree\", \"list\", \"--porcelain\", \"-z\")).split(\"\\0\\0\")[0].split(\"\\0\");\n const candidate = primary.find(field => field.startsWith(\"worktree \"))?.slice(9);\n if (!candidate || primary.includes(\"bare\")) return { root, setup: null };\n let inheritedRoot: string;\n try { inheritedRoot = await fs.realpath((await git(candidate, \"rev-parse\", \"--show-toplevel\")).trim()); }\n catch (error) {\n // --separate-git-dir may list only the metadata directory, with no recorded\n // checkout location. Do not infer a sibling or search unrelated directories.\n if (/must be run in a work tree/.test(String((error as { stderr?: string }).stderr))) return { root, setup: null };\n throw error;\n }\n const inheritedCommon = await fs.realpath(path.resolve(inheritedRoot,\n (await git(inheritedRoot, \"rev-parse\", \"--git-common-dir\")).trim()));\n if (inheritedCommon !== common) throw new Error(\"Linked worktree setup does not belong to the same Git repository.\");\n const setup = await loadSetup(inheritedRoot);\n const inactive = await readStoreJson(root, INACTIVE_HOSTS_PATH);\n if (inactive && setup) for (const host of inactiveHostsSchema.parse(inactive).hosts) delete setup.hosts[host];\n return { root: inheritedRoot, setup };\n}\n\nconst receiptSchema = z.object({ version: z.literal(1), host: z.enum([\"codex\", \"claude\"]),\n status: z.enum([\"installing\", \"configured\"]), initialReportPath: z.string(), initialBaselinePaths: z.array(z.string()),\n root: z.string(), revision: z.string().uuid(), configuredAt: z.string().optional() });\nexport async function loadSetupReceipt(root: string, directory: string, host: \"codex\" | \"claude\") {\n const raw = await readStoreJson(root, directory + \"/setup-\" + host + \".json\");\n if (raw === null) return null;\n const receipt = receiptSchema.parse(raw);\n if (receipt.root !== root || receipt.host !== host) throw new Error(\"Setup receipt belongs to another installation.\");\n return receipt;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fs from \"node:fs/promises\";\nimport type { Host } from \"../automation/store.js\";\nimport { git } from \"../automation/evidence.js\";\nimport { effectiveSetup } from \"./model.js\";\n\ndeclare const PKG_VERSION: string;\nexport const executingVersion = () => typeof PKG_VERSION === \"string\" ? PKG_VERSION : \"development\";\n\n// Windows needs cmd to launch both npm's and the standalone installer's .cmd shim.\nexport function globalCommand(args: string[], platform = process.platform) {\n return platform === \"win32\" ? { command: \"cmd.exe\", args: [\"/d\", \"/s\", \"/c\", \"mason\", ...args] }\n : { command: \"mason\", args };\n}\nexport const mcpCommand = (host: Host) => globalCommand([\"--setup-host\", host, \"mcp\"]);\nexport const hookCommand = (host: Host) => `mason --setup-host ${host} auto`;\n\n/** Probe the same PATH command the host will use; never download during setup. */\nexport async function installedCommand() {\n const invocation = globalCommand([\"internal-integration-version\"]);\n try {\n const { stdout } = await promisify(execFile)(invocation.command, invocation.args,\n { timeout: 5000, maxBuffer: 8192, windowsHide: true });\n const result = JSON.parse(stdout);\n if (result.protocol !== 1 || typeof result.version !== \"string\") throw new Error(\"Unsupported Mason integration protocol.\");\n return { available: true, version: result.version as string, message: null };\n } catch {\n return { available: false, version: null, message: \"An up-to-date mason command is not available on this process's PATH. Install or upgrade Mason, then reopen your terminal or desktop assistant and rerun mason setup.\" };\n }\n}\n\n/** Replaces the environment previously supplied by generated project launchers. */\nexport async function prepareLaunch(host: Host, options: { dir?: string; allowInactive?: boolean } = {}) {\n const root = await fs.realpath((await git(options.dir ?? process.cwd(), \"rev-parse\", \"--show-toplevel\")).trim());\n const entry = (await effectiveSetup(root)).setup?.hosts[host];\n process.env.MASON_SETUP_ROOT = root;\n process.env.MASON_SETUP_HOST = host;\n delete process.env.MASON_SETUP_REVISION;\n if (!entry) {\n if (options.allowInactive) return false;\n throw new Error(`Mason is not configured locally for ${host}. Run mason setup --host ${host} in this checkout.`);\n }\n process.env.MASON_SETUP_REVISION = entry.revision;\n return true;\n}\n\nexport function inactiveSetupMessage(): string | null {\n const host = process.env.MASON_SETUP_HOST;\n if (!process.env.MASON_SETUP_ROOT || process.env.MASON_SETUP_REVISION || (host !== \"claude\" && host !== \"codex\")) return null;\n return `Mason MCP is available, but automatic hooks are inactive in ${process.env.MASON_SETUP_ROOT}. Run mason setup --host ${host} in that checkout, review the host configuration, then restart the assistant. Setup has not been performed automatically.`;\n}\n","import { createHash } from \"node:crypto\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { normalizeFeatureType, type FeatureEntry, type FlowEntry } from \"./snapshot.js\";\n\nexport type SnapshotEntryKind = \"feature\" | \"flow\";\nexport interface SnapshotVerdict {\n ok: boolean;\n note?: string;\n // Optional at the input boundary so older clients receive actionable feedback.\n kind?: SnapshotEntryKind;\n reviewToken?: string;\n}\n\nexport const VERIFY_MAX_FILES_PER_ENTRY = 8;\nconst VERIFY_SKELETON_CHARS = 500;\ntype FileAccess = Awaited<ReturnType<typeof createFileAccess>>;\n\n/** Verification metadata and refresh timestamps do not change an entry's meaning. */\nexport function snapshotEntryContent(entry: FeatureEntry | FlowEntry) {\n return {\n description: entry.description,\n files: \"files\" in entry ? entry.files : undefined,\n chain: \"chain\" in entry ? entry.chain : undefined,\n tests: \"files\" in entry ? entry.tests : undefined,\n type: \"files\" in entry ? normalizeFeatureType(entry.type) : undefined,\n };\n}\n\ntype SourceEvidence = Array<{ path: string; hash: string | null }>;\nconst sourceHash = (content: string) => createHash(\"sha256\").update(content).digest(\"hex\");\n\nfunction reviewToken(kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry, evidence: SourceEvidence) {\n return createHash(\"sha256\").update(JSON.stringify({\n version: 1, kind, name, entry: snapshotEntryContent(entry), evidence,\n })).digest(\"hex\");\n}\n\n/** Bind the token to the exact bounded source reads used to produce the previews. */\nexport async function prepareSnapshotReview(\n access: FileAccess,\n kind: SnapshotEntryKind,\n name: string,\n entry: FeatureEntry | FlowEntry,\n) {\n const files = \"files\" in entry ? entry.files : entry.chain;\n const evidence: SourceEvidence = [];\n const skeletons: Array<{ path: string; content: string } | { path: string; missing: true }> = [];\n for (const file of files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n const full = await access.read(file);\n evidence.push({ path: file, hash: full ? sourceHash(full.content) : null });\n skeletons.push(full ? { path: full.path, content: full.content.slice(0, VERIFY_SKELETON_CHARS) } : { path: file, missing: true });\n }\n return { reviewToken: reviewToken(kind, name, entry, evidence), skeletons, truncated: files.length > VERIFY_MAX_FILES_PER_ENTRY };\n}\n\n/** Cache only hashes/availability for one trust response, never source strings or previews. */\nexport function createSnapshotEvidenceReader(access: FileAccess) {\n const hashes = new Map<string, Promise<string | null>>();\n return async (kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry) => {\n const files = \"files\" in entry ? entry.files : entry.chain;\n const evidence: SourceEvidence = [];\n for (const file of files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n let hash = hashes.get(file);\n if (!hash) {\n hash = access.read(file).then(full => full ? sourceHash(full.content) : null);\n hashes.set(file, hash);\n }\n evidence.push({ path: file, hash: await hash });\n }\n return {\n reviewToken: reviewToken(kind, name, entry, evidence),\n evidenceAvailable: evidence.length > 0 && evidence.every(file => file.hash !== null),\n };\n };\n}\n","import { assessTrust, type Freshness, type TrustState } from \"../context/trust.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { createSnapshotEvidenceReader, type SnapshotEntryKind } from \"./review.js\";\nimport type { FeatureEntry, FlowEntry, Snapshot } from \"./snapshot.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\n\n/** Recheck reviewed evidence for one retrieval; never persist or reuse it across calls. */\nexport function createSnapshotTrustReader(root: string) {\n // Share the file policy/inventory, and initialize only for token-bearing verdicts.\n let reader: Promise<ReturnType<typeof createSnapshotEvidenceReader> | null> | undefined;\n return async (kind: SnapshotEntryKind, name: string, entry: FeatureEntry | FlowEntry, freshness: Freshness): Promise<TrustState> => {\n const trust = assessTrust(entry, freshness);\n const verdict = entry.verificationFailed ? \"failed\" : entry.verifiedAt ? \"passed\" : undefined;\n if (!verdict) return trust;\n trust.recordedVerdict = verdict;\n const unknown = (reason: string) => {\n trust.verification = \"unknown\";\n trust.reasons.push(reason);\n return trust;\n };\n if (!entry.verificationToken || !/^[a-f0-9]{64}$/.test(entry.verificationToken)) return unknown(\"The recorded verdict has no supported evidence token; obtain a fresh verify_snapshot review.\");\n try {\n reader ??= createFileAccess(root).then(createSnapshotEvidenceReader).catch(() => null);\n const readReview = await reader;\n if (!readReview) return unknown(\"Verification source evidence could not be read under the current file policy.\");\n const review = await readReview(kind, name, entry);\n if (!review.evidenceAvailable) {\n return unknown(\"Verification source evidence is missing, excluded, unreadable, or empty; the recorded verdict cannot be confirmed.\");\n }\n if (review.reviewToken !== entry.verificationToken) {\n trust.verification = \"stale\";\n trust.reasons.push(\"The entry or sampled source contents differ from the recorded verification evidence; obtain a fresh review.\");\n }\n return trust;\n } catch {\n return unknown(\"Verification source evidence could not be read under the current file policy.\");\n }\n };\n}\n\n/** Walk the catalog sequentially to keep source reads bounded on large maps. */\nexport async function readSnapshotTrustIndex(readTrust: ReturnType<typeof createSnapshotTrustReader>, snapshot: Snapshot, drift: DriftReport | null) {\n const features: Record<string, TrustState> = Object.create(null), flows: Record<string, TrustState> = Object.create(null);\n for (const [name, entry] of Object.entries(snapshot.features)) {\n features[name] = await readTrust(\"feature\", name, entry, drift?.featureFreshness?.[name] ?? \"unknown\");\n }\n for (const [name, entry] of Object.entries(snapshot.flows)) {\n flows[name] = await readTrust(\"flow\", name, entry, drift?.flowFreshness?.[name] ?? \"unknown\");\n }\n return { features, flows };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { storePath } from \"../utils/storage.js\";\n\nexport interface FileEdit { path: string; before: string | null; after: string }\nexport interface RemovalEdit { path: string; before: string | null; after: null }\nexport async function readText(root: string, file: string): Promise<string | null> {\n try {\n const text = await readBoundedFile(await storePath(root, file), 2 * 1024 * 1024);\n if (text === null) throw new Error(\"Setup input is not a regular file or exceeds 2 MiB: \" + file);\n return text;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\n/** Preserve all bytes outside one unambiguous managed block. */\nexport function managedBlock(text: string, start: string, end: string, body: string): string {\n const starts = text.split(start).length - 1, ends = text.split(end).length - 1;\n if (starts !== ends || starts > 1 || starts === 1 && text.indexOf(end) < text.indexOf(start)) {\n throw new Error(\"Ambiguous Mason instruction/configuration markers; repair the marked block before setup.\");\n }\n const eol = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const block = [start, body.replace(/\\r?\\n/g, eol), end].join(eol);\n if (starts) return text.slice(0, text.indexOf(start)) + block + text.slice(text.indexOf(end) + end.length);\n return text + (text.length && !text.endsWith(\"\\n\") ? eol : \"\") + (text.length ? eol : \"\") + block + eol;\n}\n\n/** Compare before replacing or removing: retain a user's concurrent edit. */\nexport async function applyEdit(root: string, edit: FileEdit | RemovalEdit): Promise<boolean> {\n const current = await readText(root, edit.path);\n if (current === edit.after) return false;\n if (current !== edit.before) throw new Error(\"Integration input changed during update: \" + edit.path + \". Rerun the requested command to resume.\");\n if (edit.after === null) {\n const file = await storePath(root, edit.path);\n if (await readText(root, edit.path) !== edit.before) throw new Error(\"Input changed during removal: \" + edit.path);\n await fs.unlink(file);\n return true;\n }\n const file = await storePath(root, edit.path, true);\n const temporary = path.join(path.dirname(file), \".mason-setup-\" + randomUUID() + \".tmp\");\n try {\n const mode = await fs.stat(file).then(s => s.mode & 0o777, () => 0o600);\n const handle = await fs.open(temporary, \"wx\", mode);\n try { await handle.writeFile(edit.after, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n if (await readText(root, edit.path) !== edit.before) throw new Error(\"Integration input changed during update: \" + edit.path);\n await fs.rename(temporary, file);\n return true;\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import os from \"node:os\";\nimport fs from \"node:fs/promises\";\nimport { withLock } from \"./store.js\";\nimport { hash, workspace } from \"./evidence.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\n\nconst failureSchema = z.object({\n code: z.enum([\"inputs-changed\", \"storage-full\", \"busy\", \"invalid-input\", \"history-unavailable\", \"invalid-evidence\", \"io-error\", \"internal\"]),\n message: z.string(), retryable: z.boolean(), receiptRecorded: z.boolean(),\n});\nexport type AutomationFailure = z.infer<typeof failureSchema>;\nconst attemptSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/), lease: z.literal(true).optional(), event: z.string(), startedAt: z.string(), finishedAt: z.string().optional(),\n durationMs: z.number().nonnegative().optional(),\n pid: z.number().int().positive(), host: z.string(),\n status: z.enum([\"running\", \"completed\", \"failed\", \"unknown\"]),\n verificationStatus: z.string().optional(), reportPath: z.string().optional(), failure: failureSchema.optional(),\n});\nconst executionSchema = z.object({ version: z.literal(1), attempts: z.array(attemptSchema).max(160), discardedAttempts: z.number().int().nonnegative().default(0) });\nfunction parseExecution(raw: unknown) {\n try { return executionSchema.parse(raw); }\n catch (error) { throw new Error(\"Invalid automation execution store; receipt history was retained.\", { cause: error }); }\n}\n\n/** Classify failures without interpreting the advisory hook's exit code as evidence. */\nexport function automationFailure(error: unknown): AutomationFailure {\n const recorded = failureSchema.safeParse((error as { failure?: unknown } | null)?.failure);\n if (recorded.success) return recorded.data;\n const message = (error instanceof Error ? error.message : String(error)).replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \" \").slice(0, 700);\n const codes = new Set<string>();\n let cause: unknown = error;\n for (let i = 0; cause && i < 8; i++) {\n codes.add(String((cause as NodeJS.ErrnoException).code));\n cause = (cause as Error).cause;\n }\n const code: AutomationFailure[\"code\"] = codes.has(\"ENOSPC\") || codes.has(\"EDQUOT\") ? \"storage-full\"\n : /changed during|changed while|changed between/.test(message) ? \"inputs-changed\"\n : /Automation is busy/.test(message) ? \"busy\"\n : /not a git repository|unknown revision|bad revision|different history|unreachable/.test(message) ? \"history-unavailable\"\n : error instanceof z.ZodError || error instanceof SyntaxError || /Hook input|Expected one command|Unknown automation command|--host/.test(message) ? \"invalid-input\"\n : /store|baseline|modified|symbolic link|Symlink|automation state|state belongs/.test(message) ? \"invalid-evidence\"\n : [...codes].some(c => /^E[A-Z]+$/.test(c)) ? \"io-error\" : \"internal\";\n return { code, message, retryable: [\"inputs-changed\", \"storage-full\", \"busy\", \"io-error\"].includes(code), receiptRecorded: false };\n}\n\nexport function failureMessage(error: unknown): string {\n const failure = automationFailure(error);\n return `Mason automation unavailable [${failure.code}]; evidence capture/verification was not established. ${failure.message}` +\n (failure.receiptRecorded ? \"\" : \" No durable failure receipt was recorded.\");\n}\n\nconst notificationsSchema = z.object({ version: z.literal(1), sessions: z.record(z.object({\n signature: z.string(), code: failureSchema.shape.code, message: z.string(), count: z.number().int().positive(), lastAt: z.string(),\n})) });\n\nexport async function failureNotifications(root: string, directory: string) {\n const raw = await readStoreJson(root, directory + \"/notifications.json\");\n return raw === null ? { version: 1 as const, sessions: {} } : notificationsSchema.parse(raw);\n}\n\n/** Suppress repeats only after the failure itself has a durable execution receipt. */\nexport async function hookFailureMessage(dir: string, host: string, sessionId: string, error: unknown): Promise<string | null> {\n const failure = automationFailure(error);\n if (!failure.receiptRecorded) return failureMessage(error);\n try {\n const ws = await workspace(dir);\n return await withLock(ws.root, ws.directory + \"/notifications\", async () => {\n const notices = await failureNotifications(ws.root, ws.directory);\n const key = hash([host, sessionId]), signature = hash([failure.code, failure.message]);\n const previous = notices.sessions[key];\n const execution = await executionStatus(ws.root, ws.directory);\n const recovered = previous && execution.attempts.some(a => a.status === \"completed\" && a.startedAt > previous.lastAt);\n const repeat = previous?.signature === signature && !recovered;\n notices.sessions[key] = { signature, code: failure.code, message: failure.message,\n count: repeat ? previous.count + 1 : 1, lastAt: new Date().toISOString() };\n notices.sessions = Object.fromEntries(Object.entries(notices.sessions).sort(([, a], [, b]) => b.lastAt.localeCompare(a.lastAt)).slice(0, 32));\n await writeStoreJson(ws.root, ws.directory + \"/notifications.json\", notices);\n return repeat ? null : failureMessage(error) + \" Repeated failures in this session are recorded in mason status --json.\";\n });\n } catch { return failureMessage(error); }\n}\n\n/** Each invocation owns a receipt while only brief log updates are serialized. */\nconst leasePath = (directory: string, id: string) => `${directory}/executions/${id}.json`;\n\nasync function refreshRunning(root: string, directory: string, attempts: z.infer<typeof attemptSchema>[]) {\n for (const attempt of attempts) {\n if (attempt.status !== \"running\") continue;\n let alive = false;\n try {\n const owner = await readStoreJson(root, attempt.lease ? leasePath(directory, attempt.id) : directory + \"/lock\") as { pid?: unknown; host?: unknown } | null;\n if (attempt.host === os.hostname() && owner?.pid === attempt.pid && owner.host === attempt.host) {\n try { process.kill(attempt.pid, 0); alive = true; }\n catch (error) { alive = (error as NodeJS.ErrnoException).code === \"EPERM\"; }\n }\n } catch { /* Missing ownership never establishes a running check. */ }\n if (!alive) attempt.status = \"unknown\";\n }\n}\n\nasync function editExecution(root: string, directory: string, edit: (log: z.infer<typeof executionSchema>) => void) {\n return withLock(root, directory + \"/execution-lock\", async () => {\n const file = directory + \"/execution.json\";\n const raw = await readStoreJson(root, file);\n const log = raw === null ? { version: 1 as const, attempts: [], discardedAttempts: 0 } : parseExecution(raw);\n await refreshRunning(root, directory, log.attempts);\n edit(log);\n // Keep every live invocation plus the latest 32 finished attempts.\n const finished = log.attempts.filter(a => a.status !== \"running\");\n const discard = new Set(finished.slice(0, Math.max(0, finished.length - 32)).map(a => a.id));\n log.discardedAttempts += discard.size;\n log.attempts = log.attempts.filter(a => !discard.has(a.id));\n await writeStoreJson(root, file, log);\n });\n}\n\nexport async function recordExecution<T extends { report: { status: string; reportPath: string } }>(\n root: string, directory: string, event: string, run: () => Promise<T>,\n): Promise<T> {\n const started = performance.now();\n const attempt: z.infer<typeof attemptSchema> = {\n id: randomUUID(), event, startedAt: new Date().toISOString(), pid: process.pid, host: os.hostname(), status: \"running\", lease: true,\n };\n const owner = leasePath(directory, attempt.id);\n const finish = async (changes: Partial<z.infer<typeof attemptSchema>>) => editExecution(root, directory, log => {\n const current = log.attempts.find(a => a.id === attempt.id);\n if (!current) throw new Error(\"Automation execution receipt disappeared; completion could not be recorded.\");\n Object.assign(current, changes, { finishedAt: new Date().toISOString(), durationMs: performance.now() - started });\n });\n await writeStoreJson(root, owner, { pid: attempt.pid, host: attempt.host });\n try {\n await editExecution(root, directory, log => {\n if (log.attempts.filter(a => a.status === \"running\").length >= 128) throw new Error(\"Too many active automation executions; existing receipts were retained.\");\n log.attempts.push(attempt);\n });\n try {\n const result = await run();\n await finish({ status: \"completed\", verificationStatus: result.report.status, reportPath: result.report.reportPath });\n return result;\n } catch (error) {\n const failure = automationFailure(error);\n try { await finish({ status: \"failed\", failure: { ...failure, receiptRecorded: true } }); failure.receiptRecorded = true; }\n catch { /* Storage failures may also prevent their own completion receipt. */ }\n throw Object.assign(new Error(failure.message, { cause: error }), { failure });\n }\n } finally { await fs.rm(await storePath(root, owner), { force: true }).catch(() => {}); }\n}\n\nexport async function executionStatus(root: string, directory: string) {\n const raw = await readStoreJson(root, directory + \"/execution.json\");\n if (raw === null) return { status: \"not-observed\" as const, attempts: [] };\n const log = parseExecution(raw);\n await refreshRunning(root, directory, log.attempts);\n const completed = [...log.attempts].reverse().find(a => a.status === \"completed\");\n // A success that began before another call failed cannot establish recovery.\n const outstanding = [...log.attempts].reverse().find(a => [\"failed\", \"unknown\"].includes(a.status) &&\n (!completed || (a.finishedAt ?? a.startedAt) >= completed.startedAt));\n const status = log.attempts.some(a => a.status === \"running\") ? \"running\" : outstanding?.status ?? log.attempts.at(-1)?.status ?? \"not-observed\";\n return { status, attempts: log.attempts, discardedAttempts: log.discardedAttempts };\n}\n","import { profilePhase } from \"../utils/profile.js\";\nimport { withRepositoryInspection } from \"../audit/inspection.js\";\nimport { recordExecution, executionStatus, failureNotifications } from \"./execution.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { withRepairSession, reportSchema, findingId, repairFindingSchema, type RepairFinding, type RepairVerification } from \"../audit/repair.js\";\nimport { ALL_CHECKS, type AuditReport } from \"../audit/types.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { checkCache, git, hash, readInputs, workspace, type Inputs } from \"./evidence.js\";\nimport { parseState, withLock, type Event, type Host, type State } from \"./store.js\";\n\nexport interface AutomationEvent {\n event: Event;\n host?: Host;\n sessionId?: string;\n toolId?: string;\n mutating?: boolean;\n stopHookActive?: boolean;\n}\nexport interface AutomationReport {\n version: 1;\n status: \"verified\" | \"issues-remain\" | \"incomplete\" | \"unavailable\";\n root: string;\n branch: string;\n head: string;\n baselinePaths: string[];\n reportPath: string;\n findings: RepairFinding[];\n diagnostics: string[];\n checks: { ran: string[]; reused: string[]; skipped: NonNullable<AuditReport>[\"skippedChecks\"]; shared?: boolean; auditReused?: boolean };\n counts: RepairVerification[\"counts\"];\n capture: \"observed\" | \"unknown\";\n scope: string;\n}\n\nconst SCOPE = \"Documentation audit evidence only. Hook receipts show observed events, not complete interception. Resolved findings no longer fail their checks or have a recorded assessment covering current evidence. Repair and review only within the user's task authorization.\";\nconst priority = { resolved: 0, \"review-required\": 1, unresolved: 2, unverified: 3 };\nconst cleanText = (text: string) => text.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \" \").slice(0, 250);\n\n/** Read tools cannot create repair evidence. Observe their lifecycle without rescanning the checkout. */\nexport async function observeReadOnlyTool(dir: string, event: AutomationEvent) {\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n await withLock(ws.root, ws.directory, async () => {\n const statePath = ws.directory + \"/state.json\";\n const raw = await readStoreJson(ws.root, statePath);\n if (raw === null) return;\n const state = parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) {\n throw new Error(\"Automation state belongs to another branch or worktree; original evidence was retained.\");\n }\n const session = event.host && event.sessionId ? state.sessions[hash([event.host, event.sessionId])] : null;\n if (!session) return;\n const now = new Date().toISOString();\n session.lastUsed = now;\n session.events[event.event] = { at: now, count: (session.events[event.event]?.count ?? 0) + 1 };\n // Do not advance the audit fingerprint, report, or execution verdict: no check ran.\n await writeStoreJson(ws.root, statePath, state);\n });\n return { root: ws.root, directory: ws.directory };\n}\n\nexport function summarize(report: AutomationReport): string {\n const open = report.findings.filter(f => f.status !== \"resolved\");\n const onlyReview = report.status === \"incomplete\" && !report.diagnostics.length &&\n !report.counts.unresolved && !report.counts.unverified && report.counts[\"review-required\"] > 0;\n return [\n onlyReview ? `Mason: ${report.counts[\"review-required\"]} advisor${report.counts[\"review-required\"] === 1 ? \"y\" : \"ies\"} awaiting review; no unresolved issues.`\n : `Mason: ${report.status}; ${report.counts.unresolved} unresolved, ${report.counts[\"review-required\"]} need review, ${report.counts.unverified} unverified.`,\n ...open.slice(0, 4).map(f => {\n const detail = f.current ? f.current.message : f.status === \"review-required\"\n ? `${f.original.type}: current check no longer reports ${f.original.type === \"deps-changed\" ? \"this condition\" : \"the original finding\"}; historical evidence awaits assessment.`\n : `Original evidence: ${f.original.message}. ${f.reason}`;\n return `[${f.status}] ${cleanText(f.original.anchor.doc)}: ${cleanText(detail)}`;\n }),\n ...(open.length > 4 ? [`${open.length - 4} more findings in the report.`] : []),\n ...report.diagnostics.slice(0, 2).map(cleanText),\n `Evidence: ${report.reportPath}. Resume/check with mason_automation(action: \"check\") or mason-auto check.`,\n \"Keep original evidence. Address findings relevant to the authorized task; report unrelated findings with a brief scope reason and suggested follow-up. Use review_advisory for authorized assessments; otherwise leave advisories open without approving them.\",\n ].join(\"\\n\");\n}\n\ntype Workspace = Awaited<ReturnType<typeof workspace>>;\n\nasync function loadState(ws: Workspace): Promise<State> {\n const raw = await readStoreJson(ws.root, ws.directory + \"/state.json\");\n const state = raw === null ? {\n version: 1 as const, root: ws.root, gitDir: ws.gitDir, branch: ws.branch, baselines: [], sessions: {},\n updatedAt: new Date().toISOString(), fingerprint: null, latest: null,\n } : parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) {\n throw new Error(\"Automation state belongs to another branch or worktree; original evidence was retained.\");\n }\n return state;\n}\n\nconst analysisSchema = z.object({\n id: z.string(), fingerprint: z.string(), completedAt: z.number(), baselineDigest: z.string(),\n currentAudit: reportSchema.nullable().optional(),\n report: z.object({\n version: z.literal(1), status: z.enum([\"verified\", \"issues-remain\", \"incomplete\", \"unavailable\"]),\n root: z.string(), branch: z.string(), head: z.string(), baselinePaths: z.array(z.string()), reportPath: z.string(),\n findings: z.array(repairFindingSchema), diagnostics: z.array(z.string()),\n checks: z.object({ ran: z.array(z.string()), reused: z.array(z.string()),\n skipped: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })), auditReused: z.boolean().optional() }),\n counts: z.object({ resolved: z.number(), unresolved: z.number(), \"review-required\": z.number(), unverified: z.number() }),\n capture: z.enum([\"observed\", \"unknown\"]), scope: z.string(),\n }),\n});\nconst sharedSchema = z.object({ analysis: analysisSchema, digest: z.string() });\ntype Analysis = z.infer<typeof analysisSchema>;\nconst baselineDigest = async (ws: Workspace, state: State) => profilePhase(\"automation.baselines\", async () => hash(await Promise.all(\n state.baselines.map(async b => [b.path, await readStoreJson(ws.root, b.path)]),\n)));\n\nasync function matchingAnalysis(ws: Workspace, state: State, inputs: Inputs): Promise<{ analysis: Analysis | null; diagnostic?: string }> {\n const pointer = state.analysis;\n if (!pointer || pointer.fingerprint !== inputs.fingerprint) return { analysis: null };\n if (pointer.path !== ws.directory + \"/checks/analysis-\" + inputs.fingerprint + \".json\") {\n throw new Error(\"Invalid automation analysis cache path; inspect the retained state.\");\n }\n // This is a derived cache, not original repair evidence. Missing or malformed\n // data can be rebuilt, but storage/permission failures and unsafe paths remain\n // errors. Never discard or replace an original baseline to recover a cache.\n const invalid = { analysis: null, diagnostic: \"Discarded an invalid current-audit cache; audit preparation and original verification were repeated.\" };\n let raw: unknown;\n try { raw = await readStoreJson(ws.root, pointer.path); }\n catch (error) {\n const cause = (error as Error).cause;\n if (cause instanceof SyntaxError || cause instanceof Error && cause.message === \"expected a JSON object, received null\") return invalid;\n throw error;\n }\n if (raw === null) return { analysis: null };\n const parsed = sharedSchema.safeParse(raw);\n if (!parsed.success) return invalid;\n const stored = parsed.data;\n const a = stored.analysis;\n if (stored.digest !== hash(a) || a.id !== pointer.id || a.fingerprint !== inputs.fingerprint ||\n a.completedAt !== pointer.completedAt || a.report.root !== ws.root || a.report.branch !== ws.branch ||\n a.report.head !== inputs.head || hash(a.report.baselinePaths) !== hash(state.baselines.map(b => b.path))) {\n return invalid;\n }\n if (a.baselineDigest !== await baselineDigest(ws, state)) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n return { analysis: a };\n}\n\nasync function verifyInputs(ws: Workspace, inputs: Inputs) {\n return profilePhase(\"automation.revalidate\", () => withRepositoryInspection(ws.root, async () => {\n const [after, currentWs] = await Promise.all([readInputs(ws.root), workspace(ws.root)]);\n if (after.fingerprint !== inputs.fingerprint || currentWs.directory !== ws.directory) {\n throw new Error(\"Repository inputs or branch changed during automation; no current verification was recorded. Retry on a stable checkout.\");\n }\n }));\n}\n\n/** Expensive reads and checks never hold the shared state lock. */\nasync function computeAnalysis(ws: Workspace, state: State, inputs: Inputs, event: AutomationEvent, previousAudit?: AuditReport | null, cacheDiagnostic?: string) {\n const baselines = [...state.baselines];\n const now = new Date().toISOString();\n const empty: AutomationReport = { version: 1, status: \"unavailable\", root: ws.root, branch: ws.branch, head: inputs.head,\n baselinePaths: [], reportPath: \"\", findings: [],\n diagnostics: [\"No README.md or agent instruction files were discovered. Documentation capture is unavailable; other Mason tools remain usable.\"],\n checks: { ran: [], reused: [], skipped: [] }, counts: { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 },\n capture: \"unknown\", scope: SCOPE };\n if (!baselines.length && Object.values(inputs.docs).every(value => value === null)) {\n await verifyInputs(ws, inputs);\n return { baselines, report: empty, cache: null };\n }\n if (ws.branch === \"detached\" && state.latest) {\n const previous = await readStoreJson(ws.root, state.latest) as AutomationReport | null;\n if (!previous?.head || !/^[a-f0-9]{40,64}$/.test(previous.head)) throw new Error(\"The previous detached checkout evidence is unavailable.\");\n try { await git(ws.root, \"merge-base\", \"--is-ancestor\", previous.head, inputs.head); }\n catch { throw new Error(\"Detached checkout moved to a different history; original repair evidence was retained. Inspect that baseline explicitly.\"); }\n }\n let cached: unknown = null;\n const diagnostics: string[] = cacheDiagnostic ? [cacheDiagnostic] : [];\n try { cached = await readStoreJson(ws.root, ws.directory + \"/cache.json\"); }\n catch { diagnostics.push(\"Unreadable automation cache; checks are being recomputed.\"); }\n const cache = checkCache(cached, inputs);\n if (cache.diagnostic) diagnostics.push(cache.diagnostic);\n // Only complete, validated raw checks can bypass current-audit preparation.\n // Retained history and review outcomes are still evaluated on every invocation.\n const cachedAudit = previousAudit?.gitAvailable && previousAudit.headHash === inputs.head &&\n previousAudit.root === ws.root && !previousAudit.skippedChecks.length &&\n ALL_CHECKS.every(name => previousAudit.checksRun?.includes(name) && cache.has(name)) ? previousAudit : undefined;\n if (cachedAudit) for (const name of ALL_CHECKS) cache.reused.add(name);\n let currentAudit: AuditReport | null = null;\n const verifications = await withRepairSession(ws.root, cache.options, async repairs => {\n const saveBaseline = async () => {\n if (baselines.length >= 128) throw new Error(\"128 retained baselines need review; automatic capture stopped without discarding original evidence.\");\n const prepared = await repairs.prepare();\n baselines.push({ path: prepared.baselinePath, at: now, event: event.event, fingerprint: inputs.fingerprint });\n };\n if (!baselines.length) await saveBaseline();\n const verifications: RepairVerification[] = [];\n for (const baseline of baselines) verifications.push(await repairs.verify(baseline.path));\n const known = new Set(verifications.flatMap(v => v.findings.map(f => f.id)));\n // A clean initial baseline cannot retain findings introduced by a later rename.\n // Preserve those findings now, before another tool can edit or commit the docs.\n if (verifications.some(v => v.newFindings.some(f => !known.has(findingId(f))))) {\n await saveBaseline();\n verifications.push(await repairs.verify(baselines.at(-1)!.path));\n }\n currentAudit = await repairs.currentAudit();\n return verifications;\n }, () => verifyInputs(ws, inputs), cachedAudit);\n const merged = new Map<string, RepairFinding>();\n for (const verification of verifications) {\n for (const finding of verification.findings) {\n const previous = merged.get(finding.id);\n if (!previous || priority[finding.status] > priority[previous.status]) merged.set(finding.id, finding);\n }\n diagnostics.push(...verification.diagnostics);\n }\n\n const counts = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const finding of merged.values()) counts[finding.status]++;\n const report: AutomationReport = {\n version: 1, status: diagnostics.length || verifications.some(v => v.status === \"incomplete\") ? \"incomplete\" : counts.unresolved ? \"issues-remain\" : \"verified\",\n root: ws.root, branch: ws.branch, head: inputs.head, baselinePaths: baselines.map(b => b.path), reportPath: \"\",\n findings: [...merged.values()], diagnostics: [...new Set(diagnostics)],\n checks: { ran: [...cache.ran], reused: [...cache.reused].filter(name => !cache.ran.has(name)), skipped: verifications.at(-1)!.currentAudit?.skippedChecks ?? [], ...(cachedAudit ? { auditReused: true } : {}) },\n counts, capture: \"unknown\", scope: SCOPE,\n };\n return { baselines, report, currentAudit, cache: cache.ran.size || cached === null || cache.diagnostic ? cache.serialize() : null };\n}\n\n/** Per-input coordination shares expensive work; unrelated inputs can be checked concurrently. */\nasync function analyze(ws: Workspace, inputs: Inputs, event: AutomationEvent, startedAt: number) {\n return withLock(ws.root, ws.directory + \"/analysis/\" + inputs.fingerprint, async () => {\n const before = await loadState(ws);\n const { analysis: previous, diagnostic } = await matchingAnalysis(ws, before, inputs);\n // Overlap may share the whole verification. Sequential calls reuse only its\n // current audit: original history and review scopes need fresh inspection.\n if (previous && previous.completedAt >= startedAt) return { analysis: previous, shared: true };\n const originalDigest = await baselineDigest(ws, before);\n const computed = await computeAnalysis(ws, before, inputs, event, previous?.currentAudit as AuditReport | undefined, diagnostic);\n if (originalDigest !== await baselineDigest(ws, before)) throw new Error(\"Repair baseline was modified during automation; original evidence must be inspected.\");\n const id = randomUUID();\n const analysis = analysisSchema.parse({ id, fingerprint: inputs.fingerprint, completedAt: Date.now(),\n baselineDigest: await baselineDigest(ws, { ...before, baselines: computed.baselines }), report: computed.report, currentAudit: computed.currentAudit });\n const analysisPath = ws.directory + \"/checks/analysis-\" + inputs.fingerprint + \".json\";\n await withLock(ws.root, ws.directory, async () => {\n const state = await loadState(ws);\n // A concurrent check may have retained different original evidence. Never overwrite it.\n if (hash(state.baselines) !== hash(before.baselines) || state.analysis?.id !== before.analysis?.id) {\n throw new Error(\"Automation evidence changed during analysis; retry against the retained baselines.\");\n }\n await writeStoreJson(ws.root, analysisPath, { analysis, digest: hash(analysis) });\n if (computed.cache) await writeStoreJson(ws.root, ws.directory + \"/cache.json\", computed.cache);\n state.baselines = computed.baselines;\n state.analysis = { id, fingerprint: inputs.fingerprint, completedAt: analysis.completedAt, path: analysisPath };\n await writeStoreJson(ws.root, ws.directory + \"/state.json\", state);\n });\n return { analysis, shared: false };\n }, Math.max(0, 25000 - (Date.now() - startedAt)));\n}\n\n/** Durable lifecycle: read concurrently, then merge each call into the latest state. */\nexport async function automate(dir: string, event: AutomationEvent) {\n const startedAt = Date.now();\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n return recordExecution(ws.root, ws.directory, event.event, () => withRepositoryInspection(ws.root, async () => {\n const inputs = await readInputs(ws.root);\n const result = await profilePhase(\"automation.analysis\", () => analyze(ws, inputs, event, startedAt));\n if (result.shared) {\n await verifyInputs(ws, inputs);\n if (result.analysis.baselineDigest !== await baselineDigest(ws, await loadState(ws))) {\n throw new Error(\"Repair baseline was modified during shared automation; original evidence must be inspected.\");\n }\n }\n return profilePhase(\"automation.publish\", () => withLock(ws.root, ws.directory, async () => {\n const state = await loadState(ws);\n if (state.analysis?.id !== result.analysis.id) throw new Error(\"Automation evidence changed during publication; retry against the current inputs.\");\n const report = structuredClone(result.analysis.report) as AutomationReport;\n if (result.shared) report.checks = { ...report.checks, ran: [], reused: [...new Set([...report.checks.ran, ...report.checks.reused])], shared: true };\n report.reportPath = ws.directory + \"/checks/\" + randomUUID() + \".json\";\n const now = new Date().toISOString();\n const key = event.host && event.sessionId ? hash([event.host, event.sessionId]) : null;\n const newSession = key !== null && !state.sessions[key];\n if (key && !state.sessions[key]) {\n const keys = Object.keys(state.sessions).sort((a, b) => state.sessions[a].lastUsed.localeCompare(state.sessions[b].lastUsed));\n // Pending pre-edit captures cannot be evicted by another session's arrival.\n const removable = keys.filter(k => !Object.keys(state.sessions[k].pending).length);\n for (const expired of removable.slice(0, Math.max(0, keys.length - 31))) delete state.sessions[expired];\n if (Object.keys(state.sessions).length >= 128) throw new Error(\"Too many sessions with unfinished tool calls; original evidence was retained.\");\n state.sessions[key] = { host: event.host!, seen: null, continued: false,\n initialIssues: report.findings.filter(f => f.status === \"unresolved\").map(f => f.id), initialDocs: inputs.docs,\n lastUsed: now, mutationObserved: false, pending: {}, coverageGaps: [], events: {} };\n }\n const session = key ? state.sessions[key] : null;\n if (session) {\n session.lastUsed = now;\n session.events[event.event] = { at: now, count: (session.events[event.event]?.count ?? 0) + 1 };\n if (event.event === \"before_tool\" && event.mutating && event.toolId) {\n if (Object.keys(session.pending).length >= 128) throw new Error(\"Too many unfinished tool calls to track pre-edit evidence.\");\n session.pending[event.toolId] = inputs.fingerprint;\n }\n if (event.event === \"after_tool\" && event.mutating) {\n session.mutationObserved = true;\n if (!event.toolId || !session.pending[event.toolId]) {\n const gap = \"A tool completed without an observed matching pre-tool capture in this checkout; pre-edit coverage is unknown. The tool may have changed checkouts; captures are kept separately for each worktree.\";\n if (!session.coverageGaps.includes(gap)) session.coverageGaps.push(gap);\n }\n if (event.toolId) delete session.pending[event.toolId];\n }\n report.diagnostics.push(...session.coverageGaps);\n if (session.coverageGaps.length && report.status !== \"unavailable\") report.status = \"incomplete\";\n report.capture = report.status !== \"unavailable\" && !session.coverageGaps.length &&\n (session.events.session_start || session.events.before_tool) ? \"observed\" : \"unknown\";\n }\n const signature = hash([report.status, report.findings, report.diagnostics, report.checks.skipped]);\n const relevant = report.findings.some(f => f.status === \"unresolved\" && session &&\n (!session.initialIssues.includes(f.id) || session.initialDocs[f.original.anchor.doc] !== inputs.docs[f.original.anchor.doc]));\n const continueOnce = event.event === \"task_end\" && !!session?.mutationObserved && relevant && !session.continued && !event.stopHookActive;\n const notify = !session || newSession || signature !== session.seen || continueOnce;\n if (session) { session.seen = signature; if (continueOnce) session.continued = true; }\n const persistReport = !state.latest || state.fingerprint !== inputs.fingerprint || notify || event.event === \"task_end\";\n if (!persistReport) report.reportPath = state.latest!;\n state.updatedAt = now; state.fingerprint = inputs.fingerprint; state.latest = report.reportPath;\n if (persistReport) await writeStoreJson(ws.root, report.reportPath, report);\n await writeStoreJson(ws.root, ws.directory + \"/state.json\", state);\n return { report, message: notify ? summarize(report) : null, continueOnce };\n }));\n }));\n}\n\n/** Read-only inspection: configured hooks and observed runtime events are different facts. */\nexport async function automationStatus(dir: string) {\n const ws = await profilePhase(\"automation.workspace\", () => workspace(dir));\n const execution = await executionStatus(ws.root, ws.directory);\n const notifications = await failureNotifications(ws.root, ws.directory);\n const raw = await readStoreJson(ws.root, ws.directory + \"/state.json\");\n if (raw === null) return { version: 1, status: execution.status === \"not-observed\" ? \"not-observed\" : \"unavailable\", root: ws.root, branch: ws.branch, baselinePaths: [], hosts: {}, execution, notifications };\n const state = parseState(raw);\n if (state.root !== ws.root || state.gitDir !== ws.gitDir || state.branch !== ws.branch) throw new Error(\"Automation state belongs to another workspace.\");\n const inputs = await readInputs(ws.root);\n const latest = state.latest ? await readStoreJson(ws.root, state.latest) as AutomationReport | null : null;\n const hosts: Record<string, { sessions: number; observedEvents: string[] }> = {};\n for (const session of Object.values(state.sessions)) {\n const host = hosts[session.host] ??= { sessions: 0, observedEvents: [] };\n host.sessions++;\n host.observedEvents = [...new Set([...host.observedEvents, ...Object.keys(session.events)])];\n }\n const unfinished = [\"failed\", \"unknown\", \"running\"].includes(execution.status);\n return { version: 1, status: unfinished ? \"unavailable\" : inputs.fingerprint === state.fingerprint ? \"current\" : \"changed\", root: ws.root,\n branch: ws.branch, baselinePaths: state.baselines.map(b => b.path), reportPath: state.latest,\n verificationStatus: unfinished ? \"unavailable\" : latest?.status ?? \"unavailable\", hosts, execution, notifications,\n note: \"Observed events do not prove all tool paths are intercepted. Run check to verify the retained evidence.\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { git } from \"./evidence.js\";\nimport type { Host } from \"./store.js\";\n\nasync function repositoryRoot(dir: string): Promise<string | null> {\n if (!path.isAbsolute(dir)) throw new Error(\"Hook input working directory must be absolute.\");\n try { return await fs.realpath((await git(dir, \"rev-parse\", \"--show-toplevel\")).trim()); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\" ||\n /not a git repository/.test(String((error as { stderr?: string }).stderr))) return null;\n throw error;\n }\n}\n\n/** The host payload follows directory/worktree changes; the launch directory may not. */\nexport async function resolveHookRoot(host: Host, cwd: string, options: {\n launchCwd?: string; projectDir?: string;\n} = {}): Promise<string> {\n const current = await repositoryRoot(cwd);\n if (current) return current;\n const projectDir = options.projectDir ?? (host === \"claude\" ? process.env.CLAUDE_PROJECT_DIR : undefined);\n const projectRoot = projectDir ? await repositoryRoot(projectDir) : null;\n if (projectDir && !projectRoot) throw new Error(\"Hook input is outside Git and the host project is no longer a Git repository. Restore its history before running mason check.\");\n const launchRoot = await repositoryRoot(options.launchCwd ?? process.cwd());\n const roots = [...new Set([launchRoot, projectRoot].filter((root): root is string => root !== null))];\n if (!roots.length) throw new Error(\"Hook input is outside a Git repository and no project root is available. Return to the project and run mason check.\");\n if (roots.length > 1) throw new Error(\"Hook input is outside a Git repository and project roots disagree. Return to the intended checkout and run mason check; verification was not established.\");\n // CLAUDE_PROJECT_DIR stays at the original checkout after EnterWorktree.\n // Without a current repository, it cannot distinguish those checkouts.\n const worktrees = (await git(roots[0], \"worktree\", \"list\", \"--porcelain\", \"-z\"))\n .split(\"\\0\").filter(field => field.startsWith(\"worktree \"));\n if (worktrees.length !== 1) throw new Error(\"Hook input is outside a Git repository with multiple worktrees. Return to the intended worktree and run mason check; the active checkout is unknown.\");\n return roots[0];\n}\n","import { failureMessage, hookFailureMessage } from \"./execution.js\";\nimport { z } from \"zod\";\nimport { automate, observeReadOnlyTool, type AutomationEvent } from \"./runtime.js\";\nimport { hostSchema, type Host } from \"./store.js\";\nimport { resolveHookRoot } from \"./hook-root.js\";\n\nconst inputSchema = z.object({\n cwd: z.string().min(1), session_id: z.string().min(1).max(500),\n hook_event_name: z.enum([\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"Stop\"]),\n tool_name: z.string().optional(), tool_use_id: z.string().max(500).optional(),\n tool_input: z.unknown().optional(), stop_hook_active: z.boolean().optional(), permission_mode: z.string().optional(),\n});\nconst lifecycle: Record<z.infer<typeof inputSchema>[\"hook_event_name\"], AutomationEvent[\"event\"]> = {\n SessionStart: \"session_start\", UserPromptSubmit: \"turn_start\", PreToolUse: \"before_tool\", PostToolUse: \"after_tool\", Stop: \"task_end\",\n};\n\n/** Shell and unknown/MCP tools are conservatively observed: edits need not use a file editor. */\nexport function normalizeHook(host: Host, raw: unknown): { cwd: string; name: string; readOnly: boolean; event: AutomationEvent } {\n hostSchema.parse(host);\n const input = inputSchema.parse(raw);\n const readOnly = (host === \"claude\" ? /^(Read|Glob|Grep|WebSearch|WebFetch)$/ : /^(read_file|list_dir|grep_files|Read|Glob|Grep)$/).test(input.tool_name ?? \"\");\n return { cwd: input.cwd, name: input.hook_event_name, readOnly, event: {\n event: lifecycle[input.hook_event_name], host, sessionId: input.session_id, toolId: input.tool_use_id,\n mutating: !!input.tool_name && !readOnly,\n stopHookActive: input.stop_hook_active || input.permission_mode === \"plan\",\n } };\n}\n\nexport async function runAutomationHook(host: Host, stdin: string, options: { managed?: boolean } = {}): Promise<Record<string, unknown> | null> {\n let name = \"\";\n let hook: ReturnType<typeof normalizeHook> | undefined;\n try {\n if (Buffer.byteLength(stdin) > 1024 * 1024) throw new Error(\"Hook input exceeds 1 MiB.\");\n let raw: unknown;\n try { raw = JSON.parse(stdin); }\n catch { throw new Error(\"Hook input is not valid JSON.\"); }\n const input = normalizeHook(host, raw);\n hook = input;\n name = input.name;\n if (options.managed) {\n input.cwd = await resolveHookRoot(host, input.cwd);\n const { prepareLaunch } = await import(\"../setup/launcher.js\");\n if (!await prepareLaunch(host, { dir: input.cwd, allowInactive: true })) return null;\n }\n if ([\"before_tool\", \"after_tool\"].includes(input.event.event) && input.readOnly) {\n const observed = await observeReadOnlyTool(input.cwd, input.event);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(observed.root, input.event.event, { sessionId: input.event.sessionId, directory: observed.directory });\n return warning ? { systemMessage: warning } : null;\n }\n const result = await automate(input.cwd, input.event);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(result.report.root, input.event.event, {\n sessionId: input.event.sessionId, verificationStatus: result.report.status, reportPath: result.report.reportPath,\n });\n if (warning) result.message = [result.message, warning].filter(Boolean).join(\"\\n\");\n if (!result.message) return null;\n if (name === \"Stop\") {\n // A single continuation for actionable task findings; advisories never create a loop.\n return result.continueOnce ? { decision: \"block\", reason: result.message } : { systemMessage: result.message };\n }\n return { hookSpecificOutput: { hookEventName: name, additionalContext: result.message } };\n } catch (error) {\n const message = hook ? await hookFailureMessage(hook.cwd, host, hook.event.sessionId!, error) : failureMessage(error);\n if (!message) return null;\n // Hook failure is visible but does not turn documentation advice into an editing permission gate.\n return { systemMessage: message, ...([\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\"].includes(name)\n ? { hookSpecificOutput: { hookEventName: name, additionalContext: message } } : {}) };\n }\n}\n\nexport const HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"Stop\"] as const;\n/** Only guard Mason's generated launch, never interpret a custom command prefix. */\nexport function managedHookCommand(host: Host, platform = process.platform) {\n const command = `mason --setup-host ${host} auto hook --host ${host}`;\n return platform === \"win32\"\n ? `cmd.exe /d /s /c \"where mason >nul 2>nul & if errorlevel 1 (exit /b 0) else (${command})\"`\n : `if command -v mason >/dev/null 2>&1; then ${command}; fi`;\n}\nexport function knownManagedHookCommands(host: Host) {\n return [managedHookCommand(host, \"linux\"), managedHookCommand(host, \"win32\"), `mason --setup-host ${host} auto hook --host ${host}`];\n}\n/** Migration recognizes both platforms; runtime compatibility is platform-specific. */\nexport function compatibleManagedHookCommands(host: Host, platform = process.platform) {\n return [managedHookCommand(host, platform), `mason --setup-host ${host} auto hook --host ${host}`];\n}\nexport function hookConfig(host: Host, command = \"npx --no-install --package mason-context mason-auto\") {\n const handler = { type: \"command\", command: command === `mason --setup-host ${host} auto`\n ? managedHookCommand(host) : command + \" hook --host \" + host, timeout: 30 };\n return { hooks: Object.fromEntries(HOOK_EVENTS.map(name => [name,\n [{ ...([\"PreToolUse\", \"PostToolUse\"].includes(name) ? { matcher: \".*\" } : {}), hooks: [{ ...handler }] }],\n ])) };\n}\n","import { z } from \"zod\";\nimport { parse } from \"smol-toml\";\nimport { hash } from \"../automation/evidence.js\";\nimport { readText, type FileEdit } from \"./files.js\";\n\nexport const OWNERSHIP_PATH = \".mason/local/integration.json\";\nexport const BLOCKS = [\n [\"<!-- mason:start -->\", \"<!-- mason:end -->\"],\n [\"<!-- mason:agents:start -->\", \"<!-- mason:agents:end -->\"],\n [\"# mason:mcp:start\", \"# mason:mcp:end\"],\n] as const;\nconst fileSchema = z.object({ created: z.boolean(), initialHash: z.string(),\n blocks: z.record(z.string()), mcpHash: z.string().optional(), hookCommands: z.array(z.string()).optional(), hooks: z.record(z.array(z.string())).optional() });\nexport const ownershipSchema = z.object({ version: z.literal(1), files: z.record(fileSchema) });\nexport type Ownership = z.infer<typeof ownershipSchema>;\n\nexport function blockSpan(text: string, start: string, end: string) {\n const starts = text.split(start).length - 1, ends = text.split(end).length - 1;\n if (!starts && !ends) return null;\n const from = text.indexOf(start), to = text.indexOf(end) + end.length;\n if (starts !== 1 || ends !== 1 || to <= from) throw new Error(\"Ambiguous Mason markers; inspect the marked block manually.\");\n return { from, to, text: text.slice(from, to) };\n}\n\n/** Persist ownership before shared edits so interrupted setup remains removable. */\nexport async function ownershipEdit(root: string, edits: FileEdit[], hookCommands: Record<string, string> = {}): Promise<FileEdit> {\n const before = await readText(root, OWNERSHIP_PATH);\n const record: Ownership = before === null ? { version: 1, files: {} } : ownershipSchema.parse(JSON.parse(before));\n for (const edit of edits) {\n const previous = record.files[edit.path];\n const entry = { created: edit.before === null || (previous?.created ?? false),\n initialHash: edit.before === null || previous?.initialHash === hash(edit.before) ? hash(edit.after) : previous?.initialHash ?? hash(edit.after),\n blocks: Object.fromEntries(BLOCKS.flatMap(([start, end]) => {\n const block = blockSpan(edit.after, start, end);\n return block ? [[start, hash(block.text)]] : [];\n })),\n };\n const mcp = edit.path === \".codex/config.toml\" ? (parse(edit.after).mcp_servers as Record<string, unknown>)?.mason\n : edit.path === \".mcp.json\" ? JSON.parse(edit.after).mcpServers?.mason : undefined;\n const hooks = edit.path === \".codex/hooks.json\" || edit.path === \".claude/settings.json\"\n ? JSON.parse(edit.after).hooks as Record<string, Array<{ hooks: unknown[] }>> | undefined : undefined;\n record.files[edit.path] = { ...entry, ...(mcp === undefined ? {} : { mcpHash: hash(mcp) }),\n ...(hookCommands[edit.path] ? { hookCommands: [...new Set([...(previous?.hookCommands ?? []), hookCommands[edit.path]])] } : {}),\n ...(hooks === undefined ? {} : { hooks: Object.fromEntries(Object.entries(hooks).map(([event, groups]) =>\n [event, groups.flatMap(group => group.hooks.map(hash))])) }),\n };\n }\n return { path: OWNERSHIP_PATH, before, after: JSON.stringify(record, null, 2) + \"\\n\" };\n}\n\n/** Forget earlier commands only after their replacement and installation record were saved. */\nexport async function completedHookOwnership(root: string, file: string, command: string): Promise<FileEdit> {\n const before = await readText(root, OWNERSHIP_PATH);\n const record = ownershipSchema.parse(JSON.parse(before ?? \"null\"));\n record.files[file].hookCommands = [command];\n return { path: OWNERSHIP_PATH, before, after: JSON.stringify(record, null, 2) + \"\\n\" };\n}\n","import { z } from \"zod\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { workspace } from \"./evidence.js\";\nimport { HOOK_EVENTS, hookConfig, knownManagedHookCommands } from \"./adapters.js\";\nimport { withLock, type Host } from \"./store.js\";\nimport { readText } from \"../setup/files.js\";\nimport { OWNERSHIP_PATH, ownershipSchema } from \"../setup/ownership.js\";\n\nconst groupSchema = z.object({ hooks: z.array(z.object({ type: z.string(), command: z.string().optional() }).passthrough()) }).passthrough();\nexport const automationConfigSchema = z.object({ hooks: z.record(z.array(groupSchema)).optional() }).passthrough();\nexport const recordSchema = z.object({ version: z.literal(1), hosts: z.record(z.object({ command: z.string() })) });\nexport const AUTOMATION_PATH = \".mason/local/automation.json\";\nasync function installationRecord(root: string) {\n return recordSchema.parse(await readStoreJson(root, AUTOMATION_PATH) ?? { version: 1, hosts: {} });\n}\nexport const configPath = (host: Host) => host === \"claude\" ? \".claude/settings.json\" : \".codex/hooks.json\";\n\n/** Explicit install preserves other settings and hooks, replacing only Mason's recorded handlers. */\nexport async function installAutomation(dir: string, host: Host, command?: string) {\n const ws = await workspace(dir);\n return withLock(ws.root, \".mason/reports/setup-lock\", () => installLocked(ws.root, host, command));\n}\n\nexport async function planAutomationInstall(root: string, host: Host, command?: string) {\n const file = configPath(host);\n const before = await readText(root, file);\n const existing = automationConfigSchema.parse(JSON.parse(before ?? \"{}\"));\n const record = await installationRecord(root);\n const desired = hookConfig(host, command);\n const newCommand = desired.hooks.SessionStart[0].hooks[0].command;\n const previous = record.hosts[host]?.command;\n const ownershipText = await readText(root, OWNERSHIP_PATH);\n const pending = ownershipText === null ? [] : ownershipSchema.parse(JSON.parse(ownershipText)).files[file]?.hookCommands ?? [];\n // A clone has shared hooks but no local ownership receipt.\n const owned = new Set([previous, ...pending, newCommand, ...knownManagedHookCommands(host)]);\n const hooks = existing.hooks ?? {};\n for (const event of HOOK_EVENTS) {\n hooks[event] = (hooks[event] ?? []).map(group => ({ ...group,\n hooks: group.hooks.filter(handler => !(handler.type === \"command\" && typeof handler.command === \"string\" &&\n owned.has(handler.command))),\n })).filter(group => group.hooks.length);\n hooks[event].push(...desired.hooks[event]);\n }\n record.hosts[host] = { command: newCommand };\n return { file, before, config: { ...existing, hooks }, record, newCommand };\n}\n\nasync function installLocked(root: string, host: Host, command?: string) {\n const { file, before, config, record, newCommand } = await planAutomationInstall(root, host, command);\n const { ancillaryEdits } = await import(\"../setup/config.js\");\n const { applyEdit } = await import(\"../setup/files.js\");\n const { ownershipEdit, completedHookOwnership } = await import(\"../setup/ownership.js\");\n const edit = { path: file, before, after: JSON.stringify(config, null, 2) + \"\\n\" };\n const ancillary = await ancillaryEdits(root);\n await applyEdit(root, await ownershipEdit(root, [edit], { [file]: newCommand }));\n for (const edit of ancillary) await applyEdit(root, edit);\n await applyEdit(root, edit);\n // Keep the previous command until its replacement is installed. Ownership\n // records the pending command so teardown/reinstallation can resume either side.\n await writeStoreJson(root, AUTOMATION_PATH, record);\n await applyEdit(root, await completedHookOwnership(root, file, newCommand));\n return { version: 1, host, configPath: file, status: \"configured\", command: newCommand,\n events: HOOK_EVENTS,\n next: host === \"codex\"\n ? \"Review/trust these hooks using Codex /hooks and start a new session. mason-auto status reports observed events separately from configuration.\"\n : \"Start a new Claude Code session. mason-auto status reports observed events separately from configuration.\",\n note: \"Install mason-context in the project before using the default command. Ignore .mason/reports/ to keep local evidence out of commits. Hooks preserve evidence and suggest scoped repairs; they do not approve edits or decisions.\" };\n}\n\nexport async function installedAutomation(dir: string) {\n const ws = await workspace(dir);\n const record = await installationRecord(ws.root);\n const result: Record<string, unknown> = {};\n for (const host of [\"claude\", \"codex\"] as const) {\n const expected = record.hosts[host];\n if (!expected) continue;\n const current = automationConfigSchema.parse(await readStoreJson(ws.root, configPath(host)) ?? {});\n const configuredEvents = HOOK_EVENTS.filter(event => current.hooks?.[event]?.some(group =>\n group.hooks.some(handler => handler.type === \"command\" && handler.command === expected.command)));\n result[host] = { configPath: configPath(host), configuredEvents,\n status: current.disableAllHooks === true ? \"disabled\" : configuredEvents.length === HOOK_EVENTS.length ? \"configured\" : \"incomplete\",\n runtime: \"Host version, trust, policy, and tool coverage still determine execution; inspect observed events.\" };\n }\n return result;\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { parse, stringify } from \"smol-toml\";\nimport { z } from \"zod\";\nimport { CLAUDE_MD_SECTION } from \"../mcp/init.js\";\nimport { DOC_CANDIDATES } from \"../audit/docs.js\";\nimport { hookConfig, compatibleManagedHookCommands } from \"../automation/adapters.js\";\nimport { configPath, automationConfigSchema, AUTOMATION_PATH } from \"../automation/install.js\";\nimport type { Host } from \"../automation/store.js\";\nimport { readText, managedBlock, type FileEdit } from \"./files.js\";\nimport { hookCommand, mcpCommand } from \"./launcher.js\";\n\nconst object = z.record(z.unknown());\nexport const mcpPath = (host: Host) => host === \"codex\" ? \".codex/config.toml\" : \".mcp.json\";\nconst TOML_START = \"# mason:mcp:start\", TOML_END = \"# mason:mcp:end\";\nconst POINTER_START = \"<!-- mason:agents:start -->\", POINTER_END = \"<!-- mason:agents:end -->\";\nexport async function instructionEdits(root: string, host?: Host) {\n const found = await Promise.all(DOC_CANDIDATES.map(async file => ({ path: file, text: await readText(root, file) })));\n const existing = found.find(f => f.text !== null);\n const primary = host === \"codex\" && found[0].text === null ? { path: \"AGENTS.md\", text: null }\n : existing ?? { path: \"AGENTS.md\", text: null };\n const originalGuidance = primary.text === null && existing ? \"Follow the existing project conventions in \" + existing.path + \".\\n\" : \"\";\n const edits: FileEdit[] = [{ path: primary.path, before: primary.text,\n after: managedBlock(primary.text ?? originalGuidance, \"<!-- mason:start -->\", \"<!-- mason:end -->\", CLAUDE_MD_SECTION.split(\"\\n\").slice(1, -1).join(\"\\n\")) }];\n if (primary.path === \"AGENTS.md\") {\n const secondary = found.filter(f => f.path !== \"AGENTS.md\" && f.text !== null);\n if (host === \"claude\" && !secondary.length) secondary.push({ path: \"CLAUDE.md\", text: null });\n for (const file of secondary) {\n const text = file.text ?? \"\";\n const legacy = text.includes(\"<!-- mason:start -->\") || text.includes(\"<!-- mason:end -->\");\n const imported = \"@\" + (file.path.startsWith(\".claude/\") ? \"../AGENTS.md\" : \"AGENTS.md\");\n if (text.trim() === imported) continue;\n // Claude expands native imports at session start; a prose mention does not load the guidance.\n const pointer = \"Mason project knowledge and shared project instructions:\\n\" + imported;\n edits.push({ path: file.path, before: file.text,\n after: managedBlock(text, legacy ? \"<!-- mason:start -->\" : POINTER_START, legacy ? \"<!-- mason:end -->\" : POINTER_END, pointer) });\n }\n }\n return edits;\n}\n\n/** Retain host options and environment; replace only transport/launch details. */\nfunction managedMcp(previous: unknown, host: Host) {\n const options = previous === undefined ? {} : object.parse(previous);\n for (const key of [\"command\", \"args\", \"url\", \"type\", \"headers\", \"http_headers\", \"env_http_headers\", \"bearer_token_env_var\"]) delete options[key];\n return { ...options, ...(host === \"claude\" ? { type: \"stdio\" } : {}), ...mcpCommand(host) };\n}\n\nexport async function mcpEdit(root: string, host: Host): Promise<FileEdit> {\n const file = mcpPath(host), before = await readText(root, file);\n if (host === \"claude\") {\n const config = before === null ? {} : object.parse(JSON.parse(before));\n const servers = object.parse(config.mcpServers ?? {});\n // Mason owns only its named server; other servers and settings retain their values.\n return { path: file, before, after: JSON.stringify({ ...config, mcpServers: { ...servers, mason: managedMcp(servers.mason, host) } }, null, 2) + \"\\n\" };\n }\n const config = parse(before ?? \"\");\n const managed = (before ?? \"\").includes(TOML_START);\n const servers = config.mcp_servers as Record<string, unknown> | undefined;\n const desired = managedMcp(servers?.mason, host);\n let base = before ?? \"\";\n if (servers?.mason && !managed) {\n // Migrate ordinary explicit tables without reserializing the rest of TOML.\n // Validate the whole semantic result afterwards, including multiline strings.\n const headers = [...base.matchAll(/^\\s*\\[\\[?.+?\\]\\]?[^\\S\\r\\n]*(?:#.*)?$/gm)];\n const spans = headers.flatMap((header, index) => /^\\s*\\[mcp_servers\\.mason(?:\\.[A-Za-z0-9_-]+)*\\]/.test(header[0])\n ? [{ start: header.index!, end: headers[index + 1]?.index ?? base.length }] : []);\n if (!spans.length) throw new Error(\"Cannot safely migrate the existing Mason MCP TOML entry. Use an explicit [mcp_servers.mason] table and rerun setup; the file was retained.\");\n for (const span of spans.reverse()) base = base.slice(0, span.start) + base.slice(span.end);\n }\n const after = managedBlock(base, TOML_START, TOML_END, stringify({ mcp_servers: { mason: desired } }).trimEnd());\n const parsed = parse(after);\n const expected = { ...config, mcp_servers: { ...(servers ?? {}), mason: desired } };\n if (!isDeepStrictEqual(parsed, expected)) throw new Error(\"Could not safely configure the Mason MCP entry without changing other settings.\");\n return { path: file, before, after };\n}\n\nexport async function hookEdits(root: string, host: Host): Promise<FileEdit[]> {\n const file = configPath(host), before = await readText(root, file);\n const { planAutomationInstall } = await import(\"../automation/install.js\");\n const plan = await planAutomationInstall(root, host, hookCommand(host));\n return [{ path: file, before, after: JSON.stringify(plan.config, null, 2) + \"\\n\" },\n { path: AUTOMATION_PATH, before: await readText(root, AUTOMATION_PATH), after: JSON.stringify(plan.record, null, 2) + \"\\n\" }];\n}\n\nexport async function ancillaryEdits(root: string) {\n const ignore = await readText(root, \".gitignore\");\n const rules = [\"!/.mason/\", \"/.mason/*\",\n \"!/.mason/decisions/\", \"!/.mason/decisions/**\", \"!/.mason/reviews/\", \"!/.mason/reviews/**\", \"!/.mason/config.json\", \"!/.mason/snapshot.json\",\n \"/.mason/local/\", \"/.mason/reports/\"].join(\"\\n\");\n return [{ path: \".gitignore\", before: ignore, after: managedBlock(ignore ?? \"\", \"# mason:ignore:start\", \"# mason:ignore:end\", rules) }];\n}\n\nexport async function inspectHostConfig(root: string, host: Host, plannedMcp?: string) {\n const text = plannedMcp ?? await readText(root, mcpPath(host));\n const config = host === \"codex\" ? parse(text ?? \"\") : object.parse(JSON.parse(text ?? \"{}\"));\n const servers = (host === \"codex\" ? config.mcp_servers : config.mcpServers) as Record<string, unknown> | undefined;\n const hooks = automationConfigSchema.parse(JSON.parse(await readText(root, configPath(host)) ?? \"{}\"));\n const expected = hookConfig(host, hookCommand(host));\n const compatible = compatibleManagedHookCommands(host);\n const mcp = servers?.mason === undefined ? null : object.parse(servers.mason);\n return { mcp, mcpDisabled: mcp?.enabled === false, hooks: Object.fromEntries(Object.keys(expected.hooks).map(event => [event,\n (hooks.hooks?.[event] ?? []).flatMap(group => group.hooks.filter(handler => compatible.includes(handler.command ?? \"\")).map(handler => ({ ...group, hooks: [handler] })) ?? [])])),\n disabled: hooks.disableAllHooks === true || (config.features as Record<string, unknown> | undefined)?.hooks === false ||\n (config.features as Record<string, unknown> | undefined)?.codex_hooks === false };\n}\n","import { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { applyEdit, readText, type FileEdit } from \"../setup/files.js\";\n\nexport interface ProjectMarker {\n version: 1;\n initializedAt: string;\n features?: {\n confluence?: boolean;\n };\n}\n\nconst markerSchema = z.object({\n version: z.literal(1), initializedAt: z.string(),\n features: z.object({ confluence: z.boolean().optional() }).passthrough().optional(),\n}).passthrough();\n\nexport async function loadProjectMarker(rootDir: string): Promise<ProjectMarker | null> {\n const raw = await readStoreJson(rootDir, \".mason/local/project.json\");\n if (raw === null) return null;\n const marker = markerSchema.parse(raw);\n return { ...marker, features: await loadProjectFeatures(rootDir) };\n}\n\nexport async function loadProjectFeatures(rootDir: string) {\n const config = z.record(z.unknown()).parse(await readStoreJson(rootDir, \".mason/config.json\") ?? {});\n return z.object({ confluence: z.boolean().optional() }).passthrough().parse(config.features ?? {});\n}\n\nexport async function saveProjectMarker(rootDir: string, marker: ProjectMarker): Promise<void> {\n const { ancillaryEdits } = await import(\"../setup/config.js\");\n for (const edit of [...await ancillaryEdits(rootDir), ...await projectMarkerEdits(rootDir, marker)]) await applyEdit(rootDir, edit);\n}\n\nasync function projectMarkerEdits(rootDir: string, marker: ProjectMarker): Promise<FileEdit[]> {\n const { features, ...local } = markerSchema.parse(marker);\n const file = \".mason/local/project.json\";\n const edits = [{ path: file, before: await readText(rootDir, file), after: JSON.stringify(local, null, 2) + \"\\n\" }];\n if (features && Object.keys(features).length) {\n const configPath = \".mason/config.json\", before = await readText(rootDir, configPath);\n const config = z.record(z.unknown()).parse(JSON.parse(before ?? \"{}\"));\n config.features = { ...z.record(z.unknown()).parse(config.features ?? {}), ...features };\n edits.push({ path: configPath, before, after: JSON.stringify(config, null, 2) + \"\\n\" });\n }\n return edits;\n}\n\n/** Marker-delimited project instructions make the tools useful in later sessions. */\nexport const CLAUDE_MD_SECTION = `<!-- mason:start -->\n## Mason project knowledge\n\nMason provides recorded decisions and file impact over MCP. A concept map is optional.\n\n- Task, bug, change request, or investigation of why the project works this way → \\`get_context\\` with the task text and known files: matching decisions, related tests, impact, and any available map entries.\n- Before editing a file → \\`get_impact\\` to check references, tests, and historical change partners.\n- Investigation or correction reveals a reusable project lesson → \\`save_decision\\` before finishing. Capture only the lasting constraint and reason, with anchors and known sources, owner, and recorder. This creates a proposal; never infer approval. Preserve uncertain causes and unknown attribution. Route project lessons here; keep personal preferences in agent memory. Skip code summaries, current checkout status, temporary task permissions, session trivia, and secrets. No qualifying lesson means no record.\n- Before saving, compare the lesson with matching \\`get_context\\` records and any pending proposal. If new evidence changes the same lesson's assumptions, scope, or recommended action, revise it with \\`save_decision(id: existingId)\\`, including when it is accepted. Preserve supported rationale and sources, replace obsolete instructions, and add the new evidence. Create a separate record for a genuinely distinct lesson; skip unchanged restatements. Revision preserves history and leaves the accepted version operative until authorized review.\n- Consult trust metadata before relying on entries: unknown or changed freshness requires inspection, stale or unknown map verification requires a fresh evidence review, and a recorded failed verdict means the description must be corrected. Check approval too: proposals are suggestions, legacy records are unreviewed, and accepted decisions are recorded constraints subject to freshness checks. An accepted revision remains operative while a pending proposal is reviewed; keep both versions and their freshness distinct.\n- Asked to review or re-verify a decision → \\`review_decision\\` first to inspect content, sources, history, and code changes. Record acceptance, reaffirmation, or retirement only when authorized by the user or a cited team review, with the actual reviewer and reason. Never infer approval from unchanged code. Review and commit the local record through the normal project workflow.\n- For an architectural overview, use \\`get_snapshot\\` if a map is available. If \\`map.status\\` is missing or invalid, use available decisions and source evidence; do not start building a map unless requested.\n- \\`mason_init\\` returns documentation audit and committed-diff review results, plus a short setup guide. Pass \\`evidence\\` with local CI manifest paths to include test and analysis results; the CLI equivalent is \\`mason-review --evidence <manifest>\\`. State skipped, unavailable, stale, or unknown checks explicitly. Related accepted decisions identify review context, not proven violations.\n\n- When documentation repair is authorized, use \\`mason_repair(action: \"prepare\")\\` before edits, keep its baselinePath, and use \\`mason_repair(action: \"verify\", baselinePath)\\` after edits and any final doc commit. Report every original finding's outcome and any new findings. Suppressed advisories remain unresolved; editing a doc does not approve it.\n- When advisory assessment is authorized, use \\`review_advisory(action: \"prepare\", baselinePath, findingId)\\` to inspect original evidence and history. Record \\`addressed\\`, \\`inapplicable\\`, or \\`deferred\\` with the actual reviewer, reason in note, and returned reviewToken only after relevant edits are committed. Commit the assessment and verify the same baseline again. Relevant evidence changes reopen it; deferral stays outstanding. Decision findings use \\`review_decision\\`; advisory closure never approves a decision.\n\n- When Mason automation is installed, use \\`mason_automation(action: \"status\")\\` to inspect configured hooks and observed events, and \\`mason_automation(action: \"check\")\\` to resume its retained repair evidence. CLI fallback: \\`mason-auto status\\` / \\`mason-auto check\\`. Preserve existing baselines across sessions. Automatic checks do not authorize unrelated repairs or approve advisories.\n\nInspect source for what the retrieved context does not answer.\n<!-- mason:end -->`;\n\nexport type InitMode = \"quickstart\" | \"map\" | \"setup\";\n\nconst ASSISTANT_SETUP = `UNIFIED SETUP\nWhen the user requests Mason setup, call mason_init again with mode: \"setup\" and host: \"codex\" or \"claude\" for the assistant being configured. This uses the same engine as mason-auto setup: retain the initial audit before instruction edits, use the installed mason command on PATH, merge project MCP configuration and hooks, update marker-delimited instructions and Git ignore rules, and record setup. A concept map is optional.\nIf the user only requested inspection or review, report findings without running setup. The setup result distinguishes configured from observed activation. Explain the host's native trust step and request a new session; never trust hooks on the user's behalf or claim activation from generated configuration alone. After a normal task finishes, mason_automation(action: \"status\") or mason-auto status reports observed context use and hook events. Existing findings remain reviewable; setup does not approve advisories or manufacture decisions.\n\nThe managed project guidance is:\n${CLAUDE_MD_SECTION}`;\n\nconst QUICKSTART_PLAYBOOK = `Start with the audit and review results included in this response. No concept map is required.\n\n1. Explain the actionable findings with their source evidence. Separate audit issues, advisories, and skipped checks. The review covers committed changes from the merge base to HEAD; workingTree paths are not included in that review. An unavailable or empty check is not proof that the project is correct. Use the CLI for full output if a summary is truncated.\n2. Address findings within the user's requested scope. Setup alone authorizes Mason host configuration, hooks, instructions, and ignore rules; rewriting existing project claims requires repair scope. If repair is authorized, call \\`mason_repair(dir, action: \"prepare\")\\` before editing; it saves the full original findings even when this summary is truncated. Inspect relevant source, make grounded edits, then call \\`mason_repair(dir, action: \"verify\", baselinePath)\\` with that same baseline, including after any final doc commit. Report resolved, unresolved, review-required, unverified, and new findings. Keep suppressed advisories visible even when setup has already dirtied a doc. Do not invent a decision just to populate the store.\n3. When the task reveals a real lesson or constraint, compare matching \\`get_context\\` records first. If its assumptions, scope, or recommended action changed, revise that record using \\`save_decision(id: existingId)\\`; create a separate record for a genuinely distinct lesson and skip unchanged restatements. Include title, body, category, anchors, and known owner/source/actor information. Preserve supported rationale and sources, replace obsolete instructions, and add new evidence. Missing attribution can be added later. The tool writes a local proposal; editing it preserves revision history and requires a new acceptance, while any earlier accepted revision remains operative. An unchanged save never refreshes its evidence. When decision review is requested, \\`review_decision\\` prepares the record and code evidence before any authorized verdict. Review and commit records through the normal workflow. Retrieve it on the next relevant task with \\`get_context(dir, task, files)\\`.\n\n${ASSISTANT_SETUP}\n\nOPTIONAL ARCHITECTURE MAP\nA full map adds feature and flow navigation. Build it only if the user requests it, by calling \\`mason_init(dir, mode: \"map\")\\`. Decision capture and task context do not depend on that build.`;\n\nconst MAP_PLAYBOOK = `The user has requested a full architecture map. Follow this Map-Reduce workflow to cover the codebase. Report the audit and review findings included in this response before beginning.\n\nPHASE 1 — Map (loop until done)\nGoal: process every file in the codebase, batch by batch, producing a partial concept map per batch.\n\n 1. Call \\`generate_snapshot_batch(dir)\\` (omit offset on the first call).\n The response includes:\n - \\`batchId\\`: identifier for this batch\n - \\`offset\\`, \\`nextOffset\\`, \\`totalFiles\\`: progress markers\n - \\`instructions\\`: the system prompt for the batch step\n - \\`prompt\\`: the files in this batch (skeletons + a few deeper bodies)\n 2. Following the \\`instructions\\`, derive features and flows that involve ONLY the files in this batch. Use product-natural feature names (\"home screen\", not \"HomeScreenAndroid\") so the reduce step can merge platform variants.\n 3. Call \\`save_partial_snapshot(dir, batchId, offset, features, flows)\\` to persist the partial.\n 4. If \\`nextOffset\\` is null, the Map phase is done. Otherwise call \\`generate_snapshot_batch(dir, offset=nextOffset)\\` and repeat from step 2.\n\n Briefly tell the user \"Batch N of M done\" each iteration so they see progress.\n\n CRITICAL RULES FOR PHASE 1:\n - Derive features and file paths ONLY from what appears verbatim in the \\`prompt\\` field of each batch response. NEVER invent paths from memory, prior projects, or what you assume a project of this kind would contain. If you have not seen a path in a batch \\`prompt\\`, do not put it in \\`features.files\\` or \\`flows.chain\\`.\n - Process batches SEQUENTIALLY: one \\`generate_snapshot_batch\\` → derive → one \\`save_partial_snapshot\\` → next \\`generate_snapshot_batch\\`. Do not parallelise. Do not call \\`save_snapshot\\` during this phase — that is a Phase 2 step.\n - You must walk every batch until \\`nextOffset\\` is null. Do not stop early. Do not skip ahead to reduce until every batch has been saved as a partial.\n\nPHASE 2 — Reduce (once)\nGoal: merge all partial maps into one coherent product-shaped catalog.\n\n 1. Call \\`reduce_snapshot(dir)\\`. It returns every partial map plus reconciliation instructions.\n 2. Follow the instructions to produce a unified \\`features\\` and \\`flows\\` map. Specifically: merge platform variants (\"home Android\" + \"home iOS\" → \"home screen\"), dedupe near-duplicates, reconcile descriptions, and ensure every file from every partial appears somewhere in the final map.\n 3. Call \\`save_snapshot(dir, features, flows)\\` ONCE with the unified map. Mason detects that partials exist and replaces the snapshot wholesale (rather than merging with any earlier state) and then clears the partials. Do not call \\`save_snapshot\\` more than once per Map-Reduce run.\n\n${ASSISTANT_SETUP}\n\nIf a build is interrupted, its partials remain in \\`.mason/partial-snapshots/\\`. Re-run \\`mason_init(dir, mode: \"map\")\\` to obtain this workflow again.`;\n\nexport function setupPlaybook(mode: InitMode = \"quickstart\"): string {\n return mode === \"map\" ? MAP_PLAYBOOK : QUICKSTART_PLAYBOOK;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\n/**\n * History window for the co-change matrix. One capped git log for the whole\n * repo — unlike impact.ts's per-target walk, review analyzes many files at\n * once and needs a single pass.\n */\nconst HISTORY_COMMITS = 1500;\n\n/** Below this many commits for a file, a co-change rate is noise. */\nconst MIN_FILE_COMMITS = 5;\n/** A partner must share at least this many commits to count. */\nconst MIN_SHARED_COMMITS = 4;\n/** ...and appear in at least this fraction of the changed file's commits. */\nconst MIN_COCHANGE_RATE = 0.6;\n/** Commits touching more files than this are refactors, not signal. */\nconst MAX_COMMIT_FILES = 30;\n\nexport interface CochangeFinding {\n changedFile: string;\n missingPartner: string;\n sharedCommits: number;\n fileCommits: number;\n /** sharedCommits / fileCommits, rounded to 2 places. */\n rate: number;\n}\n\ninterface CochangeMatrix {\n commitsByFile: Map<string, Set<number>>;\n totalCommits: number;\n}\n\nasync function buildMatrix(resolvedRoot: string): Promise<CochangeMatrix | null> {\n try {\n const { stdout: shallow } = await exec(\"git\", [\"rev-parse\", \"--is-shallow-repository\"], { cwd: resolvedRoot });\n if (shallow.trim() === \"true\") return null;\n const { stdout } = await exec(\n \"git\",\n [\"log\", `-n${HISTORY_COMMITS}`, \"--format=%x01\", \"--name-only\", \"-M\"],\n { cwd: resolvedRoot, maxBuffer: 100 * 1024 * 1024 }\n );\n const commitsByFile = new Map<string, Set<number>>();\n const blocks = stdout.split(\"\\x01\");\n let index = 0;\n for (const block of blocks) {\n const files = block\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.length > 0 && !l.startsWith(\".mason/\"));\n if (files.length === 0 || files.length > MAX_COMMIT_FILES) continue;\n for (const file of files) {\n let set = commitsByFile.get(file);\n if (!set) {\n set = new Set();\n commitsByFile.set(file, set);\n }\n set.add(index);\n }\n index++;\n }\n return { commitsByFile, totalCommits: index };\n } catch {\n return null;\n }\n}\n\n/**\n * For each changed file, find its historical co-change partners that this\n * diff leaves untouched: files that appeared in >= MIN_COCHANGE_RATE of the\n * changed file's commits (within the window) but are absent from the diff.\n * Deterministic — pure git history, no LLM. Returns null when history is\n * unavailable.\n */\nexport async function findMissingPartners(\n resolvedRoot: string,\n changedFiles: string[],\n existsOnDisk: (relPath: string) => Promise<boolean>,\n allChangedFiles: string[] = changedFiles\n): Promise<CochangeFinding[] | null> {\n const matrix = await buildMatrix(resolvedRoot);\n if (!matrix) return null;\n\n const changedSet = new Set(allChangedFiles);\n const findings: CochangeFinding[] = [];\n\n for (const changedFile of changedFiles) {\n const fileCommits = matrix.commitsByFile.get(changedFile);\n if (!fileCommits || fileCommits.size < MIN_FILE_COMMITS) continue;\n\n for (const [partner, partnerCommits] of matrix.commitsByFile) {\n if (partner === changedFile || changedSet.has(partner)) continue;\n let shared = 0;\n for (const c of fileCommits) {\n if (partnerCommits.has(c)) shared++;\n }\n if (shared < MIN_SHARED_COMMITS) continue;\n const rate = shared / fileCommits.size;\n if (rate < MIN_COCHANGE_RATE) continue;\n if (!(await existsOnDisk(partner))) continue;\n findings.push({\n changedFile,\n missingPartner: partner,\n sharedCommits: shared,\n fileCommits: fileCommits.size,\n rate: Math.round(rate * 100) / 100,\n });\n }\n }\n\n findings.sort((a, b) => b.rate - a.rate || b.sharedCommits - a.sharedCommits);\n return findings;\n}\n","import { normalizeRepoPath } from \"../../utils/paths.js\";\n\n/** Map reported paths from the runner's checkout; never read source via a report URI. */\nexport function evidencePath(value: string, sourceRoot: string, uri = false): string | null {\n if (value.length > 4000) return null;\n let file = value;\n try {\n if (uri) {\n if (file.startsWith(\"file:\")) {\n const url = new URL(file);\n if (url.hostname && url.hostname !== \"localhost\") return null;\n file = decodeURIComponent(url.pathname).replace(/^\\/([A-Za-z]:\\/)/, \"$1\");\n } else {\n if (/^[a-z][a-z0-9+.-]*:/i.test(file)) return null;\n file = decodeURIComponent(file);\n }\n }\n } catch { return null; }\n file = file.replace(/\\\\/g, \"/\");\n const root = sourceRoot.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n if (file.startsWith(\"/\") || /^[A-Za-z]:/.test(file)) {\n if (!file.startsWith(root + \"/\")) return null;\n file = file.slice(root.length + 1);\n }\n return normalizeRepoPath(file);\n}\n","export type CheckOutcome = \"passed\" | \"failed\" | \"skipped\" | \"unavailable\";\nexport interface EvidenceLocation { file: string; line?: number; column?: number }\nexport interface RawFinding {\n id: string;\n message: string;\n severity: \"error\" | \"warning\" | \"note\";\n state: \"active\" | \"suppressed\" | \"absent\" | \"informational\";\n locations: EvidenceLocation[];\n ruleId?: string;\n truncated?: boolean;\n}\nexport interface ParsedEvidence {\n outcome: CheckOutcome;\n findings: RawFinding[];\n counts: Record<string, number>;\n incomplete: boolean;\n diagnostics: string[];\n reportedCommits?: string[];\n reportedCommands?: string[];\n reportedTools?: string[];\n executed?: boolean;\n}\nexport const MAX_FINDINGS = 200;\nexport function messagePreview(message: string) {\n return { message: message.slice(0, 4000), ...(message.length > 4000 ? { truncated: true } : {}) };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding } from \"./types.js\";\n\nconst count = z.number().int().nonnegative();\nconst schema = z.object({\n success: z.boolean(), numTotalTests: count, numPassedTests: count, numFailedTests: count,\n numPendingTests: count, numTodoTests: count, numFailedTestSuites: count,\n testResults: z.array(z.object({\n name: z.string().min(1), status: z.enum([\"passed\", \"failed\"]), message: z.string().optional(),\n assertionResults: z.array(z.object({\n fullName: z.string(), status: z.enum([\"passed\", \"failed\", \"pending\", \"skipped\", \"todo\", \"disabled\"]),\n failureMessages: z.array(z.string()).nullable().optional(),\n location: z.object({ line: count, column: count }).nullable().optional(),\n })),\n })),\n});\n\n/** Vitest JSON reporter output; summary and assertion counts must agree. */\nexport function parseVitest(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw);\n const findings: RawFinding[] = [], diagnostics: string[] = [];\n let passed = 0, failed = 0, skipped = 0;\n for (const [index, suite] of report.testResults.entries()) {\n const file = evidencePath(suite.name, sourceRoot);\n if (!file) diagnostics.push(`Test path is outside the declared checkout or invalid: ${suite.name}`);\n let suiteFailures = 0;\n for (const [testIndex, test] of suite.assertionResults.entries()) {\n if (test.status === \"passed\") passed++;\n else if (test.status === \"failed\") {\n failed++; suiteFailures++;\n findings.push({ id: `${index}:${testIndex}`, ...messagePreview([test.fullName, ...(test.failureMessages ?? [])].join(\"\\n\")),\n severity: \"error\", state: \"active\", locations: file ? [{ file, ...(test.location ? { line: test.location.line, column: test.location.column } : {}) }] : [] });\n } else skipped++;\n }\n if (suite.status === \"failed\" && !suiteFailures) {\n findings.push({ id: `${index}:suite`, ...messagePreview(suite.message || `Test suite failed: ${suite.name}`), severity: \"error\", state: \"active\", locations: file ? [{ file }] : [] });\n }\n }\n if (passed !== report.numPassedTests || failed !== report.numFailedTests || skipped !== report.numPendingTests + report.numTodoTests || passed + failed + skipped !== report.numTotalTests) {\n throw new Error(\"Vitest summary counts disagree with its assertion results\");\n }\n const hasFailures = failed > 0 || report.numFailedTestSuites > 0 || report.testResults.some(s => s.status === \"failed\");\n if (report.success && hasFailures) throw new Error(\"Vitest success conflicts with failed tests or suites\");\n const outcome = hasFailures || !report.success ? \"failed\" : !report.numTotalTests ? \"unavailable\" : !passed ? \"skipped\" : \"passed\";\n if (!report.numTotalTests) diagnostics.push(\"No tests executed; an empty report is not passing test evidence.\");\n if (skipped) diagnostics.push(`${skipped} tests were skipped, pending, disabled, or todo.`);\n return { outcome, findings, counts: { total: report.numTotalTests, passed, failed, skipped, failedSuites: report.numFailedTestSuites },\n incomplete: skipped > 0 || diagnostics.length > 0, diagnostics };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding, type EvidenceLocation } from \"./types.js\";\n\nconst index = z.number().int().nonnegative();\nconst artifact = z.object({ uri: z.string().optional(), uriBaseId: z.string().optional(), index: index.optional() });\nconst message = z.object({ text: z.string().optional(), markdown: z.string().optional(), id: z.string().optional(), arguments: z.array(z.string()).optional() });\nconst level = z.enum([\"error\", \"warning\", \"note\", \"none\"]);\nconst location = z.object({ physicalLocation: z.object({ artifactLocation: artifact.optional(), region: z.object({ startLine: index.optional(), startColumn: index.optional() }).optional() }).optional() });\nconst schema = z.object({\n version: z.literal(\"2.1.0\"), runs: z.array(z.object({\n tool: z.object({ driver: z.object({ name: z.string().min(1), rules: z.array(z.object({ id: z.string(), defaultConfiguration: z.object({ level: level.optional() }).optional(), messageStrings: z.record(message).optional() })).optional(), globalMessageStrings: z.record(message).optional() }) }),\n invocations: z.array(z.object({ executionSuccessful: z.boolean(), commandLine: z.string().optional(), toolExecutionNotifications: z.array(z.object({ level: level.optional(), message })).optional() })).optional(),\n versionControlProvenance: z.array(z.object({ revisionId: z.string().optional() })).optional(),\n originalUriBaseIds: z.record(artifact).optional(), artifacts: z.array(z.object({ location: artifact.optional() })).optional(),\n results: z.array(z.object({\n ruleId: z.string().optional(), ruleIndex: index.optional(), message, level: level.optional(),\n kind: z.enum([\"fail\", \"pass\", \"open\", \"informational\", \"notApplicable\", \"review\"]).optional(),\n baselineState: z.enum([\"new\", \"unchanged\", \"updated\", \"absent\"]).optional(),\n suppressions: z.array(z.object({ kind: z.enum([\"inSource\", \"external\"]), status: z.enum([\"accepted\", \"underReview\", \"rejected\"]).optional() })).nullable().optional(),\n locations: z.array(location).optional(), relatedLocations: z.array(location).optional(),\n })).optional(),\n })),\n});\n\nexport function parseSarif(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw), findings: RawFinding[] = [], diagnostics: string[] = [];\n let active = 0, suppressed = 0, absent = 0, unresolved = 0;\n let executed = report.runs.length > 0, executionFailed = false;\n const reportedCommits: string[] = [], reportedCommands: string[] = [], reportedTools: string[] = [];\n for (const [runIndex, run] of report.runs.entries()) {\n reportedTools.push(run.tool.driver.name);\n reportedCommits.push(...(run.versionControlProvenance ?? []).flatMap(v => v.revisionId ? [v.revisionId] : []));\n if (!run.invocations?.length) executed = false;\n for (const invocation of run.invocations ?? []) {\n if (invocation.commandLine) reportedCommands.push(invocation.commandLine);\n if (!invocation.executionSuccessful) executionFailed = true;\n for (const notification of invocation.toolExecutionNotifications ?? []) {\n diagnostics.push(notification.message.text ?? notification.message.markdown ?? \"SARIF tool execution notification\");\n if (notification.level === \"error\") executionFailed = true;\n }\n }\n if (!run.results) { diagnostics.push(`Run ${runIndex} omits results; analysis output is unavailable.`); executed = false; }\n const resolve = (ref: z.infer<typeof artifact>, seen = new Set<string>()): string | null => {\n if (!ref.uri && ref.index !== undefined) {\n const key = `artifact:${ref.index}`;\n if (seen.has(key)) return null;\n const entry = run.artifacts?.[ref.index]?.location;\n return entry ? resolve(entry, new Set([...seen, key])) : null;\n }\n if (!ref.uri) return null;\n if (!ref.uriBaseId) return ref.uri;\n if (seen.has(ref.uriBaseId)) return null;\n const base = run.originalUriBaseIds?.[ref.uriBaseId];\n if (!base) return null;\n const prefix = resolve(base, new Set([...seen, ref.uriBaseId]));\n if (!prefix) return null;\n // Base URIs use concatenation, preserving traversal for the path validator.\n return /^[a-z][a-z0-9+.-]*:/i.test(ref.uri) ? ref.uri : prefix + ref.uri;\n };\n for (const [resultIndex, result] of (run.results ?? []).entries()) {\n const kind = result.kind ?? \"fail\";\n const isSuppressed = result.suppressions?.some(s => s.status === \"accepted\");\n if (result.suppressions?.some(s => !s.status || s.status === \"underReview\")) {\n diagnostics.push(`Suppression state unresolved for result ${runIndex}:${resultIndex}.`); unresolved++;\n }\n const state = result.baselineState === \"absent\" ? \"absent\" : isSuppressed ? \"suppressed\" : kind === \"fail\" ? \"active\" : \"informational\";\n if (state === \"active\") active++;\n if (state === \"absent\") absent++;\n if (state === \"suppressed\") suppressed++;\n if ([\"open\", \"review\"].includes(kind) && state === \"informational\") { unresolved++; diagnostics.push(`Result ${runIndex}:${resultIndex} needs further analysis or review.`); }\n if (kind === \"pass\" || kind === \"notApplicable\") continue;\n const rule = result.ruleIndex !== undefined ? run.tool.driver.rules?.[result.ruleIndex] : run.tool.driver.rules?.find(rule => rule.id === result.ruleId);\n const template = result.message.id ? rule?.messageStrings?.[result.message.id] ?? run.tool.driver.globalMessageStrings?.[result.message.id] : undefined;\n const rawMessage = result.message.text ?? result.message.markdown ?? template?.text ?? template?.markdown;\n if (!rawMessage) diagnostics.push(`Message cannot be resolved for result ${runIndex}:${resultIndex}.`);\n const rendered = (rawMessage ?? `Unresolved SARIF message ${result.message.id ?? \"\"}`).replace(/\\{(\\d+)\\}/g, (match, n) => result.message.arguments?.[Number(n)] ?? match);\n const locations: EvidenceLocation[] = [];\n for (const entry of [...(result.locations ?? []), ...(result.relatedLocations ?? [])]) {\n const ref = entry.physicalLocation?.artifactLocation;\n const uri = ref ? resolve(ref) : null;\n const file = uri ? evidencePath(uri, sourceRoot, true) : null;\n if (file) locations.push({ file, line: entry.physicalLocation?.region?.startLine, column: entry.physicalLocation?.region?.startColumn });\n else diagnostics.push(`Unresolved or out-of-checkout location for result ${runIndex}:${resultIndex}.`);\n }\n const severity = result.level ?? rule?.defaultConfiguration?.level ?? (kind === \"fail\" ? \"warning\" : \"none\");\n findings.push({ id: `${runIndex}:${resultIndex}`, ruleId: result.ruleId ?? rule?.id, ...messagePreview(rendered), severity: severity === \"none\" ? \"note\" : severity, state, locations });\n }\n }\n if (!report.runs.length) diagnostics.push(\"SARIF contains no analysis runs.\");\n if (executionFailed) diagnostics.push(\"The SARIF tool reported an unsuccessful analysis invocation.\");\n return { outcome: executionFailed || !report.runs.length || report.runs.some(r => !r.results) ? \"unavailable\" : active ? \"failed\" : \"passed\",\n findings, counts: { active, suppressed, absent, unresolved }, incomplete: diagnostics.length > 0,\n diagnostics, reportedCommits, reportedCommands, reportedTools, executed: executed && !executionFailed };\n}\n","import { z } from \"zod\";\nimport { evidencePath } from \"./paths.js\";\nimport { messagePreview, type ParsedEvidence, type RawFinding } from \"./types.js\";\n\nconst schema = z.object({\n version: z.literal(1),\n commit: z.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/).optional(),\n results: z.array(z.object({\n name: z.string().min(1).max(1000), status: z.enum([\"passed\", \"failed\", \"skipped\"]),\n message: z.string().max(100000).optional(),\n locations: z.array(z.object({ file: z.string().min(1).max(4000),\n line: z.number().int().positive().optional(), column: z.number().int().positive().optional() })).max(100).default([]),\n })).max(100000),\n});\n\n/** Adapter boundary for native validators. Derive outcomes from individual results;\n * a manifest still has to establish command completion and commit attribution. */\nexport function parseCheck(raw: unknown, sourceRoot: string): ParsedEvidence {\n const report = schema.parse(raw);\n const diagnostics: string[] = [], findings: RawFinding[] = [];\n const counts = { total: report.results.length, passed: 0, failed: 0, skipped: 0 };\n for (const [index, result] of report.results.entries()) {\n counts[result.status]++;\n const locations = result.locations.flatMap(location => {\n const file = evidencePath(location.file, sourceRoot);\n if (!file) { diagnostics.push(`Check location is outside the declared checkout or invalid: ${location.file}`); return []; }\n return [{ ...location, file }];\n });\n if (result.status === \"failed\") findings.push({ id: String(index),\n ...messagePreview([result.name, result.message].filter(Boolean).join(\"\\n\")), severity: \"error\", state: \"active\", locations });\n }\n if (!counts.total) diagnostics.push(\"No check results were recorded; an empty report is not passing evidence.\");\n if (counts.skipped) diagnostics.push(`${counts.skipped} checks were skipped; verification is incomplete.`);\n return { outcome: counts.failed ? \"failed\" : !counts.total ? \"unavailable\" : !counts.passed ? \"skipped\" : \"passed\",\n counts, findings, incomplete: diagnostics.length > 0, diagnostics,\n ...(report.commit ? { reportedCommits: [report.commit] } : {}) };\n}\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { normalizeRepoPath, matchingPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getWorkingTree } from \"../drift/drift.js\";\nimport { buildTestMap, type TestPair } from \"../test-map.js\";\nimport { decisionApproval, decisionProvenance, effectiveDecision, type DecisionRecord } from \"../decisions/provenance.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { parseVitest } from \"./evidence/vitest.js\";\nimport { parseSarif } from \"./evidence/sarif.js\";\nimport { parseCheck } from \"./evidence/check.js\";\nimport { MAX_FINDINGS, type CheckOutcome, type RawFinding, type ParsedEvidence } from \"./evidence/types.js\";\n\nconst checkSchema = z.object({\n id: z.string().min(1).max(100), kind: z.enum([\"tests\", \"static-analysis\", \"security\", \"complexity\", \"duplication\", \"documentation\"]),\n tool: z.string().min(1).max(200), command: z.string().min(1).max(2000),\n commit: z.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/).nullable().optional(),\n workingTreeClean: z.boolean().optional(),\n source: z.string().max(2000).optional(), sourceRoot: z.string().min(1).max(4000).optional(),\n status: z.enum([\"completed\", \"skipped\", \"unavailable\"]).default(\"completed\"), reason: z.string().min(1).max(2000).optional(),\n exitCode: z.number().int().nullable().optional(),\n environment: z.object({ toolVersion: z.string().min(1).max(200),\n runtime: z.string().min(1).max(200).optional(), platform: z.string().min(1).max(200).optional(),\n configuration: z.array(z.string().min(1).max(4000)).max(100).optional() }).optional(),\n report: z.object({ format: z.enum([\"vitest-json\", \"sarif\", \"mason-check-json\"]), path: z.string().min(1).max(4000) }).optional(),\n});\ntype CheckInput = z.infer<typeof checkSchema>;\nexport interface LinkedFinding extends RawFinding {\n relatedChangedFiles: Array<{ file: string; relationship: \"direct\" | \"paired-test\"; confidence?: string }>;\n acceptedDecisions: Array<{ id: string; title: string; owner: string | null; freshness: Freshness; reviewRequired: boolean; viaFiles: string[] }>;\n totalAcceptedDecisions: number;\n}\nexport interface EvidenceCheck {\n id: string; kind: CheckInput[\"kind\"]; tool: string; command: string; commit: string | null;\n workingTreeClean: boolean | null;\n source: string | null; manifest: string; report: CheckInput[\"report\"] | null;\n outcome: CheckOutcome; freshness: \"current\" | \"stale\" | \"unknown\";\n findings: LinkedFinding[]; totalFindings: number; counts: Record<string, number>;\n incomplete: boolean; diagnostics: string[]; truncated: boolean;\n reportedCommands?: string[]; reportedTools?: string[];\n environment?: CheckInput[\"environment\"];\n}\nexport interface ReviewEvidence {\n version: 1; scope: \"committed\"; headHash: string;\n status: \"passed\" | \"failed\" | \"incomplete\" | \"unavailable\";\n checks: EvidenceCheck[]; diagnostics: string[];\n summary: { passed: number; failed: number; skipped: number; unavailable: number; stale: number; unknown: number };\n workingTree: Awaited<ReturnType<typeof getWorkingTree>>;\n hint: string;\n}\n\nfunction relativeArtifact(root: string, file: string): string {\n const relative = path.isAbsolute(file) ? path.relative(root, file) : file;\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Evidence artifact must be inside the repository: ${file}`);\n return normalized;\n}\n\nfunction linkFinding(finding: RawFinding, changed: Set<string>, pairs: TestPair[], decisions: DecisionRecord[], freshness: Record<string, Freshness>): LinkedFinding {\n const located = [...new Set(finding.locations.map(l => l.file))];\n const paired = pairs.filter(pair => located.includes(pair.test));\n const relatedChangedFiles: LinkedFinding[\"relatedChangedFiles\"] = located.filter(file => changed.has(file)).map(file => ({ file, relationship: \"direct\" }));\n for (const pair of paired) {\n if (changed.has(pair.source) && !relatedChangedFiles.some(f => f.file === pair.source)) relatedChangedFiles.push({ file: pair.source, relationship: \"paired-test\", confidence: pair.confidence });\n }\n const allFiles = [...new Set([...located, ...paired.map(pair => pair.source)])];\n const acceptedDecisions = decisions.map(effectiveDecision).filter(d => d.status === \"active\" && decisionApproval(d) === \"accepted\")\n .map(d => ({ d, viaFiles: matchingPaths(d.files, allFiles) })).filter(match => match.viaFiles.length)\n .map(({ d, viaFiles }) => {\n const state = freshness[d.id] ?? \"unknown\", provenance = decisionProvenance(d, state);\n return { id: d.id, title: d.title, owner: provenance.owner, freshness: state, reviewRequired: provenance.reviewRequired, viaFiles };\n });\n return { ...finding, relatedChangedFiles, acceptedDecisions: acceptedDecisions.slice(0, 5), totalAcceptedDecisions: acceptedDecisions.length };\n}\n\n/** Read-only imports. Commands, URLs, and result locations are never executed or fetched. */\nexport async function collectReviewEvidence(root: string, manifests: string[], changedFiles: string[], decisions: DecisionRecord[], decisionFreshness: Record<string, Freshness> = {}, reviewedHead?: string): Promise<ReviewEvidence> {\n const [headHash, workingTree] = await Promise.all([reviewedHead ?? getCurrentGitHash(root), getWorkingTree(root)]);\n const output: ReviewEvidence = {\n version: 1, scope: \"committed\", headHash, status: \"unavailable\", checks: [], diagnostics: [], workingTree,\n summary: { passed: 0, failed: 0, skipped: 0, unavailable: 0, stale: 0, unknown: 0 },\n hint: \"Evidence describes the recorded check runs for a commit, not uncommitted edits or complete test coverage. Commands and CI provenance are imported assertions, not authenticated execution. File and test-pair associations identify relevant decisions; they do not prove a decision was violated. Missing checks must be declared in the manifest to be reported.\",\n };\n const seen = new Set<string>(), changed = new Set(changedFiles);\n let pairs: TestPair[] | undefined;\n if (manifests.length > 10) output.diagnostics.push(\"Only the first 10 evidence manifests were imported.\");\n for (const supplied of manifests.slice(0, 10)) {\n let manifest: string, raw: { version: 1; checks: unknown[] };\n try {\n manifest = relativeArtifact(root, supplied);\n raw = z.object({ version: z.literal(1), checks: z.array(z.unknown()) }).parse(await readStoreJson(root, manifest));\n } catch (error) { output.diagnostics.push(`${supplied}: ${String(error)}`); continue; }\n if (!raw.checks.length) output.diagnostics.push(`${manifest}: no checks declared.`);\n for (const [index, item] of raw.checks.entries()) {\n if (output.checks.length >= 50) { output.diagnostics.push(\"Only the first 50 checks were imported.\"); break; }\n const input = checkSchema.safeParse(item);\n if (!input.success) { output.diagnostics.push(`${manifest} check ${index}: ${input.error.message}`); continue; }\n const check = input.data;\n if (seen.has(check.id)) { output.diagnostics.push(`Duplicate check id ${check.id}; give different runs distinct ids.`); continue; }\n seen.add(check.id);\n const result: EvidenceCheck = {\n id: check.id, kind: check.kind, tool: check.tool, command: check.command,\n commit: check.commit?.toLowerCase() ?? null, workingTreeClean: check.workingTreeClean ?? null, source: check.source ?? null, manifest, report: check.report ?? null,\n outcome: \"unavailable\", freshness: \"unknown\", findings: [], totalFindings: 0, counts: {}, incomplete: false, diagnostics: [], truncated: false,\n ...(check.environment ? { environment: check.environment } : {}),\n };\n output.checks.push(result);\n if (check.workingTreeClean !== true) result.diagnostics.push(\"The check's working tree was dirty or not recorded; its results cannot be attributed to the claimed commit alone.\");\n else if (result.commit && headHash !== \"unknown\") result.freshness = result.commit === headHash.toLowerCase() ? \"current\" : \"stale\";\n else result.diagnostics.push(\"The tested commit or reviewed HEAD is unknown.\");\n if (check.status !== \"completed\") {\n result.outcome = check.status;\n result.diagnostics.push(check.reason ?? \"No reason was recorded for this skipped or unavailable check.\");\n continue;\n }\n try {\n if (!check.report) throw new Error(\"Completed check has no report artifact.\");\n if (check.report.format !== \"mason-check-json\" && (check.kind === \"tests\") !== (check.report.format === \"vitest-json\")) throw new Error(\"Test checks require vitest-json or mason-check-json; analysis checks require sarif or mason-check-json.\");\n const file = relativeArtifact(root, check.report.path);\n const report = await readStoreJson(root, file);\n if (report === null) throw new Error(`Report artifact is missing: ${file}`);\n const sourceRoot = check.sourceRoot ?? root;\n if (!path.posix.isAbsolute(sourceRoot) && !/^[A-Za-z]:[\\\\/]/.test(sourceRoot)) throw new Error(\"sourceRoot must identify the absolute checkout root on the check runner.\");\n const parsed: ParsedEvidence = check.report.format === \"vitest-json\" ? parseVitest(report, sourceRoot)\n : check.report.format === \"mason-check-json\" ? parseCheck(report, sourceRoot) : parseSarif(report, sourceRoot);\n result.outcome = parsed.outcome; result.counts = parsed.counts; result.incomplete = parsed.incomplete;\n result.diagnostics.push(...parsed.diagnostics);\n result.reportedCommands = parsed.reportedCommands; result.reportedTools = parsed.reportedTools;\n if (parsed.reportedCommits?.some(commit => !result.commit || commit.toLowerCase() !== result.commit)) {\n result.freshness = \"unknown\"; result.incomplete = true;\n result.diagnostics.push(\"Report revision metadata conflicts with, or cannot be tied to, the manifest's tested commit.\");\n }\n if (check.exitCode == null && !parsed.executed) {\n result.incomplete = true; result.diagnostics.push(\"Neither an exit code nor successful analysis invocation was recorded; completion cannot be confirmed.\");\n }\n if (check.exitCode != null && check.exitCode !== 0 && result.outcome === \"passed\") {\n result.outcome = \"failed\"; result.diagnostics.push(`Check command exited ${check.exitCode} despite a report with no active failures.`);\n }\n if (check.kind === \"tests\" && pairs === undefined) {\n try { pairs = (await buildTestMap(root)).paired; }\n catch (error) { pairs = []; output.diagnostics.push(`Test pairing unavailable: ${String(error)}`); }\n }\n result.totalFindings = parsed.findings.length;\n // Prioritize findings on changed files while retaining overall outcomes and counts.\n const testPairs = check.kind === \"tests\" ? pairs ?? [] : [];\n const relevant = new Set([...changed, ...testPairs.filter(p => changed.has(p.source)).map(p => p.test)]);\n const touchesChange = (f: RawFinding) => f.locations.some(l => relevant.has(l.file));\n parsed.findings.sort((a, b) => Number(b.state === \"active\") - Number(a.state === \"active\") || Number(touchesChange(b)) - Number(touchesChange(a)));\n result.findings = parsed.findings.slice(0, MAX_FINDINGS).map(f => linkFinding(f, changed, testPairs, decisions, decisionFreshness));\n result.truncated = parsed.findings.length > MAX_FINDINGS || result.findings.some(f => f.truncated || f.totalAcceptedDecisions > f.acceptedDecisions.length);\n } catch (error) {\n result.outcome = \"unavailable\"; result.incomplete = true; result.diagnostics.push(String(error));\n }\n }\n }\n if (!output.checks.length) output.diagnostics.push(\"No readable checks were imported.\");\n for (const check of output.checks) {\n output.summary[check.outcome]++;\n if (check.freshness !== \"current\") output.summary[check.freshness]++;\n }\n if (output.checks.some(c => c.outcome === \"failed\" && c.freshness === \"current\")) output.status = \"failed\";\n else if (!output.checks.length || output.checks.every(c => c.outcome === \"unavailable\")) output.status = \"unavailable\";\n else if (output.diagnostics.length || output.checks.some(c => c.outcome !== \"passed\" || c.freshness !== \"current\" || c.incomplete)) output.status = \"incomplete\";\n else output.status = \"passed\";\n return output;\n}\n\nexport function summarizeEvidence(evidence: ReviewEvidence) {\n const previews = (values: string[], limit: number) => values.slice(0, limit).map(value => value.slice(0, 2000));\n const checks = evidence.checks.slice(0, 10).map(check => {\n const findings = check.findings.slice(0, 5).map(finding => ({ ...finding,\n ruleId: finding.ruleId?.slice(0, 200),\n locations: finding.locations.slice(0, 5), totalLocations: finding.locations.length,\n relatedChangedFiles: finding.relatedChangedFiles.slice(0, 5), totalRelatedChangedFiles: finding.relatedChangedFiles.length,\n acceptedDecisions: finding.acceptedDecisions.map(decision => ({ ...decision, viaFiles: decision.viaFiles.slice(0, 5) })),\n truncated: finding.truncated || finding.locations.length > 5 || finding.relatedChangedFiles.length > 5 ||\n (finding.ruleId?.length ?? 0) > 200 || finding.acceptedDecisions.some(d => d.viaFiles.length > 5),\n }));\n return { ...check, findings, reportedCommands: check.reportedCommands ? previews(check.reportedCommands, 5) : undefined,\n reportedTools: check.reportedTools ? previews(check.reportedTools, 5) : undefined,\n diagnostics: previews(check.diagnostics, 10),\n truncated: check.truncated || check.findings.length > 5 || findings.some(f => f.truncated) || check.diagnostics.length > 10 ||\n check.diagnostics.some(d => d.length > 2000) || [check.reportedCommands ?? [], check.reportedTools ?? []].some(values => values.length > 5 || values.some(v => v.length > 2000)),\n };\n });\n return { ...evidence, checks, diagnostics: previews(evidence.diagnostics, 20),\n truncated: evidence.checks.length > 10 || evidence.diagnostics.length > 20 || evidence.diagnostics.some(d => d.length > 2000) || checks.some(c => c.truncated),\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { getChangesWithStatus, touchedPaths } from \"../drift/drift.js\";\nimport { decisionProvenance, decisionKnowledge, effectiveDecision } from \"../decisions/provenance.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionRecord } from \"../decisions/decisions.js\";\nimport { findMissingPartners } from \"./cochange.js\";\nimport type { CochangeFinding } from \"./cochange.js\";\nimport { collectReviewEvidence, type ReviewEvidence } from \"./evidence.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\n\nconst exec = promisify(execFile);\n\n/** Diffs larger than this are refactors; partner analysis would be noise. */\nconst MAX_ANALYZED_FILES = 50;\n\nexport interface TouchedDecision extends Partial<ReturnType<typeof decisionProvenance>> {\n id: string;\n title: string;\n body: string;\n category: string;\n anchors: string[];\n freshness?: Freshness;\n touchedFiles: string[];\n pendingProposal?: NonNullable<ReturnType<typeof decisionKnowledge>[\"pendingProposal\"]> & { touchedFiles: string[] };\n}\n\nexport interface ReviewReport {\n /** Additive-only schema. */\n version: 1;\n diagnostics?: StoreDiagnostic[];\n root: string;\n base: string;\n mergeBase: string;\n changedFiles: string[];\n /** Historical partners this diff leaves untouched — drive exit 1. */\n missingPartners: CochangeFinding[];\n /** Decisions whose anchors the diff touches — informational only. */\n touchedDecisions: TouchedDecision[];\n historyAvailable: boolean;\n truncated: boolean;\n /** Optional imported CI results. Does not change the legacy review exit codes. */\n evidence?: ReviewEvidence;\n}\n\nasync function resolveMergeBase(\n resolvedRoot: string,\n base: string,\n head: string\n): Promise<string | null> {\n try {\n const { stdout } = await exec(\"git\", [\"merge-base\", base, head], {\n cwd: resolvedRoot,\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/** First base ref that resolves: origin/HEAD, origin/main, origin/master, main. */\nexport async function defaultBase(resolvedRoot: string): Promise<string | null> {\n for (const ref of [\"origin/HEAD\", \"origin/main\", \"origin/master\", \"main\"]) {\n try {\n await exec(\"git\", [\"rev-parse\", \"--verify\", \"--quiet\", ref], {\n cwd: resolvedRoot,\n });\n return ref;\n } catch {\n // Try the next candidate.\n }\n }\n return null;\n}\n\nfunction anchorsTouched(\n record: DecisionRecord,\n changedFiles: string[]\n): string[] {\n return matchingPaths(record.files, changedFiles);\n}\n\n/**\n * Review a diff against what git history and the decision store know:\n * co-change partners the diff forgot, and recorded constraints it touches.\n * Deterministic — no LLM, no network. Returns null when the base ref or\n * merge base cannot be resolved.\n */\nexport async function computeReview(\n rootDir: string,\n base: string,\n options: { evidence?: string[] } = {}\n): Promise<ReviewReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const head = await getCurrentGitHash(resolvedRoot);\n if (head === \"unknown\") return null;\n const mergeBase = await resolveMergeBase(resolvedRoot, base, head);\n if (!mergeBase) return null;\n\n const changes = await getChangesWithStatus(resolvedRoot, mergeBase, head);\n if (changes === null) return null;\n\n const changedFiles = touchedPaths(changes);\n\n const report: ReviewReport = {\n version: 1,\n root: resolvedRoot,\n base,\n mergeBase,\n changedFiles,\n missingPartners: [],\n touchedDecisions: [],\n historyAvailable: true,\n truncated: false,\n };\n const store = await loadDecisionStore(resolvedRoot);\n report.diagnostics = store.diagnostics;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, store.records);\n if (options.evidence !== undefined) {\n report.evidence = await collectReviewEvidence(resolvedRoot, options.evidence, changedFiles, store.records, decisionDrift.freshness, head);\n if (store.diagnostics.length) {\n report.evidence.diagnostics.push(\"Invalid decision records make knowledge associations incomplete; consult review diagnostics.\");\n if (report.evidence.status === \"passed\") report.evidence.status = \"incomplete\";\n }\n }\n const finalize = async () => {\n if (report.evidence && await getCurrentGitHash(resolvedRoot) !== head) {\n report.evidence.diagnostics.push(\"HEAD changed during the review; rerun to obtain consistent change and knowledge associations.\");\n for (const check of report.evidence.checks) check.freshness = \"unknown\";\n report.evidence.summary.stale = 0;\n report.evidence.summary.unknown = report.evidence.checks.length;\n if (report.evidence.status !== \"unavailable\") report.evidence.status = \"incomplete\";\n }\n return report;\n };\n if (changedFiles.length === 0) return finalize();\n\n let analyzed = changedFiles;\n if (changedFiles.length > MAX_ANALYZED_FILES) {\n analyzed = changedFiles.slice(0, MAX_ANALYZED_FILES);\n report.truncated = true;\n }\n\n const partners = await findMissingPartners(\n resolvedRoot,\n analyzed,\n async (relPath) => {\n try {\n await fs.access(path.join(resolvedRoot, relPath));\n return true;\n } catch {\n return false;\n }\n },\n changedFiles\n );\n if (partners === null) {\n report.historyAvailable = false;\n } else {\n report.missingPartners = partners;\n }\n\n const decisions = store.records;\n for (const record of decisions) {\n if (record.status !== \"active\") continue;\n const effective = effectiveDecision(record);\n const touched = anchorsTouched(effective, changedFiles);\n const proposalTouched = effective !== record ? anchorsTouched(record, changedFiles) : [];\n if (touched.length > 0 || proposalTouched.length > 0) {\n const { pendingProposal, ...knowledge } = decisionKnowledge(record, decisionDrift.freshness?.[record.id] ?? \"unknown\", decisionDrift.pendingProposals?.[record.id]?.freshness ?? \"unknown\");\n report.touchedDecisions.push({\n ...knowledge,\n ...(pendingProposal ? { pendingProposal: { ...pendingProposal, touchedFiles: proposalTouched } } : {}),\n id: record.id,\n anchors: effective.files,\n freshness: decisionDrift.freshness?.[record.id] ?? \"unknown\",\n touchedFiles: touched,\n });\n }\n }\n\n return finalize();\n}\n","import { computeAudit } from \"../audit/audit.js\";\nimport { computeReview, defaultBase } from \"../review/review.js\";\nimport { getWorkingTree } from \"../drift/drift.js\";\nimport { inspectSnapshot } from \"../snapshot/snapshot.js\";\nimport { decisionApproval, effectiveDecision } from \"../decisions/provenance.js\";\nimport { summarizeEvidence } from \"../review/evidence.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\n\nconst MAX_FINDINGS = 20;\nconst reason = (error: unknown) => error instanceof Error ? error.message : String(error);\n\nasync function auditSummary(root: string) {\n try {\n const report = await computeAudit(root);\n if (!report) return { status: \"no-context-files\", reason: \"No README.md or agent instruction files found to audit.\" };\n if (!report.gitAvailable) return { status: \"unavailable\", reason: \"Audit needs readable Git history to verify documentation claims.\", docs: report.docs };\n return {\n ...report, status: \"complete\",\n issues: report.issues.slice(0, MAX_FINDINGS),\n advisories: report.advisories.slice(0, MAX_FINDINGS),\n suppressedAdvisories: (report.suppressedAdvisories ?? []).slice(0, MAX_FINDINGS),\n counts: { issues: report.issues.length, advisories: report.advisories.length,\n suppressedAdvisories: report.suppressedAdvisories?.length ?? 0 },\n truncated: report.issues.length > MAX_FINDINGS || report.advisories.length > MAX_FINDINGS ||\n (report.suppressedAdvisories?.length ?? 0) > MAX_FINDINGS,\n };\n } catch (error) { return { status: \"unavailable\", reason: reason(error) }; }\n}\n\nasync function reviewSummary(root: string, requestedBase?: string, evidence?: string[]) {\n const workingTree = await getWorkingTree(root);\n const scope = \"committed\" as const;\n try {\n const base = requestedBase ?? await defaultBase(root);\n if (!base) return { status: \"unavailable\", scope, workingTree, reason: \"No default review base resolves. Pass base to mason_init, or run mason-review --base <ref>.\" };\n const report = await computeReview(root, base, { evidence });\n if (!report) return { status: \"unavailable\", scope, base, workingTree, reason: \"The review base, merge base, or committed diff could not be read.\" };\n return {\n ...report, scope, workingTree,\n ...(report.evidence ? { evidence: summarizeEvidence(report.evidence) } : {}),\n status: !report.historyAvailable ? \"unavailable\" : report.changedFiles.length ? \"complete\" : \"no-changes\",\n ...(!report.historyAvailable ? { reason: \"Co-change history could not be read; review findings are incomplete.\" } : {}),\n changedFiles: report.changedFiles.slice(0, MAX_FINDINGS),\n missingPartners: report.missingPartners.slice(0, MAX_FINDINGS),\n touchedDecisions: report.touchedDecisions.slice(0, MAX_FINDINGS),\n counts: { changedFiles: report.changedFiles.length, missingPartners: report.missingPartners.length, touchedDecisions: report.touchedDecisions.length },\n truncated: report.truncated || [report.changedFiles, report.missingPartners, report.touchedDecisions].some(list => list.length > MAX_FINDINGS),\n hint: \"Reviews cover merge-base..HEAD. Uncommitted paths are reported separately in workingTree; they have not been reviewed.\",\n };\n } catch (error) { return { status: \"unavailable\", scope, workingTree, reason: reason(error) }; }\n}\n\n/** Useful first-run results, with no writes, model calls, or map requirement. */\nexport async function inspectOnboarding(root: string, base?: string, evidence?: string[]) {\n const [audit, review, map, decisions] = await Promise.all([\n auditSummary(root), reviewSummary(root, base, evidence), inspectSnapshot(root), loadDecisionStore(root),\n ]);\n return {\n audit, review, map: { status: map.status },\n decisions: {\n active: decisions.records.filter(record => record.status === \"active\").length,\n ...Object.fromEntries([\"accepted\", \"proposed\", \"unreviewed\"].map(approval => [approval, decisions.records.filter(record => record.status === \"active\" && decisionApproval(effectiveDecision(record)) === approval).length])),\n pendingProposals: decisions.records.filter(record => effectiveDecision(record) !== record).length,\n },\n diagnostics: [...map.diagnostics, ...decisions.diagnostics],\n };\n}\n","import path from \"node:path\";\n\nexport interface ReferenceEntry {\n file: string;\n matches: string[];\n /** Literal relative JS/TS paths or named JVM imports tied to declared symbols. */\n kind: \"import\" | \"mention\";\n evidence: \"resolved-import\" | \"explicit-path\" | \"name-candidate\";\n}\n\nconst jsExtensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".cts\", \".mjs\", \".cjs\"];\nconst genericNames = new Set([\"index\", \"main\", \"app\", \"init\", \"config\", \"settings\", \"types\", \"utils\", \"test\", \"tests\"]);\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst word = (s: string) => new RegExp(`(?<![\\\\w$])${escape(s)}(?![\\\\w$])`);\n\n/** Treat templates (including nested interpolation strings) as opaque syntax. */\nfunction templateEnd(content: string, start: number): number {\n let i = start + 1, interpolation = 0;\n while (i < content.length) {\n const c = content[i];\n if (c === \"\\\\\") { i += 2; continue; }\n if (!interpolation) {\n if (c === \"`\") return i + 1;\n if (c === \"$\" && content[i + 1] === \"{\") { interpolation = 1; i += 2; continue; }\n } else {\n if (c === \"`\") { i = templateEnd(content, i); continue; }\n if (c === '\"' || c === \"'\") {\n const quote = c;\n for (i++; i < content.length; i++) { if (content[i] === \"\\\\\") i++; else if (content[i] === quote) { i++; break; } }\n continue;\n }\n if (content.startsWith(\"//\", i)) { const end = content.indexOf(\"\\n\", i + 2); i = end < 0 ? content.length : end; continue; }\n if (content.startsWith(\"/*\", i)) { const end = content.indexOf(\"*/\", i + 2); i = end < 0 ? content.length : end + 2; continue; }\n if (c === \"{\") interpolation++;\n if (c === \"}\") interpolation--;\n }\n i++;\n }\n return content.length;\n}\n\n/** Skip comments and string bodies before inspecting JS/TS import syntax. */\nfunction tokens(content: string): { value: string; string?: boolean }[] {\n const result: { value: string; string?: boolean }[] = [];\n const re = /\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)|\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|`(?:\\\\.|[^`\\\\])*`|[\\w$]+|[^\\s]/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(content))) {\n const value = match[0];\n if (value.startsWith(\"//\") || value.startsWith(\"/*\")) continue;\n if (/^[\"'`]/.test(value)) {\n if (value[0] === \"`\") {\n re.lastIndex = templateEnd(content, match.index);\n result.push({ value: \"<opaque>\" });\n continue;\n }\n // Escaped or interpolated module strings require runtime/language resolution.\n result.push({ value: value.slice(1, -1), string: !value.includes(\"\\\\\") && value[0] !== \"`\" });\n // Keep opaque strings opaque even if their content equals import/from.\n if (!result.at(-1)!.string) result[result.length - 1] = { value: \"<opaque>\" };\n } else result.push({ value });\n }\n return result;\n}\n\nfunction imports(content: string): string[] {\n const ts = tokens(content), found: string[] = [];\n for (let i = 0; i < ts.length; i++) {\n const t = ts[i];\n if (t.string || ts[i - 1]?.value === \".\") continue;\n if ([\"require\", \"import\"].includes(t.value) && ts[i + 1]?.value === \"(\" && ts[i + 2]?.string && ts[i + 3]?.value === \")\") {\n found.push(ts[i + 2].value);\n }\n if (![\"import\", \"export\"].includes(t.value) || ts[i + 1]?.value === \"(\") continue;\n if (t.value === \"import\" && ts[i + 1]?.string) { found.push(ts[i + 1].value); continue; }\n for (let j = i + 1; j < Math.min(ts.length, i + 150); j++) {\n if ([\";\", \"=\", \"import\", \"export\"].includes(ts[j].value) && !ts[j].string) break;\n if (ts[j].value === \"from\" && !ts[j].string && ts[j + 1]?.string) { found.push(ts[j + 1].value); break; }\n }\n }\n return found;\n}\n\nfunction qualifiedName(ts: ReturnType<typeof tokens>, start: number): string {\n let name = \"\";\n for (let i = start; i < ts.length; i++) {\n if (ts[i].string || !/^[A-Za-z_$][\\w$]*$/.test(ts[i].value)) break;\n name += ts[i].value;\n if (ts[i + 1]?.value !== \".\" || !/^[A-Za-z_$][\\w$]*$/.test(ts[i + 2]?.value ?? \"\")) break;\n name += \".\"; i++;\n }\n return name;\n}\n\n/** Match explicit package/symbol identity; package wildcards stay unresolved. */\nfunction declaredSymbols(content: string): string[] {\n const ts = tokens(content);\n const packageAt = ts.findIndex(t => !t.string && t.value === \"package\");\n if (packageAt < 0) return [];\n const pkg = qualifiedName(ts, packageAt + 1), names: string[] = [];\n let depth = 0;\n for (let i = 0; i < ts.length; i++) {\n if (ts[i].string) continue;\n if (ts[i].value === \"{\") depth++;\n if (ts[i].value === \"}\") depth--;\n if (depth === 0 && [\"class\", \"interface\", \"object\", \"enum\", \"typealias\", \"fun\"].includes(ts[i].value) &&\n /^[A-Za-z_$][\\w$]*$/.test(ts[i + 1]?.value ?? \"\") && ts[i + 1].value !== \"class\") names.push(pkg + \".\" + ts[i + 1].value);\n }\n return names;\n}\n\nfunction jvmImports(content: string): string[] {\n const ts = tokens(content), result: string[] = [];\n for (let i = 0; i < ts.length; i++) if (!ts[i].string && ts[i].value === \"import\") {\n const name = qualifiedName(ts, i + (ts[i + 1]?.value === \"static\" ? 2 : 1));\n if (name) result.push(name);\n }\n return result;\n}\n\nfunction resolveImport(file: string, specifier: string, available: Set<string>): string | null {\n if (!specifier.startsWith(\"./\") && !specifier.startsWith(\"../\")) return null;\n const relative = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier));\n if (relative.startsWith(\"../\")) return null;\n if (available.has(relative)) return relative;\n const ext = path.posix.extname(relative);\n const replacements: Record<string, string[]> = { \".js\": [\".ts\", \".tsx\"], \".mjs\": [\".mts\"], \".cjs\": [\".cts\"] };\n const candidates = ext ? (replacements[ext] ?? []).map(e => relative.slice(0, -ext.length) + e) :\n jsExtensions.flatMap(e => [relative + e, relative + \"/index\" + e]);\n const found = candidates.filter(f => available.has(f));\n // Resolution depends on compiler configuration when multiple candidates exist.\n return found.length === 1 ? found[0] : null;\n}\n\n/** Explicit paths are textual evidence, not proof of a dependency. */\nfunction mentionsPath(content: string, target: string): boolean {\n return new RegExp(`(?<![\\\\w./\\\\\\\\-])(?:\\\\./)?${escape(target)}(?![\\\\w./\\\\\\\\-])`).test(content);\n}\n\nexport function createReferenceMatcher(targets: string[], available: Set<string>, targetContents = new Map<string, string>()) {\n const counts = new Map<string, number>();\n for (const file of available) {\n const name = path.posix.basename(file, path.posix.extname(file));\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n const jvmTargets = new Map([...targetContents].filter(([file]) => /\\.(?:kt|kts|java)$/.test(file)).map(([file, content]) => [file, declaredSymbols(content)]));\n return (source: { path: string; content: string }): ReferenceEntry[] => {\n if (targets.includes(source.path)) return [];\n const resolved = new Set(jsExtensions.includes(path.posix.extname(source.path)) ?\n imports(source.content).map(s => resolveImport(source.path, s, available)).filter(Boolean) : []);\n if (/\\.(?:kt|kts|java)$/.test(source.path)) {\n const imported = jvmImports(source.content);\n for (const [target, symbols] of jvmTargets) if (symbols.some(symbol => imported.some(name => name === symbol || name.startsWith(symbol + \".\")))) resolved.add(target);\n }\n // Keep each evidence class separate: one resolved import must not promote\n // another target's ambiguous name match in the same source file.\n const groups = new Map<ReferenceEntry[\"evidence\"], string[]>();\n const add = (evidence: ReferenceEntry[\"evidence\"], match: string) => groups.set(evidence, [...(groups.get(evidence) ?? []), match]);\n for (const target of targets) {\n if (resolved.has(target)) { add(\"resolved-import\", target); continue; }\n if (mentionsPath(source.content, target)) {\n add(\"explicit-path\", target);\n continue;\n }\n const ext = path.posix.extname(target), name = path.posix.basename(target, ext);\n // A config/doc name, generic symbol, or duplicate basename has too little identity.\n if (!/\\.(?:[cm]?[jt]sx?|py|kt|java|go|rs|swift|rb|cs|cpp|c|h|hpp|dart|php)$/.test(ext) ||\n name.startsWith(\".\") || name.length < 3 || genericNames.has(name.toLowerCase()) || counts.get(name) !== 1) continue;\n if (word(name).test(source.content)) {\n add(\"name-candidate\", name);\n }\n }\n return [...groups].map(([evidence, matches]) => ({ file: source.path, matches, kind: evidence === \"resolved-import\" ? \"import\" : \"mention\", evidence }));\n };\n}\n\nexport function sortReferences(result: ReferenceEntry[]): ReferenceEntry[] {\n const rank = { \"resolved-import\": 0, \"explicit-path\": 1, \"name-candidate\": 2 };\n return result.sort((a, b) => rank[a.evidence] - rank[b.evidence] || b.matches.length - a.matches.length || a.file.localeCompare(b.file));\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_GLOB } from \"../utils/files.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { createReferenceMatcher, sortReferences, type ReferenceEntry } from \"./references.js\";\nexport type { ReferenceEntry } from \"./references.js\";\n\nconst exec = promisify(execFile);\n\nexport interface CochangeEntry {\n file: string;\n cochangeRate: number;\n sharedCommits: number;\n}\n\nexport interface TestEntry {\n file: string;\n confidence: \"exact\" | \"best-guess\";\n}\n\nexport interface ImpactResult {\n targetFiles: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n tests: TestEntry[];\n}\n\nexport async function analyzeImpact(\n rootDir: string,\n targetFiles: string[]\n): Promise<ImpactResult> {\n const resolvedRoot = path.resolve(rootDir);\n\n // Resolve target files to full relative paths if only basename given\n const resolvedTargets = await resolveTargetFiles(resolvedRoot, targetFiles);\n\n const [cochange, references, tests] = await Promise.all([\n getCochangeFiles(resolvedRoot, resolvedTargets),\n getReferences(resolvedRoot, resolvedTargets),\n getRelatedTests(resolvedRoot, resolvedTargets),\n ]);\n\n return {\n targetFiles: resolvedTargets,\n cochange,\n references,\n tests,\n };\n}\n\nasync function resolveTargetFiles(\n rootDir: string,\n targets: string[]\n): Promise<string[]> {\n const resolved: string[] = [];\n const access = await createFileAccess(rootDir);\n\n for (const target of targets) {\n // If it contains a path separator, use as-is\n if (target.includes(\"/\")) {\n const normalized = normalizeRepoPath(target);\n if (normalized) resolved.push(normalized);\n continue;\n }\n\n // Otherwise, search for the filename\n const matches = await access.list(`**/${target}`);\n\n if (matches.length > 0) {\n resolved.push(matches[0]);\n } else {\n // Try without extension\n const noExt = target.replace(/\\.[^.]+$/, \"\");\n const extMatches = await access.list(`**/${noExt}.*`);\n if (extMatches.length > 0) {\n resolved.push(extMatches[0]);\n } else {\n resolved.push(target); // Keep as-is, might still work for grep\n }\n }\n }\n\n return resolved;\n}\n\nasync function getCochangeFiles(\n rootDir: string,\n targetFiles: string[]\n): Promise<CochangeEntry[]> {\n const cochangeCounts = new Map<string, number>();\n let totalTargetCommits = 0;\n\n for (const targetFile of targetFiles) {\n try {\n // Get commits that touched this file (cap at 500)\n const { stdout: commitLog } = await exec(\n \"git\",\n [\"log\", \"--format=%H\", \"-n\", \"500\", \"--\", targetFile],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const commits = commitLog.trim().split(\"\\n\").filter(Boolean);\n totalTargetCommits += commits.length;\n\n if (commits.length === 0) continue;\n\n // For each commit, get the other files that changed\n for (const commit of commits) {\n try {\n const { stdout: filesInCommit } = await exec(\n \"git\",\n [\"diff-tree\", \"--no-commit-id\", \"--name-only\", \"-r\", commit],\n { cwd: rootDir }\n );\n\n const files = filesInCommit.trim().split(\"\\n\").filter(Boolean);\n for (const file of files) {\n if (targetFiles.includes(file)) continue; // Skip the target itself\n cochangeCounts.set(file, (cochangeCounts.get(file) ?? 0) + 1);\n }\n } catch {\n // Skip this commit\n }\n }\n } catch {\n // No git or file not tracked\n }\n }\n\n if (totalTargetCommits === 0) return [];\n\n // Filter to files that co-change >30% of the time, sort by rate\n return [...cochangeCounts.entries()]\n .map(([file, count]) => ({\n file,\n cochangeRate: Math.round((count / totalTargetCommits) * 100) / 100,\n sharedCommits: count,\n }))\n .filter((e) => e.cochangeRate >= 0.3 || e.sharedCommits >= 3)\n .sort((a, b) => b.cochangeRate - a.cochangeRate)\n .slice(0, 20);\n}\n\nasync function getReferences(\n rootDir: string,\n targetFiles: string[]\n): Promise<ReferenceEntry[]> {\n const access = await createFileAccess(rootDir);\n const allSourceFiles = await access.list(SOURCE_GLOB);\n const available = new Set(allSourceFiles);\n const targetContents = new Map<string, string>();\n for (const target of targetFiles) {\n const source = await access.read(target);\n if (source) { available.add(target); targetContents.set(target, source.content); }\n }\n const match = createReferenceMatcher(targetFiles, available, targetContents);\n const references: ReferenceEntry[] = [];\n for (let i = 0; i < allSourceFiles.length; i += 50) {\n const batch = await Promise.all(allSourceFiles.slice(i, i + 50).map(file => access.read(file)));\n for (const source of batch) if (source) references.push(...match(source));\n }\n return sortReferences(references);\n}\n\nasync function getRelatedTests(\n rootDir: string,\n targetFiles: string[]\n): Promise<TestEntry[]> {\n const testPatterns = [\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*Test.kt\",\n \"**/*Test.java\",\n \"**/*Tests.kt\",\n \"**/*Tests.java\",\n \"**/test_*.py\",\n \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\",\n \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n\n const testFiles = await (await createFileAccess(rootDir)).list(testPatterns);\n const results: TestEntry[] = [];\n\n for (const target of targetFiles) {\n const targetBaseName = path\n .basename(target)\n .replace(/\\.[^.]+$/, \"\");\n\n for (const testFile of testFiles) {\n const testBaseName = path\n .basename(testFile)\n .replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (sourceName === targetBaseName) {\n results.push({\n file: testFile,\n confidence: \"exact\",\n });\n }\n }\n }\n\n return results;\n}\n","import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { inspectSnapshot, normalizeFeatureType } from \"../snapshot/snapshot.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport type { FeatureType, Snapshot } from \"../snapshot/snapshot.js\";\nimport { createSnapshotTrustReader, readSnapshotTrustIndex } from \"../snapshot/trust.js\";\nimport { computeDrift, type DriftReport } from \"../drift/drift.js\";\nimport { analyzeImpact } from \"../impact/impact.js\";\nimport type { CochangeEntry, ReferenceEntry } from \"../impact/impact.js\";\nimport { scoreEntry, tokenSet } from \"./lexical.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { decisionKnowledge, effectiveDecision, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport { anchorMatches, sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { trustHint, type TrustState } from \"./trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionDriftReport } from \"../decisions/drift.js\";\nimport type { DecisionCategory, DecisionRecord } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst MAX_FEATURES = 5;\nconst MAX_FLOWS = 3;\nconst MAX_IMPACT_TARGETS = 3;\nconst MAX_DECISIONS = 5;\nconst DECISION_FEATURE_OVERLAP_BOOST = 2;\n\nexport interface MatchedFeature {\n description: string;\n files: string[];\n tests?: string[];\n type: FeatureType;\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedFlow {\n description: string;\n chain: string[];\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedDecision extends ReturnType<typeof decisionKnowledge> {\n title: string;\n /** Full body — the payload the decisions store exists for. */\n body: string;\n category: DecisionCategory;\n files: string[];\n score: number;\n /** Anchor files changed since this record was last verified. */\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface ContextBundle {\n exists: true;\n map: { status: \"available\" };\n diagnostics?: StoreDiagnostic[];\n task: string;\n features: Record<string, MatchedFeature>;\n flows: Record<string, MatchedFlow>;\n /** Relevant knowledge; approval distinguishes constraints from proposals. */\n decisions: Record<string, MatchedDecision>;\n /** All tests paired with the matched files, deduped. */\n relatedTests: string[];\n impact: {\n targets: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n /** Weak name-only candidates omitted from compact context; available via get_impact. */\n referenceCandidatesOmitted?: number;\n } | null;\n freshness: {\n stale: boolean;\n recommendation: string;\n /** Matched entries whose files changed since they were last verified. */\n staleMatches: string[];\n };\n hint: string;\n}\n\nexport interface NoMatchBundle {\n exists: true;\n map: { status: \"available\" };\n impact?: ContextBundle[\"impact\"];\n relatedTests?: string[];\n diagnostics?: StoreDiagnostic[];\n freshness?: DriftReport | null;\n trust?: { features: Record<string, TrustState>; flows: Record<string, TrustState> };\n task: string;\n features: Record<string, never>;\n flows: Record<string, never>;\n /** Decisions can match even when no feature does. */\n decisions: Record<string, MatchedDecision>;\n /** The full feature catalog, so the caller can still act without a second guess. */\n availableFeatures: Record<string, string>;\n availableFlows: Record<string, string>;\n hint: string;\n}\n\nexport interface UnmappedContextBundle extends Omit<ContextBundle, \"exists\" | \"map\" | \"freshness\"> {\n /** Legacy exists indicates map availability, not decision availability. */\n exists: false;\n map: { status: \"missing\" | \"invalid\" };\n freshness: { stale: null; recommendation: \"no-map\" | \"repair-map\"; staleMatches: string[] };\n}\n\nasync function collectImpact(root: string, candidates: string[]): Promise<{\n impact: ContextBundle[\"impact\"]; relatedTests: string[];\n}> {\n const targets = new Set<string>();\n let sourceFiles: string[] | undefined;\n for (const candidate of sanitizeRepoPaths(candidates)) {\n const stat = await fs.stat(path.join(root, candidate)).catch(() => null);\n if (stat?.isDirectory()) {\n sourceFiles ??= await (await createFileAccess(root)).list();\n for (const file of sourceFiles) {\n if (anchorMatches(candidate, file)) targets.add(file);\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n } else {\n targets.add(candidate);\n }\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n if (!targets.size) return { impact: null, relatedTests: [] };\n const result = await analyzeImpact(root, [...targets]);\n const referenceCandidatesOmitted = result.references.filter(r => r.evidence === \"name-candidate\").length;\n return {\n impact: { targets: result.targetFiles, cochange: result.cochange, references: result.references.filter(r => r.evidence !== \"name-candidate\").slice(0, 10),\n ...(referenceCandidatesOmitted ? { referenceCandidatesOmitted } : {}) },\n relatedTests: [...new Set(result.tests.map(t => t.file))],\n };\n}\n\n/**\n * Assemble everything needed to start a task in one call: matching map\n * entries, their files and tests, blast radius for the top files, and\n * per-entry freshness. Deterministic and LLM-free.\n *\n * `files` optionally anchors matching to an explicit file list (e.g. a diff):\n * entries containing those files are boosted above pure lexical matches.\n */\nexport async function assembleContext(\n rootDir: string,\n task: string,\n files?: string[]\n): Promise<ContextBundle | NoMatchBundle | UnmappedContextBundle> {\n const resolvedRoot = path.resolve(rootDir);\n const mapState = await inspectSnapshot(resolvedRoot);\n const snapshot = mapState.snapshot;\n const store = await loadDecisionStore(resolvedRoot);\n const allDecisions = store.records;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, allDecisions);\n const taskTokens = tokenSet(task);\n const anchorFiles = new Set(sanitizeRepoPaths(files ?? []));\n\n const anchorBoost = (entryFiles: string[]): number => {\n let boost = 0;\n for (const f of entryFiles) if ([...anchorFiles].some(file => anchorMatches(f, file))) boost += 5;\n return boost;\n };\n\n if (!snapshot) {\n const decisions = matchDecisions(allDecisions, taskTokens, anchorBoost, new Set(), decisionDrift);\n const { impact, relatedTests } = await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]);\n const invalid = mapState.status === \"invalid\";\n return {\n exists: false, map: { status: invalid ? \"invalid\" : \"missing\" }, task,\n features: {}, flows: {}, decisions, impact, relatedTests,\n diagnostics: [...mapState.diagnostics, ...store.diagnostics],\n freshness: { stale: null, recommendation: invalid ? \"repair-map\" : \"no-map\", staleMatches: [] },\n hint: (invalid ? \"The concept map is invalid; consult diagnostics and repair it before relying on map entries. \" : \"No concept map is present. Maps are optional; decisions and file impact work now. \") +\n (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" + trustHint(Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])) : \"No saved decision matched. Inspect the source and use save_decision for a learned constraint or incident rationale. \") +\n (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n }\n\n const drift = await computeDrift(resolvedRoot);\n const readTrust = createSnapshotTrustReader(resolvedRoot);\n\n const featureScores = Object.entries(snapshot.features)\n .map(([name, feat]) => ({\n name,\n feat,\n score:\n scoreEntry(taskTokens, { name, description: feat.description, files: feat.files }) +\n anchorBoost([...feat.files, ...(feat.tests ?? [])]),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FEATURES);\n\n const flowScores = Object.entries(snapshot.flows)\n .map(([name, flow]) => ({\n name,\n flow,\n score:\n scoreEntry(taskTokens, { name, description: flow.description, files: flow.chain }) +\n anchorBoost(flow.chain),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FLOWS);\n\n const matchedEntryFiles = new Set<string>([\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap((e) => e.flow.chain),\n ]);\n const decisions = matchDecisions(\n allDecisions,\n taskTokens,\n anchorBoost,\n matchedEntryFiles,\n decisionDrift\n );\n\n if (featureScores.length === 0 && flowScores.length === 0) {\n const bundle = noMatchBundle(snapshot, task, decisions);\n Object.assign(bundle, await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]));\n bundle.diagnostics = store.diagnostics;\n bundle.freshness = drift;\n bundle.trust = await readSnapshotTrustIndex(readTrust, snapshot, drift);\n bundle.hint += \" \" + trustHint([\n ...Object.values(bundle.trust.features),\n ...Object.values(bundle.trust.flows),\n ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])]),\n ]);\n if (Object.keys(decisions).length) bundle.hint += \" \" + DECISION_GUIDANCE;\n if (store.diagnostics.length) bundle.hint += \" Some decision records are invalid; consult diagnostics.\";\n return bundle;\n }\n\n const features: Record<string, MatchedFeature> = {};\n const staleMatches: string[] = [];\n for (const { name, feat, score } of featureScores) {\n const trust = await readTrust(\"feature\", name, feat, drift?.featureFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n features[name] = {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n score,\n stale,\n trust,\n };\n }\n\n const flows: Record<string, MatchedFlow> = {};\n for (const { name, flow, score } of flowScores) {\n const trust = await readTrust(\"flow\", name, flow, drift?.flowFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n flows[name] = {\n description: flow.description,\n chain: flow.chain,\n score,\n stale,\n trust,\n };\n }\n\n const { impact, relatedTests: impactTests } = await collectImpact(resolvedRoot, [\n ...anchorFiles,\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap(e => e.flow.chain),\n ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])]),\n ]);\n\n const relatedTests = [\n ...new Set([\n ...featureScores.flatMap((e) => e.feat.tests ?? []),\n ...impactTests,\n ]),\n ];\n\n const stale = drift?.stale ?? false;\n return {\n exists: true,\n map: { status: \"available\" },\n diagnostics: store.diagnostics,\n task,\n features,\n flows,\n decisions,\n relatedTests,\n impact,\n freshness: {\n stale,\n recommendation: drift?.recommendation ?? \"up-to-date\",\n staleMatches,\n },\n hint: (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" : \"\") + trustHint([...Object.values(features).map(e => e.trust), ...Object.values(flows).map(e => e.trust), ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])]) + (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n}\n\n/**\n * Score active decisions against the task with the same lexical machinery\n * as map entries, plus a feature-overlap boost: a decision anchored to a\n * file of an already-matched feature is relevant even with zero lexical\n * overlap (\"auth is weird\" should surface on any auth task).\n */\nfunction matchDecisions(\n allDecisions: DecisionRecord[],\n taskTokens: Set<string>,\n anchorBoost: (files: string[]) => number,\n matchedEntryFiles: Set<string>,\n decisionDrift: DecisionDriftReport\n): Record<string, MatchedDecision> {\n const scored = allDecisions\n .filter((d) => d.status === \"active\")\n .map((d) => {\n const scoreRevision = (revision: DecisionRecord) =>\n scoreEntry(taskTokens, { name: revision.title, description: revision.body, files: revision.files }) + anchorBoost(revision.files) +\n (revision.files.some(f => [...matchedEntryFiles].some(file => anchorMatches(f, file))) ? DECISION_FEATURE_OVERLAP_BOOST : 0);\n const score = Math.max(scoreRevision(effectiveDecision(d)), scoreRevision(d));\n return { d, score };\n })\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_DECISIONS);\n\n const result: Record<string, MatchedDecision> = {};\n for (const { d, score } of scored) {\n result[d.id] = {\n ...decisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\"),\n score,\n stale: decisionDrift.freshness?.[d.id] !== \"current\",\n };\n }\n return result;\n}\n\nfunction noMatchBundle(\n snapshot: Snapshot,\n task: string,\n decisions: Record<string, MatchedDecision>\n): NoMatchBundle {\n const availableFeatures: Record<string, string> = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n availableFeatures[name] = feat.description;\n }\n const availableFlows: Record<string, string> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n availableFlows[name] = flow.description;\n }\n return {\n exists: true,\n map: { status: \"available\" },\n task,\n features: {},\n flows: {},\n decisions,\n availableFeatures,\n availableFlows,\n hint: \"No map entry matched the task wording. The full catalog is listed — pick the relevant entries and call get_context again with their names in the task, or read their files directly via get_snapshot.\",\n };\n}\n","import fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { withLock, events, type Host } from \"../automation/store.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { effectiveSetup } from \"./model.js\";\nimport { executingVersion, inactiveSetupMessage } from \"./launcher.js\";\n\nconst observationSchema = z.object({ version: z.literal(1), masonVersion: z.string(), root: z.string(), revision: z.string(), host: z.enum([\"codex\", \"claude\"]),\n contextCalls: z.number().int().nonnegative(), lastContextAt: z.string().optional(),\n sessions: z.record(z.object({ events: z.array(z.enum(events)), at: z.string(),\n verificationStatus: z.string().optional(), reportPath: z.string().optional() })),\n});\nexport type Observation = z.infer<typeof observationSchema>;\nexport function observationPath(directory: string, host: Host, revision: string, version = executingVersion()) { return `${directory}/activation/${host}-${revision}-${hash(version).slice(0, 12)}.json`; }\n\nexport async function readObservation(root: string, directory: string, host: Host, revision: string, version = executingVersion()): Promise<Observation | null> {\n const raw = await readStoreJson(root, observationPath(directory, host, revision, version));\n if (raw === null) return null;\n const record = observationSchema.parse(raw);\n if (record.root !== root || record.host !== host || record.revision !== revision || record.masonVersion !== version) throw new Error(\"Activation receipt belongs to another installation.\");\n return record;\n}\n\n/** Only the configured Mason invocation supplies these values. Never persist task text or tool arguments. */\nexport async function observeActivation(dir: string, event: \"context\" | typeof events[number], options: {\n sessionId?: string; verificationStatus?: string; reportPath?: string; directory?: string;\n} = {}): Promise<string | null> {\n const host = process.env.MASON_SETUP_HOST, revision = process.env.MASON_SETUP_REVISION;\n if ((host !== \"codex\" && host !== \"claude\") || !process.env.MASON_SETUP_ROOT) return null;\n try {\n if (!revision) {\n if ((await effectiveSetup(process.env.MASON_SETUP_ROOT)).setup?.hosts[host]) {\n return \"Mason setup is now present. Restart the assistant to connect this MCP session to the configured integration; activation has not been established by this session.\";\n }\n return inactiveSetupMessage();\n }\n const capturedDirectory = options.directory?.match(/^\\.mason\\/reports\\/automation\\/[a-f0-9]{24}$/)?.[0]\n ?? options.reportPath?.match(/^(\\.mason\\/reports\\/automation\\/[a-f0-9]{24})\\/checks\\//)?.[1];\n const ws = capturedDirectory ? { root: await fs.realpath(dir), directory: capturedDirectory } : await workspace(dir);\n if (ws.root !== await fs.realpath(process.env.MASON_SETUP_ROOT)) return null;\n const { setup } = await effectiveSetup(ws.root);\n if (setup?.hosts[host]?.revision !== revision) return \"Mason setup changed; restart the assistant to observe the current integration.\";\n const directory = ws.directory + \"/activation\";\n await withLock(ws.root, directory, async () => {\n const now = new Date().toISOString();\n const record = await readObservation(ws.root, ws.directory, host, revision) ?? {\n version: 1, masonVersion: executingVersion(), root: ws.root, revision, host, contextCalls: 0, sessions: {},\n } satisfies Observation;\n if (event === \"context\") { record.contextCalls++; record.lastContextAt = now; }\n else if (options.sessionId) {\n const key = hash(options.sessionId);\n const session = record.sessions[key] ?? { events: [], at: now };\n // Repeated tool observations add no activation evidence; avoid another write.\n if (event !== \"task_end\" && session.events.includes(event)) return;\n session.events = [...new Set([...session.events, event])];\n session.at = now;\n if (event === \"task_end\") { session.verificationStatus = options.verificationStatus; session.reportPath = options.reportPath; }\n record.sessions[key] = session;\n const ordered = Object.entries(record.sessions).sort(([, a], [, b]) => b.at.localeCompare(a.at));\n record.sessions = Object.fromEntries(ordered.slice(0, 32));\n } else return;\n await writeStoreJson(ws.root, observationPath(ws.directory, host, revision), record);\n });\n return null;\n } catch (error) {\n return \"Mason activation observation could not be saved; activation coverage is unknown. \" + (error instanceof Error ? error.message : String(error)).replace(/[\\u0000-\\u001f\\u007f]/g, \" \").slice(0, 300);\n }\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { events, type Host } from \"../automation/store.js\";\nimport { automationStatus } from \"../automation/runtime.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { hookConfig } from \"../automation/adapters.js\";\nimport { effectiveSetup, loadSetupReceipt } from \"./model.js\";\nimport { inspectHostConfig, instructionEdits } from \"./config.js\";\nimport { hookCommand, mcpCommand, installedCommand } from \"./launcher.js\";\nimport { readObservation } from \"./observations.js\";\n\nexport async function setupStatus(dir: string) {\n const ws = await workspace(dir);\n const activation = await effectiveSetup(ws.root);\n const setup = activation.setup;\n if (!setup || !Object.keys(setup.hosts).length) {\n const partial = await Promise.all(([\"codex\", \"claude\"] as const).map(async host => ({ host,\n receipt: await loadSetupReceipt(ws.root, ws.directory, host) })));\n const pending = partial.filter(item => item.receipt !== null).map(item => item.host);\n return { version: 1, status: pending.length ? \"incomplete\" : \"not-configured\", hosts: {},\n next: pending.length ? \"Setup did not finish. Rerun mason-auto setup --host \" + pending[0] + \" to resume using the retained original evidence.\"\n : \"Project hooks are inactive until local setup. Run mason setup --host codex or --host claude.\" };\n }\n const hosts: Record<string, { status: string; runtime: string; mcp: string; instructions: string; hookConfiguration: string;\n observedEvents: string[]; contextCalls: number; verificationStatus: string; pending: string[]; updates: string[] }> = {};\n const installed = await installedCommand();\n const automation = await automationStatus(ws.root);\n for (const host of [\"codex\", \"claude\"] as const) {\n const entry = setup.hosts[host];\n if (!entry) continue;\n const instructions = await instructionEdits(ws.root, host);\n const instructionsCurrent = instructions.every(edit => edit.before === edit.after);\n const config = await inspectHostConfig(ws.root, host, undefined);\n const mcp = !config.mcpDisabled && hash(config.mcp) === entry.mcpFingerprint &&\n isDeepStrictEqual({ command: config.mcp?.command, args: config.mcp?.args }, mcpCommand(host));\n const expectedHooks = hookConfig(host, hookCommand(host)).hooks;\n const currentHooks = isDeepStrictEqual(config.hooks, expectedHooks);\n const compatibleHooks = Object.fromEntries(Object.entries(config.hooks).map(([event, groups]) => [event,\n groups.map(group => ({ ...group, hooks: group.hooks.map(handler => ({ ...handler,\n command: expectedHooks.SessionStart[0].hooks[0].command })) }))]));\n const hooks = isDeepStrictEqual(compatibleHooks, expectedHooks) && !config.disabled;\n const local = await loadSetupReceipt(ws.root, ws.directory, host);\n const configured = activation.root !== ws.root || local?.status === \"configured\" && local.root === ws.root && local.revision === entry.revision;\n const observation = await readObservation(ws.root, ws.directory, host, entry.revision, installed.version ?? \"unavailable\");\n // Complete lifecycle evidence must come from one session in this worktree/branch.\n const sessions = Object.values(observation?.sessions ?? {}).sort((a, b) => b.at.localeCompare(a.at));\n const complete = sessions.find(session => events.every(event => session.events.includes(event)));\n const observedEvents = complete?.events ?? sessions[0]?.events ?? [];\n const pending: string[] = [];\n if (!installed.available) pending.push(installed.message!);\n if (!mcp || !hooks || !instructionsCurrent || !configured) pending.push(\"Rerun setup to reconcile project configuration; inspect any disabled host settings.\");\n if (!observation?.contextCalls) pending.push(\"Start a new assistant session and request task context through Mason's get_context tool.\");\n if (!complete) pending.push(\"Review/trust the host configuration, then complete a normal task to observe the full hook lifecycle.\");\n if (automation.status === \"unavailable\") pending.push(\"The latest automation attempt did not establish verification. Run mason-auto check and inspect its diagnostics.\");\n const healthy = installed.available && mcp && hooks && instructionsCurrent && configured && automation.status !== \"unavailable\";\n hosts[host] = { status: healthy ? complete && observation?.contextCalls ? \"active\" : \"pending\" : \"attention\",\n runtime: installed.available ? \"global (\" + installed.version + \")\" : \"unavailable-on-path\", mcp: mcp ? \"configured\" : \"changed\",\n instructions: instructionsCurrent ? \"current\" : \"changed\", hookConfiguration: hooks ? currentHooks ? \"configured\" : \"compatible\" : \"disabled-or-changed\",\n observedEvents, contextCalls: observation?.contextCalls ?? 0,\n verificationStatus: automation.status === \"current\" ? automation.verificationStatus ?? \"unavailable\" : \"unavailable\", pending,\n updates: hooks && !currentHooks ? [\"A newer hook template is available. Run mason setup --host \" + host + \" to update it when convenient; review and commit the configuration changes.\"] : [] };\n }\n const statuses = Object.values(hosts).map(host => host.status);\n const decisions = await loadDecisionStore(ws.root);\n return { version: 1, status: statuses.length && statuses.every(status => status === \"active\") ? \"active\"\n : statuses.includes(\"attention\") ? \"attention\" : \"pending\", root: ws.root, hosts, activationRoot: activation.root,\n decisionRecords: decisions.records.length, diagnostics: decisions.diagnostics,\n scope: \"Activation receipts record observed use after setup, not complete interception, correct repairs, or measured usefulness. Host trust and higher-priority settings may prevent execution. Receipts are local to this worktree and branch.\" };\n}\n\nexport function summarizeActivation(status: Awaited<ReturnType<typeof setupStatus>>): string {\n const lines = [\"Mason setup: \" + status.status + \".\"];\n if (status.activationRoot && status.activationRoot !== status.root) {\n lines.push(\"Activation inherited from \" + status.activationRoot + \"; evidence belongs to this worktree.\");\n }\n for (const [host, state] of Object.entries(status.hosts)) {\n lines.push(`${host}: ${state.status}`, ` Runtime: ${state.runtime}; MCP: ${state.mcp}; instructions: ${state.instructions}.`,\n ` Hooks: ${state.hookConfiguration}; observed: ${state.observedEvents.join(\", \") || \"none\"}.`,\n ` Task context requests: ${state.contextCalls}; verification: ${state.verificationStatus}.`,\n ...state.pending.map(message => \" Next: \" + message));\n lines.push(...state.updates.map(message => \" Optional: \" + message));\n }\n if (\"decisionRecords\" in status) lines.push(`Decision records: ${status.decisionRecords}.`);\n if (status.next) lines.push(status.next);\n return lines.join(\"\\n\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { hash, workspace } from \"../automation/evidence.js\";\nimport { withLock, type Host } from \"../automation/store.js\";\nimport { automate } from \"../automation/runtime.js\";\nimport { inspectOnboarding } from \"../mcp/onboarding.js\";\nimport { writeStoreJson } from \"../utils/storage.js\";\nimport { applyEdit, readText } from \"./files.js\";\nimport { ancillaryEdits, hookEdits, instructionEdits, mcpEdit, inspectHostConfig } from \"./config.js\";\nimport { hookCommand, installedCommand } from \"./launcher.js\";\nimport { hookConfig } from \"../automation/adapters.js\";\nimport { loadSetup, loadSetupReceipt, SETUP_PATH, type SetupConfig } from \"./model.js\";\nimport { setupStatus } from \"./status.js\";\nimport { ownershipEdit, completedHookOwnership } from \"./ownership.js\";\nimport type { Progress } from \"../utils/progress.js\";\n\nexport async function selectHost(root: string, explicit?: Host): Promise<Host> {\n if (explicit) return explicit;\n if (process.env.MASON_SETUP_HOST === \"codex\" || process.env.MASON_SETUP_HOST === \"claude\") return process.env.MASON_SETUP_HOST;\n const found: Host[] = [];\n if (await readText(root, \".codex/config.toml\") !== null || await readText(root, \".codex/hooks.json\") !== null) found.push(\"codex\");\n if (await readText(root, \".claude/settings.json\") !== null || await readText(root, \".mcp.json\") !== null) found.push(\"claude\");\n if (found.length === 1) return found[0];\n throw new Error(\"Choose the assistant for setup with --host codex or --host claude.\");\n}\n\nexport async function setupProject(dir: string, options: { host?: Host; base?: string; evidence?: string[]; progress?: Progress } = {}) {\n options.progress?.step(\"Checking project configuration\");\n const ws = await workspace(dir);\n const host = await selectHost(ws.root, options.host);\n return withLock(ws.root, \".mason/reports/setup-lock\", async () => {\n const existing = await loadSetup(ws.root);\n const previousReceipt = await loadSetupReceipt(ws.root, ws.directory, host);\n const installed = await installedCommand();\n if (!installed.available) throw new Error(installed.message!);\n // Preflight every edit before shared files change.\n const instructions = await instructionEdits(ws.root, host);\n const mcp = await mcpEdit(ws.root, host);\n const hooks = await hookEdits(ws.root, host);\n const ancillary = await ancillaryEdits(ws.root);\n const edits = [...ancillary, ...instructions, mcp, ...hooks];\n const setupBefore = await readText(ws.root, SETUP_PATH);\n const mcpFingerprint = hash((await inspectHostConfig(ws.root, host, mcp.after)).mcp);\n const desiredHooks = hookConfig(host, hookCommand(host)).hooks;\n const configuredHook = desiredHooks.SessionStart[0].hooks[0].command;\n const ownership = await ownershipEdit(ws.root, [...instructions, mcp, hooks[0]], { [hooks[0].path]: configuredHook });\n const fingerprint = hash({ command: \"mason\",\n mcp: mcpFingerprint, hooks: desiredHooks,\n instructions: instructions.map(edit => edit.path) });\n const previous = existing?.hosts[host];\n const changed = edits.some(edit => edit.before !== edit.after) || previous?.fingerprint !== fingerprint;\n const revision = !changed && previous ? previous.revision : randomUUID();\n const setup: SetupConfig = existing ?? { version: 2, hosts: {} };\n setup.hosts[host] = { configuredVersion: installed.version!, revision, fingerprint, mcpFingerprint, instructions: instructions.map(e => e.path) };\n\n // Capture through the ordinary automation engine so later hooks resume the\n // same immutable baselines. This must precede instruction and ignore edits.\n options.progress?.step(\"Auditing documentation and preserving original findings\");\n const initial = await automate(ws.root, { event: \"turn_start\" });\n options.progress?.step(\"Reviewing project context and committed changes\");\n const findings = await inspectOnboarding(ws.root, options.base, options.evidence);\n const receiptPath = ws.directory + \"/setup-\" + host + \".json\";\n const initialReportPath = previousReceipt?.initialReportPath ?? initial.report.reportPath;\n const initialBaselinePaths = previousReceipt?.initialBaselinePaths ?? initial.report.baselinePaths;\n options.progress?.step(`Configuring ${host === \"codex\" ? \"Codex\" : \"Claude Code\"} integration`);\n await writeStoreJson(ws.root, receiptPath, { version: 1, host, status: \"installing\", initialReportPath,\n initialBaselinePaths, root: ws.root, revision });\n const changedFiles: string[] = [];\n if (await applyEdit(ws.root, ownership)) changedFiles.push(ownership.path);\n for (const edit of edits) if (await applyEdit(ws.root, edit)) changedFiles.push(edit.path);\n if (await applyEdit(ws.root, { path: SETUP_PATH, before: setupBefore, after: JSON.stringify(setup, null, 2) + \"\\n\" })) changedFiles.push(SETUP_PATH);\n if (await applyEdit(ws.root, await completedHookOwnership(ws.root, hooks[0].path, configuredHook)) && !changedFiles.includes(ownership.path)) changedFiles.push(ownership.path);\n // Ensure a repo that initially had no instructions now has a baseline too.\n options.progress?.step(\"Checking configuration and retained findings\");\n const checked = await automate(ws.root, { event: \"turn_start\" });\n const configured = await inspectHostConfig(ws.root, host, undefined);\n await writeStoreJson(ws.root, receiptPath, { version: 1, host, status: \"configured\", initialReportPath,\n initialBaselinePaths, root: ws.root, revision, configuredAt: new Date().toISOString() });\n return { version: 1, action: \"setup\", status: \"configured\", host, root: ws.root,\n runtime: { kind: \"global\", command: \"mason\", version: installed.version }, changedFiles, initialReportPath, findings, reportPath: checked.report.reportPath,\n activation: await setupStatus(ws.root),\n next: configured.disabled || configured.mcpDisabled ? \"Mason hooks or MCP are disabled in project configuration. Review that setting before activation.\"\n : host === \"codex\" ? \"Review/trust this project's MCP configuration and hooks in Codex (/hooks in the CLI), then start a new session and give it a normal task.\"\n : \"Approve the project MCP server in Claude Code, then start a new session and give it a normal task.\",\n };\n });\n}\n\nexport function summarizeSetup(result: Awaited<ReturnType<typeof setupProject>>): string {\n const audit = result.findings.audit;\n return [`Mason configured for ${result.host}.`,\n \" MCP server and lifecycle hooks use mason from PATH.\",\n \" Project instructions updated; original audit evidence retained.\",\n ` ${result.changedFiles.length} files changed.`,\n `Initial audit: ${audit.status}${\"counts\" in audit ? `; ${audit.counts.issues} issues, ${audit.counts.advisories + audit.counts.suppressedAdvisories} advisories` : \"\"}.`,\n ...(\"issues\" in audit ? audit.issues.slice(0, 3).map(f => \" \" + f.message) : []),\n `Original evidence: ${result.initialReportPath}`,\n \"Activation: \" + result.activation.status + \".\",\n result.next,\n \"If the assistant cannot find mason, restart the desktop app so it picks up PATH.\",\n \"After the task finishes, run mason-auto status. Configuration alone does not establish activation.\",\n ].join(\"\\n\");\n}\n","import type { ConfluenceConfig } from \"../llm/config.js\";\n\nexport interface ConfluencePage {\n id: string;\n title: string;\n version: number;\n body: string;\n parentId?: string;\n}\n\nexport interface CreatePageInput {\n spaceId: string;\n title: string;\n body: string;\n parentId?: string;\n}\n\nexport interface UpdatePageInput {\n id: string;\n title: string;\n body: string;\n version: number;\n parentId?: string;\n}\n\nexport interface ConfluenceSpace {\n id: string;\n key: string;\n name: string;\n}\n\nexport interface ConfluenceRootPage {\n id: string;\n title: string;\n}\n\nexport interface ConfluenceClient {\n resolveSpaceId(spaceKey: string): Promise<string>;\n listSpaces(): Promise<ConfluenceSpace[]>;\n listRootPages(spaceId: string): Promise<ConfluenceRootPage[]>;\n findPageByTitle(spaceId: string, title: string): Promise<ConfluencePage | null>;\n createPage(input: CreatePageInput): Promise<ConfluencePage>;\n updatePage(input: UpdatePageInput): Promise<ConfluencePage>;\n}\n\ninterface PageApiResponse {\n id: string;\n title: string;\n parentId?: string;\n version?: { number: number };\n body?: { storage?: { value?: string } };\n}\n\nexport function createConfluenceClient(\n config: ConfluenceConfig,\n fetchFn: typeof fetch = fetch\n): ConfluenceClient {\n const baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n const auth =\n \"Basic \" +\n Buffer.from(`${config.email}:${config.apiToken}`).toString(\"base64\");\n\n async function call(\n method: string,\n path: string,\n body?: unknown\n ): Promise<unknown> {\n const res = await fetchFn(`${baseUrl}${path}`, {\n method,\n headers: {\n Authorization: auth,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `Confluence ${method} ${path} failed: ${res.status} ${res.statusText} — ${text}`\n );\n }\n\n if (res.status === 204) return null;\n return res.json();\n }\n\n function toPage(raw: PageApiResponse): ConfluencePage {\n return {\n id: raw.id,\n title: raw.title,\n version: raw.version?.number ?? 1,\n body: raw.body?.storage?.value ?? \"\",\n parentId: raw.parentId,\n };\n }\n\n return {\n async resolveSpaceId(spaceKey: string): Promise<string> {\n const res = (await call(\n \"GET\",\n `/wiki/api/v2/spaces?keys=${encodeURIComponent(spaceKey)}`\n )) as { results?: Array<{ id: string; key: string }> };\n const space = res.results?.find((s) => s.key === spaceKey);\n if (!space) {\n throw new Error(`Confluence space not found: ${spaceKey}`);\n }\n return space.id;\n },\n\n async listSpaces(): Promise<ConfluenceSpace[]> {\n const all: ConfluenceSpace[] = [];\n let cursor = \"/wiki/api/v2/spaces?limit=100\";\n while (cursor) {\n const res = (await call(\"GET\", cursor)) as {\n results?: Array<{ id: string; key: string; name?: string }>;\n _links?: { next?: string };\n };\n for (const s of res.results ?? []) {\n all.push({ id: s.id, key: s.key, name: s.name ?? s.key });\n }\n const next = res._links?.next;\n if (!next) break;\n // v2 returns relative paths beginning with \"/wiki/...\"\n cursor = next.startsWith(\"/\") ? next : `/${next}`;\n }\n return all;\n },\n\n async listRootPages(spaceId: string): Promise<ConfluenceRootPage[]> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?depth=root&limit=50`;\n const res = (await call(\"GET\", url)) as {\n results?: Array<{ id: string; title: string }>;\n };\n return (res.results ?? []).map((p) => ({ id: p.id, title: p.title }));\n },\n\n async findPageByTitle(\n spaceId: string,\n title: string\n ): Promise<ConfluencePage | null> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?title=${encodeURIComponent(title)}&body-format=storage&limit=1`;\n const res = (await call(\"GET\", url)) as {\n results?: PageApiResponse[];\n };\n const match = res.results?.find((p) => p.title === title);\n return match ? toPage(match) : null;\n },\n\n async createPage(input: CreatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"POST\", \"/wiki/api/v2/pages\", {\n spaceId: input.spaceId,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n\n async updatePage(input: UpdatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"PUT\", `/wiki/api/v2/pages/${input.id}`, {\n id: input.id,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n version: {\n number: input.version + 1,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport type Provider = \"claude\" | \"gemini\" | \"openai\" | \"ollama\";\n\nexport interface ConfluenceConfig {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey: string;\n parentPageId?: string;\n}\n\nexport interface MasonConfig {\n provider: Provider;\n apiKey?: string;\n model?: string;\n ollamaHost?: string;\n confluence?: ConfluenceConfig;\n}\n\nfunction configDir(): string {\n return path.join(os.homedir(), \".mason\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nconst DEFAULT_MODELS: Record<Provider, string> = {\n claude: \"claude-sonnet-4-20250514\",\n gemini: \"gemini-2.5-flash\",\n openai: \"gpt-4o\",\n ollama: \"llama3\",\n};\n\nexport async function loadConfig(): Promise<MasonConfig | null> {\n try {\n const raw = await fs.readFile(configFile(), \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: MasonConfig): Promise<void> {\n await fs.mkdir(configDir(), { recursive: true });\n await fs.writeFile(configFile(), JSON.stringify(config, null, 2), \"utf-8\");\n}\n\nexport function getDefaultModel(provider: Provider): string {\n return DEFAULT_MODELS[provider];\n}\n\nexport function validateProvider(value: string): Provider {\n const valid: Provider[] = [\"claude\", \"gemini\", \"openai\", \"ollama\"];\n if (!valid.includes(value as Provider)) {\n throw new Error(\n `Invalid provider \"${value}\". Must be one of: ${valid.join(\", \")}`\n );\n }\n return value as Provider;\n}\n\nexport async function detectCLI(\n provider: Provider\n): Promise<{ available: boolean; version?: string }> {\n const cliName = provider === \"claude\" ? \"claude\"\n : provider === \"gemini\" ? \"gemini\"\n : provider === \"ollama\" ? \"ollama\"\n : null;\n\n if (!cliName) return { available: false };\n\n try {\n const { stdout } = await exec(cliName, [\"--version\"]);\n return { available: true, version: stdout.trim() };\n } catch {\n return { available: false };\n }\n}\n\nexport function needsApiKey(provider: Provider): boolean {\n return provider === \"openai\";\n}\n\nexport async function saveConfluenceConfig(\n confluence: ConfluenceConfig\n): Promise<void> {\n const existing = (await loadConfig()) ?? { provider: \"claude\" as Provider };\n await saveConfig({ ...existing, confluence });\n}\n\nexport async function loadConfluenceConfig(): Promise<ConfluenceConfig | null> {\n const config = await loadConfig();\n return config?.confluence ?? null;\n}\n","export function normalizeAtlassianBaseUrl(input: string): string {\n const trimmed = input.trim().replace(/\\/+$/, \"\");\n if (!trimmed) throw new Error(\"Confluence baseUrl is required.\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n if (trimmed.includes(\".\")) return `https://${trimmed}`;\n // Bare subdomain — assume Atlassian Cloud\n return `https://${trimmed}.atlassian.net`;\n}\n","import type { FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\n\n// Mason fully owns each page body and overwrites it on every sync. Confluence\n// strips HTML comments and re-serializes storage XHTML, so in-page region\n// markers can't survive a round-trip — no-op detection happens via a content\n// hash in the local sync state instead (see sync.ts / diff.ts).\n\nfunction escape(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction infoPanel(text: string): string {\n return (\n `<ac:structured-macro ac:name=\"info\"><ac:rich-text-body>` +\n `<p>${escape(text)}</p>` +\n `</ac:rich-text-body></ac:structured-macro>`\n );\n}\n\nexport function featurePageTitle(prefix: string, name: string): string {\n return `${prefix}${name}`;\n}\n\nexport interface RenderedFeaturePage {\n body: string;\n title: string;\n}\n\nexport interface RenderFeaturePageOptions {\n name: string;\n productDescription: string;\n flowDescriptions: Array<{ name: string; description: string }>;\n indexPageTitle: string;\n}\n\nexport function renderFeaturePage(\n options: RenderFeaturePageOptions\n): RenderedFeaturePage {\n const overviewBody =\n `<h2>What it does</h2>` + `<p>${escape(options.productDescription)}</p>`;\n\n // Only render \"How it fits in\" when there are flows — an empty section with a\n // \"nothing here\" placeholder reads as unfinished.\n const flowsBody = options.flowDescriptions.length\n ? `<h2>How it fits in</h2><ul>` +\n options.flowDescriptions\n .map(\n (f) =>\n `<li><strong>${escape(f.name)}</strong> — ${escape(f.description)}</li>`\n )\n .join(\"\") +\n `</ul>`\n : \"\";\n\n // Native Confluence page link, resolved by title.\n const navBody =\n `<p><ac:link><ri:page ri:content-title=\"${escape(options.indexPageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[Back to ${options.indexPageTitle}]]></ac:plain-text-link-body>` +\n `</ac:link></p>`;\n\n // Provenance note as a footer, not wedged between the content sections.\n const footer = infoPanel(\n `Generated from code by Mason. This page is overwritten on each sync — ` +\n `edit the code, not the page.`\n );\n\n const body = overviewBody + flowsBody + navBody + footer;\n\n return {\n title: options.name,\n body,\n };\n}\n\nexport interface RenderIndexPageOptions {\n featureTitles: string[];\n featurePrefix: string;\n}\n\nexport function renderIndexPage(options: RenderIndexPageOptions): string {\n if (options.featureTitles.length === 0) {\n return infoPanel(\"No features in the snapshot yet.\");\n }\n\n const list =\n `<h2>Features</h2><ul>` +\n options.featureTitles\n .map((name) => {\n const pageTitle = featurePageTitle(options.featurePrefix, name);\n return (\n `<li><ac:link><ri:page ri:content-title=\"${escape(pageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[${name}]]></ac:plain-text-link-body>` +\n `</ac:link></li>`\n );\n })\n .join(\"\") +\n `</ul>`;\n\n const banner = infoPanel(\n `Generated from code by Mason. Maintained automatically — edit the code, not this page.`\n );\n\n return banner + list;\n}\n\nexport interface DiffSection {\n syncedAt: string;\n addedFeatures: string[];\n removedFeatures: string[];\n changedFeatures: string[];\n addedFlows: string[];\n removedFlows: string[];\n}\n\nexport function renderChangelogSection(section: DiffSection): string {\n const segments: string[] = [];\n if (section.addedFeatures.length) {\n segments.push(\n `<p><strong>Added features:</strong> ${section.addedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFeatures.length) {\n segments.push(\n `<p><strong>Removed features:</strong> ${section.removedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.changedFeatures.length) {\n segments.push(\n `<p><strong>Updated features:</strong> ${section.changedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.addedFlows.length) {\n segments.push(\n `<p><strong>Added flows:</strong> ${section.addedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFlows.length) {\n segments.push(\n `<p><strong>Removed flows:</strong> ${section.removedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (segments.length === 0) {\n segments.push(`<p><em>No meaningful changes detected.</em></p>`);\n }\n\n return (\n `<h3>${escape(section.syncedAt)}</h3>` + segments.join(\"\")\n );\n}\n\nexport function renderChangelogPage(sections: string[]): string {\n if (sections.length === 0) {\n return `<p><em>No sync has run yet.</em></p>`;\n }\n // Newest first\n return sections.join(\"\\n<hr/>\\n\");\n}\n\nexport type FeatureMap = Record<string, FeatureEntry>;\nexport type FlowMap = Record<string, FlowEntry>;\n\nexport function flowsForFeature(\n featureFiles: string[],\n flows: FlowMap\n): Array<{ name: string; description: string }> {\n const fileSet = new Set(featureFiles);\n const result: Array<{ name: string; description: string }> = [];\n for (const [name, flow] of Object.entries(flows)) {\n if (flow.chain.some((file) => fileSet.has(file))) {\n result.push({ name, description: flow.description });\n }\n }\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { DiffSection } from \"./renderer.js\";\n\nexport interface RewriteCacheEntry {\n /** sha256 of the engineering (source) description this prose was derived from */\n sourceHash: string;\n /** the cached product-language prose */\n product: string;\n /** true when produced by the no-LLM fallback, not the model — re-attempted next run */\n fallback?: boolean;\n}\n\nexport interface RewriteCache {\n features: Record<string, RewriteCacheEntry>;\n flows: Record<string, RewriteCacheEntry>;\n}\n\nexport interface SyncState {\n version: 2;\n syncedAt: string;\n pageIds: {\n index?: string;\n changelog?: string;\n features: Record<string, string>;\n };\n lastSnapshot: {\n features: Record<string, { description: string }>;\n flows: Record<string, { description: string }>;\n };\n changelogSections: string[];\n /** product-language prose cache, keyed by feature/flow name */\n rewriteCache: RewriteCache;\n /**\n * Hash of the body Mason last rendered for each page, keyed by page title.\n * Used to skip re-publishing unchanged pages — we compare our render hash to\n * this, never to Confluence's re-serialized body. Optional for forward\n * compatibility with state written before this field existed.\n */\n pageHashes?: Record<string, string>;\n}\n\n/** Stable content hash of a source description, for cache invalidation. */\nexport function hashDescription(description: string): string {\n return createHash(\"sha256\").update(description, \"utf8\").digest(\"hex\");\n}\n\nfunction syncStateDir(rootDir: string): string {\n return path.join(rootDir, \".mason\");\n}\n\nfunction syncStatePath(rootDir: string): string {\n return path.join(syncStateDir(rootDir), \"confluence-sync.json\");\n}\n\nexport async function loadSyncState(rootDir: string): Promise<SyncState | null> {\n try {\n const raw = await fs.readFile(syncStatePath(rootDir), \"utf-8\");\n const parsed = JSON.parse(raw);\n // Only v2 state is usable. Older state (v1) is treated as absent: the next\n // export re-finds pages by title and rebuilds the rewrite cache from scratch.\n if (parsed.version !== 2) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nexport async function saveSyncState(\n rootDir: string,\n state: SyncState\n): Promise<void> {\n await fs.mkdir(syncStateDir(rootDir), { recursive: true });\n await fs.writeFile(\n syncStatePath(rootDir),\n JSON.stringify(state, null, 2),\n \"utf-8\"\n );\n}\n\nexport function computeDiff(\n previous: SyncState | null,\n current: Snapshot,\n syncedAt: string\n): DiffSection {\n const prevFeatures = previous?.lastSnapshot.features ?? {};\n const prevFlows = previous?.lastSnapshot.flows ?? {};\n\n const currentFeatureNames = Object.keys(current.features);\n const prevFeatureNames = Object.keys(prevFeatures);\n\n const addedFeatures = currentFeatureNames.filter(\n (n) => !(n in prevFeatures)\n );\n const removedFeatures = prevFeatureNames.filter(\n (n) => !(n in current.features)\n );\n const changedFeatures = currentFeatureNames.filter(\n (n) =>\n n in prevFeatures &&\n prevFeatures[n].description !== current.features[n].description\n );\n\n const currentFlowNames = Object.keys(current.flows);\n const prevFlowNames = Object.keys(prevFlows);\n const addedFlows = currentFlowNames.filter((n) => !(n in prevFlows));\n const removedFlows = prevFlowNames.filter((n) => !(n in current.flows));\n\n return {\n syncedAt,\n addedFeatures,\n removedFeatures,\n changedFeatures,\n addedFlows,\n removedFlows,\n };\n}\n\nexport function isMeaningfulDiff(diff: DiffSection): boolean {\n return (\n diff.addedFeatures.length > 0 ||\n diff.removedFeatures.length > 0 ||\n diff.changedFeatures.length > 0 ||\n diff.addedFlows.length > 0 ||\n diff.removedFlows.length > 0\n );\n}\n\nexport function snapshotMinimal(snapshot: Snapshot): SyncState[\"lastSnapshot\"] {\n const features: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.features)) {\n features[k] = { description: v.description };\n }\n const flows: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.flows)) {\n flows[k] = { description: v.description };\n }\n return { features, flows };\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { MasonConfig } from \"./config.js\";\nimport { getDefaultModel } from \"./config.js\";\n\nconst exec = promisify(execFile);\n\nconst CLAUDE_MD_SYSTEM_PROMPT = `You are Mason, a context engineering tool. You've been given a comprehensive analysis of a codebase including:\n- Git history stats (commit patterns, frequently changed files, stale directories)\n- Project structure (directory layout, file counts by type)\n- Curated code samples (key architectural files with previews)\n- Test-to-source file mapping\n\nYour job: write a COMPLETE CLAUDE.md file from scratch based ONLY on the analysis data provided below. Do NOT read any existing files in the project. Do NOT reference or preserve any existing CLAUDE.md. Generate the entire document fresh.\n\nCRITICAL: Output ONLY the raw markdown content. No preamble, no summary, no \"Here's the CLAUDE.md:\", no explanation, no questions, no commentary. Start directly with \"# CLAUDE.md\" and end with the last line of content. Your entire response will be written directly to a file.\n\nThe CLAUDE.md should include:\n- Project overview (what it is, tech stack, architecture)\n- Module/package structure and boundaries\n- Code conventions and patterns you observe in the samples\n- Testing conventions and coverage\n- Build and development commands\n- Important files and hot spots\n- Any warnings or gotchas\n\nBe specific and actionable. Reference actual file paths. Don't be generic — every rule should be grounded in what you see in the data.`;\n\nexport type CallResult =\n | { type: \"response\"; text: string }\n | { type: \"prompt\"; text: string };\n\nexport async function callLLM(\n config: MasonConfig,\n userMessage: string,\n systemPrompt?: string\n): Promise<CallResult> {\n const model = config.model ?? getDefaultModel(config.provider);\n const system = systemPrompt ?? CLAUDE_MD_SYSTEM_PROMPT;\n\n switch (config.provider) {\n case \"claude\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callClaudeAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callClaudeCLI(system, userMessage),\n };\n\n case \"ollama\":\n return {\n type: \"response\",\n text: await callOllamaCLI(\n config.ollamaHost ?? \"http://localhost:11434\",\n model,\n system,\n userMessage,\n ),\n };\n\n case \"gemini\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callGeminiAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callGeminiCLI(system, userMessage),\n };\n\n case \"openai\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callOpenAIAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"prompt\",\n text: formatPromptForCopy(system, userMessage),\n };\n }\n}\n\nfunction formatPromptForCopy(system: string, userMessage: string): string {\n return `${system}\\n\\n---\\n\\n${userMessage}`;\n}\n\n// === CLI-based providers (no API key) ===\n\nasync function callViaTempFile(\n command: string,\n args: (promptPath: string) => string[],\n system: string,\n userMessage: string\n): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n const os = await import(\"node:os\");\n const path = await import(\"node:path\");\n\n const prompt = `${system}\\n\\n${userMessage}`;\n const tmpFile = path.join(os.tmpdir(), `mason-prompt-${Date.now()}.txt`);\n\n try {\n await fs.writeFile(tmpFile, prompt, \"utf-8\");\n const { stdout } = await exec(command, args(tmpFile), {\n maxBuffer: 10_000_000,\n timeout: 300_000,\n });\n return stdout.trim();\n } finally {\n await fs.unlink(tmpFile).catch(() => {});\n }\n}\n\nfunction spawnWithStdin(\n command: string,\n args: string[],\n input: string\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n timeout: 300_000,\n });\n\n // ora puts stdin into raw mode, which means Ctrl+C is emitted as\n // process.emit(\"SIGINT\") rather than a real signal to the process\n // group. Forward it to the child so it can terminate.\n const onSigint = () => proc.kill(\"SIGINT\");\n process.on(\"SIGINT\", onSigint);\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code: number | null) => {\n process.off(\"SIGINT\", onSigint);\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(new Error(`${command} exited with code ${code}: ${stderr}`));\n }\n });\n\n proc.on(\"error\", (err) => {\n process.off(\"SIGINT\", onSigint);\n reject(err);\n });\n\n proc.stdin.write(input);\n proc.stdin.end();\n });\n}\n\nasync function callClaudeCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n return spawnWithStdin(\"claude\", [\"-p\", \"--system-prompt\", system], userMessage);\n}\n\nasync function callGeminiCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n const prompt = `<system>\\n${system}\\n</system>\\n\\n${userMessage}`;\n return spawnWithStdin(\"gemini\", [\"-p\", \"\"], prompt);\n}\n\nasync function callOllamaCLI(\n host: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const response = await fetch(`${host}/api/chat`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n stream: false,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n }),\n });\n\n const result = (await response.json()) as {\n message?: { content?: string };\n };\n return result.message?.content ?? \"\";\n}\n\n// === API-based providers ===\n\nasync function callClaudeAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: Anthropic } = await import(\"@anthropic-ai/sdk\");\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model,\n max_tokens: 8192,\n system,\n messages: [{ role: \"user\", content: userMessage }],\n });\n\n const textBlock = response.content.find((b) => b.type === \"text\");\n return textBlock?.text ?? \"\";\n}\n\nasync function callGeminiAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({\n apiKey,\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n\nasync function callOpenAIAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({ apiKey });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n","import { callLLM } from \"../llm/providers.js\";\nimport type { MasonConfig } from \"../llm/config.js\";\nimport type {\n FeatureEntry,\n FlowEntry,\n Snapshot,\n} from \"../snapshot/snapshot.js\";\nimport {\n hashDescription,\n type RewriteCache,\n type RewriteCacheEntry,\n} from \"./diff.js\";\n\nconst PM_REWRITE_SYSTEM_PROMPT = `You are Mason, rewriting an engineering-flavoured concept map into product-readable language for a company wiki.\n\nYou will receive a JSON object with two maps:\n- \"features\": each entry has a description and a list of source file paths.\n- \"flows\": each entry has a description and an ordered chain of file paths.\n\nYour job: rewrite EACH description so a Product Manager, designer, or non-engineering stakeholder can understand what the system does — without seeing any code. Treat the file paths as hints, not content. Do NOT include them in your output.\n\nHard rules:\n- NEVER mention file names, directory names, file extensions, class names, function names, repository names, framework names, or libraries.\n- NEVER use words like \"module\", \"service\", \"handler\", \"controller\", \"ViewModel\", \"repository\", \"endpoint\", \"API\", \"schema\", \"interface\", \"class\".\n- Use plain English. Focus on what users or the business can do, what data moves, what decisions get made, and why it matters.\n- 1–3 sentences per description. Concrete. No filler.\n- Preserve the original keys exactly; only the description values change.\n\nOutput ONLY raw JSON with the same shape as the input — same keys, rewritten descriptions. No markdown, no code fences, no preamble.`;\n\ntype Rewritten = {\n features: Record<string, string>;\n flows: Record<string, string>;\n};\n\ninterface RewriteInput {\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nfunction buildPrompt(input: RewriteInput): string {\n return `Rewrite the descriptions below for a product audience. Return ONLY a JSON object of the form {\"features\": {\"name\": \"rewritten description\", ...}, \"flows\": {...}}.\\n\\n${JSON.stringify(input, null, 2)}`;\n}\n\nfunction parseRewriteResponse(raw: string): Rewritten {\n let cleaned = raw.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n try {\n const parsed = JSON.parse(cleaned);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (match) {\n try {\n const parsed = JSON.parse(match[0]);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n return { features: {}, flows: {} };\n }\n }\n return { features: {}, flows: {} };\n }\n}\n\nexport interface RewriteResult {\n features: Record<string, string>;\n flows: Record<string, string>;\n /** Updated prose cache to persist into the sync state. */\n cache: RewriteCache;\n}\n\nexport interface RewriteContext {\n /** Prose cache from the previous sync; used to skip unchanged entries. */\n previousCache?: RewriteCache;\n /** LLM caller; injectable for tests. Defaults to the configured provider. */\n llm?: typeof callLLM;\n}\n\n/** Pick a subset of a record by key. */\nfunction pick<T>(source: Record<string, T>, keys: string[]): Record<string, T> {\n const out: Record<string, T> = {};\n for (const k of keys) out[k] = source[k];\n return out;\n}\n\n/**\n * Rewrite engineering descriptions into product-readable prose, incrementally.\n *\n * Entries whose source description is unchanged since the last sync (matched by\n * content hash) reuse their cached prose verbatim — no LLM call. Only new or\n * changed entries are sent to the model, batched into a single request. When\n * nothing changed, the LLM is not invoked at all.\n */\nexport async function rewriteForProduct(\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext = {}\n): Promise<RewriteResult> {\n const featureHashes = hashEntries(snapshot.features);\n const flowHashes = hashEntries(snapshot.flows);\n\n const missFeatures = missingNames(\n snapshot.features,\n featureHashes,\n ctx.previousCache?.features\n );\n const missFlows = missingNames(\n snapshot.flows,\n flowHashes,\n ctx.previousCache?.flows\n );\n\n let parsed: Rewritten = { features: {}, flows: {} };\n if (missFeatures.length > 0 || missFlows.length > 0) {\n const input: RewriteInput = {\n features: pick(snapshot.features, missFeatures),\n flows: pick(snapshot.flows, missFlows),\n };\n const prompt = buildPrompt(input);\n const llm = ctx.llm ?? callLLM;\n const result = await llm(config, prompt, PM_REWRITE_SYSTEM_PROMPT);\n const text =\n typeof result === \"string\"\n ? result\n : result.type === \"response\"\n ? result.text\n : \"\";\n // Empty text means no API/CLI is available — leave `parsed` empty so every\n // miss falls back to its engineering description (cached as fallback).\n if (text) parsed = parseRewriteResponse(text);\n }\n\n const features = resolve(\n snapshot.features,\n featureHashes,\n parsed.features,\n ctx.previousCache?.features\n );\n const flows = resolve(\n snapshot.flows,\n flowHashes,\n parsed.flows,\n ctx.previousCache?.flows\n );\n\n return {\n features: features.descriptions,\n flows: flows.descriptions,\n cache: { features: features.cache, flows: flows.cache },\n };\n}\n\nfunction hashEntries(\n entries: Record<string, { description: string }>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, entry] of Object.entries(entries)) {\n out[name] = hashDescription(entry.description);\n }\n return out;\n}\n\n/** A cache entry is a hit only if the source hash matches and it isn't a fallback. */\nfunction isHit(\n prev: RewriteCacheEntry | undefined,\n hash: string\n): prev is RewriteCacheEntry {\n return !!prev && prev.sourceHash === hash && !prev.fallback;\n}\n\nfunction missingNames(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): string[] {\n return Object.keys(entries).filter(\n (name) => !isHit(prevCache?.[name], hashes[name])\n );\n}\n\n/**\n * Build the final prose map + next cache for one collection (features or flows):\n * reuse cached prose on a hit, take fresh model prose on a miss, or fall back to\n * the engineering description (marked `fallback`) when the model omitted it.\n */\nfunction resolve(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n rewritten: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): { descriptions: Record<string, string>; cache: Record<string, RewriteCacheEntry> } {\n const descriptions: Record<string, string> = {};\n const cache: Record<string, RewriteCacheEntry> = {};\n\n for (const [name, entry] of Object.entries(entries)) {\n const hash = hashes[name];\n const prev = prevCache?.[name];\n\n if (isHit(prev, hash)) {\n descriptions[name] = prev.product;\n cache[name] = { sourceHash: hash, product: prev.product };\n continue;\n }\n\n const fresh = rewritten[name];\n if (typeof fresh === \"string\" && fresh.trim().length > 0) {\n descriptions[name] = fresh;\n cache[name] = { sourceHash: hash, product: fresh };\n } else {\n // No usable model output — keep the engineering description and mark it a\n // fallback so a later successful run re-attempts it.\n descriptions[name] = entry.description;\n cache[name] = { sourceHash: hash, product: entry.description, fallback: true };\n }\n }\n\n return { descriptions, cache };\n}\n","import { loadSnapshot } from \"../snapshot/snapshot.js\";\nimport type { MasonConfig, ConfluenceConfig } from \"../llm/config.js\";\nimport { createConfluenceClient, type ConfluenceClient } from \"./client.js\";\nimport {\n renderFeaturePage,\n renderIndexPage,\n renderChangelogPage,\n renderChangelogSection,\n flowsForFeature,\n featurePageTitle,\n} from \"./renderer.js\";\nimport {\n computeDiff,\n isMeaningfulDiff,\n loadSyncState,\n saveSyncState,\n snapshotMinimal,\n hashDescription,\n type SyncState,\n} from \"./diff.js\";\nimport {\n rewriteForProduct,\n type RewriteResult,\n type RewriteContext,\n} from \"./rewrite.js\";\nimport type { FeatureEntry, Snapshot } from \"../snapshot/snapshot.js\";\n\nexport interface SyncOptions {\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n}\n\nexport interface SyncSummary {\n created: string[];\n updated: string[];\n unchanged: string[];\n indexPageId: string;\n changelogPageId: string;\n hadChanges: boolean;\n}\n\nexport interface SyncDeps {\n client: ConfluenceClient;\n rewrite: (\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext\n ) => Promise<RewriteResult>;\n}\n\nconst DEFAULT_INDEX_TITLE = \"Mason — System Map\";\nconst DEFAULT_CHANGELOG_TITLE = \"Mason — Changelog\";\nconst DEFAULT_FEATURE_PREFIX = \"Feature: \";\n\nexport async function exportToConfluence(\n rootDir: string,\n config: MasonConfig,\n options: SyncOptions = {},\n deps?: Partial<SyncDeps>\n): Promise<SyncSummary> {\n const confluence = config.confluence;\n if (!confluence) {\n throw new Error(\n \"No Confluence credentials configured. Ask your assistant to call mason_set_confluence first.\"\n );\n }\n\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n throw new Error(\n \"No snapshot found. Build the concept map first (ask your assistant to run mason_init and follow the playbook).\"\n );\n }\n\n const client = deps?.client ?? createConfluenceClient(confluence);\n const rewrite = deps?.rewrite ?? rewriteForProduct;\n\n // Only user-facing capabilities are published to the wiki. Infrastructure\n // features (DI wiring, config, logging, provider plumbing) stay in the AI\n // concept map but never become PM-facing pages. Filter once here; everything\n // downstream — rewrite, index, feature pages, changelog diff, persisted\n // state — operates on this published subset. Missing type defaults to\n // \"capability\" (see normalizeFeatureType), so older snapshots publish as before.\n const publishedFeatures: Record<string, FeatureEntry> = {};\n for (const [name, entry] of Object.entries(snapshot.features)) {\n if (entry.type !== \"infrastructure\") publishedFeatures[name] = entry;\n }\n const publishSnapshot: Snapshot = { ...snapshot, features: publishedFeatures };\n\n const indexTitle = options.indexPageTitle ?? DEFAULT_INDEX_TITLE;\n const changelogTitle = options.changelogPageTitle ?? DEFAULT_CHANGELOG_TITLE;\n const featurePrefix = options.featurePagePrefix ?? DEFAULT_FEATURE_PREFIX;\n\n const spaceId = await client.resolveSpaceId(confluence.spaceKey);\n // Wall-clock time is used ONLY for the append-only changelog heading. Page\n // bodies carry no timestamp/hash, so a page is re-published only when its own\n // content (description/flows) changes — not on every unrelated commit.\n const syncedAt = new Date().toISOString();\n const previousState = await loadSyncState(rootDir);\n const previousHashes = previousState?.pageHashes ?? {};\n const nextHashes: Record<string, string> = {};\n\n const productLanguage = await rewrite(publishSnapshot, config, {\n previousCache: previousState?.rewriteCache,\n });\n\n // 1. Upsert index page (so feature pages can hang under it)\n const indexBody = renderIndexPage({\n featureTitles: Object.keys(publishSnapshot.features),\n featurePrefix,\n });\n\n const indexPage = await upsertPage({\n client,\n spaceId,\n title: indexTitle,\n parentId: confluence.parentPageId,\n renderedBody: indexBody,\n previousHash: previousHashes[indexTitle],\n });\n nextHashes[indexTitle] = indexPage.hash;\n\n // 2. Upsert each feature page under the index\n const created: string[] = [];\n const updated: string[] = [];\n const unchanged: string[] = [];\n const featurePageIds: Record<string, string> = {};\n\n for (const [name, entry] of Object.entries(publishSnapshot.features)) {\n const title = featurePageTitle(featurePrefix, name);\n const productDescription =\n productLanguage.features[name] ?? entry.description;\n const relatedFlows = flowsForFeature(entry.files, publishSnapshot.flows).map(\n (f) => ({\n name: f.name,\n description: productLanguage.flows[f.name] ?? f.description,\n })\n );\n\n const rendered = renderFeaturePage({\n name,\n productDescription,\n flowDescriptions: relatedFlows,\n indexPageTitle: indexTitle,\n });\n\n const result = await upsertPage({\n client,\n spaceId,\n title,\n parentId: indexPage.id,\n renderedBody: rendered.body,\n previousHash: previousHashes[title],\n });\n nextHashes[title] = result.hash;\n\n featurePageIds[name] = result.id;\n if (result.outcome === \"created\") created.push(title);\n else if (result.outcome === \"updated\") updated.push(title);\n else unchanged.push(title);\n }\n\n // 3. Diff + changelog page\n const diff = computeDiff(previousState, publishSnapshot, syncedAt);\n const hadChanges = previousState === null || isMeaningfulDiff(diff);\n\n const previousSections = previousState?.changelogSections ?? [];\n let newSections = previousSections;\n if (hadChanges) {\n const section = renderChangelogSection(diff);\n newSections = [section, ...previousSections].slice(0, 50);\n }\n\n const changelogBody = renderChangelogPage(newSections);\n const changelogPage = await upsertPage({\n client,\n spaceId,\n title: changelogTitle,\n parentId: indexPage.id,\n renderedBody: changelogBody,\n previousHash: previousHashes[changelogTitle],\n });\n nextHashes[changelogTitle] = changelogPage.hash;\n\n // 4. Persist sync state\n const nextState: SyncState = {\n version: 2,\n syncedAt,\n pageIds: {\n index: indexPage.id,\n changelog: changelogPage.id,\n features: featurePageIds,\n },\n lastSnapshot: snapshotMinimal(publishSnapshot),\n changelogSections: newSections,\n rewriteCache: productLanguage.cache,\n pageHashes: nextHashes,\n };\n await saveSyncState(rootDir, nextState);\n\n return {\n created,\n updated,\n unchanged,\n indexPageId: indexPage.id,\n changelogPageId: changelogPage.id,\n hadChanges,\n };\n}\n\ninterface UpsertArgs {\n client: ConfluenceClient;\n spaceId: string;\n title: string;\n parentId?: string;\n renderedBody: string;\n /** Hash of the body we published for this page last sync, if any. */\n previousHash?: string;\n}\n\ninterface UpsertResult {\n id: string;\n outcome: \"created\" | \"updated\" | \"unchanged\";\n /** Hash of the body published this sync — persist for next-run comparison. */\n hash: string;\n}\n\nasync function upsertPage(args: UpsertArgs): Promise<UpsertResult> {\n const hash = hashDescription(args.renderedBody);\n const existing = await args.client.findPageByTitle(args.spaceId, args.title);\n\n if (!existing) {\n const page = await args.client.createPage({\n spaceId: args.spaceId,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n });\n return { id: page.id, outcome: \"created\", hash };\n }\n\n // Confluence re-serializes stored bodies (strips comments, re-encodes\n // entities, injects macro ids), so we can't compare against existing.body.\n // Compare our render hash to the hash we stored last sync instead. When it\n // matches, the page is already current — skip the write entirely.\n if (args.previousHash === hash) {\n return { id: existing.id, outcome: \"unchanged\", hash };\n }\n\n // Mason owns the whole page body: overwrite it wholesale.\n const updated = await args.client.updatePage({\n id: existing.id,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n version: existing.version,\n });\n return { id: updated.id, outcome: \"updated\", hash };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { inactiveSetupMessage } from \"../setup/launcher.js\";\nimport { attributionSchema } from \"../decisions/provenance.js\";\nimport { advisoryReviewRequest } from \"../audit/advisory-review.js\";\nimport { decisionTitleSchema, decisionBodySchema, BODY_RECOMMENDED_CHARS, BODY_MAX_CHARS, TITLE_MAX_CHARS } from \"../decisions/decisions.js\";\nimport {\n analyzeProject,\n checkDrift,\n exportToConfluenceTool,\n fullAnalysis,\n generateSnapshotBatch,\n getCodeSamples,\n getContext,\n getImpact,\n getSnapshot,\n saveDecision,\n reviewDecision,\n saveVerification,\n verifySnapshot,\n masonCompleteInit,\n masonInit,\n masonRepair,\n masonReviewAdvisory,\n masonAutomation,\n masonSetConfluence,\n reduceSnapshot,\n saveSnapshotData,\n saveSnapshotPartial,\n} from \"./tools.js\";\n\ndeclare const PKG_VERSION: string;\n\nexport function createMcpServer(): McpServer {\n const setupNotice = inactiveSetupMessage();\n const server = new McpServer(\n {\n name: \"mason\",\n version: PKG_VERSION,\n },\n {\n instructions: (setupNotice ? setupNotice + \"\\n\\n\" : \"\") +\n \"Mason retrieves recorded decisions, file impact, and optional feature/flow maps. Use get_context with the task and known files, and get_impact before editing. Save learned rationale and constraints with save_decision; review and commit the local records through the project workflow. These tools work without initialization or a concept map. Consult trust and diagnostics: changed or unknown freshness needs source inspection, stale or unknown map verification needs a fresh review, recorded failed verdicts need correction, and proposals are suggestions and legacy records are unreviewed. Accepted decisions are recorded team constraints, still subject to freshness checks. Use review_decision to prepare code evidence and record only authorized acceptance, reaffirmation, or retirement. Never invent a reviewer or treat these recorded identities as authenticated approval. mason_init returns documentation audit and committed-diff review findings with a quickstart guide. Use mode: \\\"map\\\" only when a full architecture map is requested. A missing map is not a setup failure; use decisions and source evidence. get_snapshot provides architecture navigation when a map is available. The mason-audit and mason-review CLIs also work without setup.\",\n }\n );\n\n server.tool(\n \"mason_init\",\n \"Inspect this project now: returns documentation audit findings, committed-diff review findings, decision/map status, and a quickstart playbook. Quickstart and map modes are read-only and deterministic. Explicit mode: setup configures MCP, instructions and lifecycle hooks to use mason on PATH while retaining original audit evidence; use it only when the user requests setup. Optional host selects codex or claude. Optional base selects the review comparison; evidence imports CI manifests with check outcomes, commit freshness, and links to changed files and accepted decisions. mode: map returns the full Map-Reduce build workflow. Repeat calls refresh findings even after setup.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n mode: z.enum([\"quickstart\", \"map\", \"setup\"]).optional().default(\"quickstart\")\n .describe(\"Quickstart inspects without edits; map requests an architecture build; setup installs the shared onboarding flow.\"),\n host: z.enum([\"codex\", \"claude\"]).optional().describe(\"Assistant to configure in setup mode; inferred only when unambiguous.\"),\n base: z.string().optional().describe(\"Git ref for committed-diff review. Defaults to the first available main branch ref.\"),\n evidence: z.array(z.string()).max(10).optional().describe(\"Repository-local CI evidence manifests to include in the review. Imports Vitest JSON, SARIF, and native-validator mason-check-json results without executing check commands.\"),\n },\n async ({ dir, mode, host, base, evidence }) => {\n const result = await masonInit(dir, { mode, host, base, evidence });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_automation\",\n \"Inspect installed automation and observed host events, or resume/check retained documentation repair evidence across sessions. status is read-only; check saves local baselines and verification reports without editing source or approving advisories. Returns concise results with a full report path. Works without a map.\",\n {\n dir: z.string().describe(\"Absolute path to the project directory\"),\n action: z.enum([\"status\", \"check\"]).describe(\"Inspect configuration and receipts, or capture/resume and verify original audit evidence.\"),\n },\n async ({ dir, action }) => ({ content: [{ type: \"text\", text: await masonAutomation(dir, action) }] })\n );\n\n server.tool(\n \"mason_repair\",\n \"Track documentation repairs against original audit evidence. prepare saves a local baseline and returns a scoped work order; verify reads that baseline and reports resolved, unresolved, review-required, unverified, and new findings. Suppressed advisories remain unresolved. Does not edit documentation or approve decisions. No map required.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n action: z.enum([\"prepare\", \"verify\"]),\n baselinePath: z.string().optional().describe(\"Original baseline path returned by prepare; required for verify.\"),\n checks: z.array(z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]))\n .min(1).optional().describe(\"Optional audit check subset for prepare. Verification always uses the original checks.\"),\n },\n async ({ dir, action, baselinePath, checks }) => {\n const result = await masonRepair(dir, { action, baselinePath, checks });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_advisory\",\n \"Prepare an assessment of an original repair advisory and its exact repository scope, then record authorized addressed, inapplicable or deferred outcomes with reviewToken, reviewer and note. Relevant changes reopen reviews; unrelated commits preserve them. Records belong in Git. Decision findings route to review_decision; this tool never approves decisions. Recorded identities are assertions, not authenticated approvals.\",\n { dir: z.string().describe(\"Absolute path to the project root\"), ...advisoryReviewRequest.shape },\n async ({ dir, ...request }) => ({ content: [{ type: \"text\", text: await masonReviewAdvisory(dir, request) }] })\n );\n\n server.tool(\n \"mason_complete_init\",\n \"Record assistant instruction setup locally in ignored .mason/local/project.json, with feature settings in shared .mason/config.json. Other tools work without this marker. Repeated calls preserve the original setup time and existing settings; pass confluenceConfigured only to change that setting.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n confluenceConfigured: z\n .boolean()\n .optional()\n .describe(\"Set the Confluence setup status; omit to preserve the existing value\"),\n },\n async ({ dir, confluenceConfigured }) => {\n const result = await masonCompleteInit(dir, { confluenceConfigured });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_set_confluence\",\n \"Configure Confluence credentials. Two-step flow: (1) call without `spaceKey` to validate the credentials and receive a list of available spaces — relay them to the user. (2) call again with the same `baseUrl`/`email`/`apiToken` plus the chosen `spaceKey` to persist. Credentials are stored in `~/.mason/config.json`. Warn the user that the API token will be visible in chat history before they paste it.\",\n {\n baseUrl: z\n .string()\n .describe(\"Confluence base URL. Accepts `acme`, `acme.atlassian.net`, or `https://acme.atlassian.net` (normalized automatically).\"),\n email: z.string().describe(\"User's Atlassian account email\"),\n apiToken: z\n .string()\n .describe(\"API token from id.atlassian.com/manage-profile/security/api-tokens\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Confluence space key. Omit on the first call to list available spaces.\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Optional parent page ID under which Mason's index page is created\"),\n },\n async ({ baseUrl, email, apiToken, spaceKey, parentPageId }) => {\n const result = await masonSetConfluence({\n baseUrl,\n email,\n apiToken,\n spaceKey,\n parentPageId,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"full_analysis\",\n \"One-shot orientation for a project WITHOUT a concept map (get_snapshot returned exists:false). Returns git history stats, project structure with file counts, curated code sample previews (~60 lines each), and test-to-source mapping. On a mapped project, prefer get_snapshot — it is cheaper and answers feature/architecture questions directly.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await fullAnalysis(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"analyze_project\",\n \"Run git history analysis on a codebase. Returns commit convention patterns, stale directories, and frequently changed files. These are aggregate stats across hundreds of commits that would be expensive to compute manually.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await analyzeProject(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_code_samples\",\n \"Get previews (first ~60 lines) of representative source files from the codebase. Includes entry points, config files, hot files (frequently changed), test examples, and one file per directory for breadth. Read files natively for full content.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n count: z\n .number()\n .optional()\n .default(15)\n .describe(\"Maximum number of files to sample (default: 15)\"),\n },\n async ({ dir, count }) => {\n const result = await getCodeSamples(dir, count);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_snapshot\",\n \"Return the optional feature-to-file architecture map with drift and trust evidence. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. If no map exists, returns exists:false plus project structure, Git signals, and test pairs. Decision capture, get_context, and get_impact still work. No initialization required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await getSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_context\",\n \"Assemble task context: matching decisions with rationale, approval, owner, sources, last review, and freshness, plus related tests, file impact, and any available map entries. Map verification is rechecked against sampled source contents; stale or unknown verification requires a fresh review, and recordedVerdict preserves the historical verdict. Proposals are suggestions; legacy records are unreviewed; accepted decisions are constraints subject to freshness. No initialization or map required. Pass task and optional files. map.status and diagnostics preserve missing or invalid knowledge. Impact covers up to three unique files, expanding directory anchors.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n task: z\n .string()\n .describe(\"The task, bug, or change request in natural language — e.g. 'add rate limiting to the API client' or a ticket description\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Optional file paths already known to be involved (e.g. from a diff or stack trace). Entries containing them are boosted above pure text matches.\"),\n },\n async ({ dir, task, files }) => {\n const result = await getContext(dir, task, files);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(dir, \"context\");\n if (warning) return { content: [{ type: \"text\", text: result }, { type: \"text\", text: warning }] };\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"generate_snapshot_batch\",\n \"Map step of the concept-map build. Returns one batch of source files (skeletons of every file in the batch plus a few deeper-read bodies for grounding), along with a system prompt instructing you to derive features and flows for ONLY this batch. Call repeatedly with the returned `nextOffset` until it is null, calling `save_partial_snapshot` between each call. Use product-natural feature names so partials merge cleanly in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n offset: z\n .number()\n .int()\n .optional()\n .describe(\"0-indexed file offset to start the batch at. Omit on the first call; pass the `nextOffset` from the previous response for subsequent calls.\"),\n batchSize: z\n .number()\n .int()\n .optional()\n .describe(\"Files per batch. Defaults to 50.\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Scope the batch walk to this explicit file list — e.g. the drift set from mason_check_drift (changedFiles + unmappedFiles). Pass the SAME list on every batch call of one refresh run. Triggers refresh mode: reduce_snapshot will merge the partials into the existing map instead of rebuilding it.\"),\n },\n async ({ dir, offset, batchSize, files }) => {\n const result = await generateSnapshotBatch(dir, offset, batchSize, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_partial_snapshot\",\n \"Persist the partial concept map you derived for one batch. Call this once per batch, with the `batchId` from the `generate_snapshot_batch` response. Partials accumulate in `.mason/partial-snapshots/` and are merged in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n batchId: z\n .string()\n .describe(\"The `batchId` returned by `generate_snapshot_batch`.\"),\n offset: z\n .number()\n .int()\n .describe(\"The `offset` returned by `generate_snapshot_batch`. Used to order partials in the reduce step.\"),\n features: z\n .record(\n z.object({\n description: z.string(),\n files: z.array(z.string()),\n tests: z.array(z.string()).optional(),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n '\"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, config, logging, adapters). Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Partial features for this batch only — files outside the batch will be added by other partials.\"),\n flows: z\n .record(\n z.object({\n description: z.string(),\n chain: z.array(z.string()),\n })\n )\n .describe(\"Partial flows whose entire chain is in this batch. Cross-batch flows are reconstructed in reduce.\"),\n },\n async ({ dir, batchId, offset, features, flows }) => {\n const result = await saveSnapshotPartial(dir, batchId, offset, features, flows);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"reduce_snapshot\",\n \"Reduce step of the concept-map build. Returns every partial snapshot plus a system prompt asking you to merge them into one coherent project-wide map. Resolve platform variants into single product features, dedupe near-duplicates, and ensure no file is dropped. After producing the unified map, call `save_snapshot` to persist it (this also clears the partials).\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await reduceSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_snapshot\",\n \"Save a concept-to-files map as a persistent project snapshot. Maps feature names and data flows to the files that implement them. Persists across conversations — future sessions can call get_snapshot to instantly find relevant files. No API key needed — you are the LLM generating the map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n features: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the feature\"),\n files: z.array(z.string()).describe(\"File paths that implement this feature\"),\n tests: z.array(z.string()).optional().describe(\"Test file paths for this feature\"),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n 'Classification: \"capability\" for user-facing functionality, \"infrastructure\" for internal plumbing with no end user (DI/service wiring, config, logging, adapters). Capabilities are published to Confluence; infrastructure stays in the AI concept map only. Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Map of feature names to their implementing files\"),\n flows: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the flow\"),\n chain: z.array(z.string()).describe(\"Ordered list of file paths showing data/call flow\"),\n })\n )\n .describe(\"Map of flow names to ordered file chains\"),\n removeFeatures: z\n .array(z.string())\n .optional()\n .describe(\"Feature names to delete from the existing map — for features that were renamed or no longer exist. Applied before merging; only meaningful on incremental saves.\"),\n removeFlows: z\n .array(z.string())\n .optional()\n .describe(\"Flow names to delete from the existing map. Applied before merging; only meaningful on incremental saves.\"),\n },\n async ({ dir, features, flows, removeFeatures, removeFlows }) => {\n const result = await saveSnapshotData(\n dir,\n features,\n flows,\n removeFeatures ?? [],\n removeFlows ?? []\n );\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_decision\",\n \"Capture or revise a decision proposal with rationale, anchors, optional owner, sources, and a known actor. Compare matching get_context records and pending proposals before saving. When new evidence changes the same lesson's assumptions, scope, or recommended action, pass its existing id, including for accepted records. Preserve supported rationale and sources and replace obsolete instructions. Create a new record for a genuinely distinct lesson; skip unchanged restatements. No setup or map required. Writes a local record and preserves content history. Changes create a pending proposal while the last accepted revision remains operative; unchanged content does not re-verify or refresh it. Use review_decision for authorized acceptance or reaffirmation. A proposal cannot supersede a record with an operative accepted revision; review its replacement and retire the original separately.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n title: decisionTitleSchema\n .describe(`Short, specific headline (max ${TITLE_MAX_CHARS} characters). Generates a stable id on creation; revising the title keeps the existing id.`),\n body: decisionBodySchema\n .describe(`The knowledge itself: what was tried/decided, why, and what to avoid. Must contain information NOT derivable by reading the code. Aim for ${BODY_RECOMMENDED_CHARS} characters or fewer; up to ${BODY_MAX_CHARS} is accepted with a warning above the target. Matching context and hooks include the full body. Preserve exceptions; use sources for supporting references.`),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Repo-relative files or directory prefixes this applies to. Matching is shared by retrieval, hooks, review, and drift checking; changes flag the decision for re-verification.\"),\n id: z\n .string()\n .optional()\n .describe(\"Pass the matching record's existing id when evidence changes that lesson's assumptions, scope, or recommended action, including for accepted records. Changed content becomes a proposal while the accepted version remains operative; unchanged content leaves review and freshness untouched.\"),\n supersedes: z\n .string()\n .optional()\n .describe(\"Id of an unreviewed record or proposal with no accepted revision to replace. Operative accepted decisions require separate review and retirement.\"),\n owner: attributionSchema.shape.owner.describe(\"Responsible person or team, when known. Null clears it. Required for acceptance.\"),\n sources: attributionSchema.shape.sources.describe(\"Known PR, issue, incident, discussion, or document references. Omit to preserve; [] clears. At least one is required for acceptance.\"),\n actor: attributionSchema.shape.actor.describe(\"Known person or agent recording this revision. Omit if unknown; do not infer from Git identity.\"),\n force: z\n .boolean()\n .optional()\n .describe(\"Save even when a near-duplicate was detected\"),\n },\n async ({ dir, title, body, category, files, id, supersedes, force, owner, sources, actor }) => {\n const result = await saveDecision(dir, {\n title,\n body,\n category,\n files,\n id,\n supersedes,\n force,\n owner,\n sources,\n actor,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_decision\",\n \"Prepare a decision review: returns the full record and history, any operative accepted revision, provenance, changes and previews for both sets of anchors, and a reviewToken. Then record accept, reaffirm, or retire with that token, the authorized reviewer, and a reason. Acceptance replaces the operative revision; retirement withdraws the entire record including its proposal. Acceptance requires owner, source, readable Git HEAD, and committed anchor changes. Changed records or code invalidate the token. Identities and approvals are recorded assertions for normal PR review, not authenticated proof.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/).describe(\"Decision id from get_context or save_decision\"),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).optional().default(\"prepare\")\n .describe(\"Prepare is read-only. Other actions record an explicitly authorized review.\"),\n reviewer: z.string().trim().min(1).max(200).optional().describe(\"Identity of the actual reviewer; required for a verdict. Never invent one.\"),\n note: z.string().trim().min(1).max(1500).optional().describe(\"Review rationale; required for a verdict. Cite evidence for the decision.\"),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional().describe(\"Token from the prepared review; rejects stale record or code revisions\"),\n },\n async ({ dir, ...input }) => {\n const result = await reviewDecision(dir, input);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_check_drift\",\n \"Check how far the concept map has drifted from HEAD. Deterministic (git + filesystem, no LLM). Returns which features/flows are stale and the changed files behind them, new source files not yet mapped, ghost files (mapped but deleted), renames, and a `recommendation`: `up-to-date` (nothing to do), `incremental` (update just the stale entries via save_snapshot), or `full-rebuild` (re-run the Map-Reduce build). Call this before trusting the map in a long session, or periodically to keep the map and any synced wikis fresh.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await checkDrift(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"verify_snapshot\",\n \"Spot-check the concept map's CORRECTNESS (drift checks freshness; this checks entries were right to begin with). Returns a sample of entries — always the never-verified and least-recently-verified first — with skeletons of their claimed files, for you to judge whether the files actually implement what the entry claims. Report verdicts back via save_verification with each entry’s kind and reviewToken. Tokens bind the entry and bounded source evidence; changed evidence requires a fresh review. Run periodically, or after an automated refresh wrote entries no human reviewed.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n sample: z\n .number()\n .int()\n .optional()\n .describe(\"Entries to sample (default 5)\"),\n },\n async ({ dir, sample }) => {\n const result = await verifySnapshot(dir, sample);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"save_verification\",\n \"Record verify_snapshot verdicts using each entry’s kind and reviewToken. Missing tokens request a fresh review; changed or deleted entries return conflicts without being stamped. Entries judged ok are stamped verifiedAt; failures are flagged verificationFailed with your note and surface in get_context, get_snapshot, and mason_check_drift until corrected. Verdict notes are required for failures.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n verdicts: z\n .record(\n z.object({\n kind: z.enum([\"feature\", \"flow\"]).optional().describe(\"Entry kind returned by verify_snapshot; required to record a verdict\"),\n reviewToken: z.string().optional().describe(\"Copy the reviewToken from verify_snapshot after inspecting its evidence; required to record a verdict\"),\n ok: z.boolean(),\n note: z\n .string()\n .optional()\n .describe(\"One line on what's wrong — required when ok is false\"),\n })\n )\n .describe(\"Entry name → verdict, exactly as returned by verify_snapshot\"),\n },\n async ({ dir, verdicts }) => {\n const result = await saveVerification(dir, verdicts);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"get_impact\",\n \"Trace historical co-change partners, related tests, and references with evidence: resolved imports, explicit paths, or uncertain name candidates. Candidates are not proven dependencies. Deterministic and read-only; no initialization or concept map required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n files: z\n .array(z.string())\n .describe(\"File paths or names to analyze (e.g., ['WeatherRepository.kt'] or ['src/services/auth.ts'])\"),\n },\n async ({ dir, files }) => {\n const result = await getImpact(dir, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"export_to_confluence\",\n \"Sync the project's concept map to Confluence as product-readable wiki pages: an index page, one page per feature (PM-language descriptions, no file paths), and a changelog page. Mason replaces managed page bodies; manual edits to those bodies are overwritten. Requires `mason_set_confluence` to have been called first.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Override the configured space key\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Override the configured parent page ID\"),\n indexPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the index page (default: 'Mason — System Map')\"),\n changelogPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the changelog page (default: 'Mason — Changelog')\"),\n featurePagePrefix: z\n .string()\n .optional()\n .describe(\"Prefix for each feature page title (default: 'Feature: ')\"),\n },\n async ({ dir, spaceKey, parentPageId, indexPageTitle, changelogPageTitle, featurePagePrefix }) => {\n const result = await exportToConfluenceTool(dir, {\n spaceKey,\n parentPageId,\n indexPageTitle,\n changelogPageTitle,\n featurePagePrefix,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(onClose?: () => void): Promise<void> {\n const server = createMcpServer();\n if (onClose) server.server.onclose = onClose;\n const transport = new StdioServerTransport();\n await server.connect(transport);\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 { prepareRepair, verifyRepair } from \"../audit/repair.js\";\nimport { reviewAdvisory, type AdvisoryReviewInput } from \"../audit/advisory-review.js\";\nimport { formatFixPrompt } from \"../audit/cli.js\";\nimport type { CheckName } from \"../audit/types.js\";\n\nconst exec = promisify(execFile);\nimport { runAll } from \"../analyzers/index.js\";\nimport { isGitRepo } from \"../utils/git.js\";\nimport { sampleFiles } from \"./sampler.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { trustHint, type TrustState } from \"../context/trust.js\";\nimport { compactDecisionKnowledge, effectiveDecision, decisionTrust, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport type { UpsertDecisionInput } from \"../decisions/decisions.js\";\nimport { reviewDecision as runDecisionReview, type ReviewDecisionInput } from \"../decisions/review.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport {\n loadSnapshot,\n updateSnapshot,\n getCurrentGitHash,\n prepareSnapshotBatch,\n normalizeFeatureType,\n DEFAULT_BATCH_SIZE,\n type FeatureType,\n} from \"../snapshot/snapshot.js\";\nimport { createSnapshotTrustReader, readSnapshotTrustIndex } from \"../snapshot/trust.js\";\nimport { computeDrift } from \"../drift/drift.js\";\nimport { prepareSnapshotReview, snapshotEntryContent, type SnapshotVerdict } from \"../snapshot/review.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\nimport {\n BATCH_SYSTEM_PROMPT,\n REDUCE_SYSTEM_PROMPT,\n REFRESH_REDUCE_SYSTEM_PROMPT,\n buildBatchPrompt,\n buildReducePrompt,\n buildRefreshReducePrompt,\n} from \"../snapshot/prompt.js\";\nimport {\n batchIdFor,\n clearAllPartials,\n clearScope,\n loadAllPartials,\n loadScope,\n savePartial,\n saveScope,\n} from \"../snapshot/partials.js\";\nimport type { Snapshot, FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\nimport type { AnalyzerContext } from \"../types.js\";\nimport {\n loadProjectMarker, loadProjectFeatures,\n saveProjectMarker,\n setupPlaybook,\n type ProjectMarker,\n type InitMode,\n} from \"./init.js\";\nimport { inspectOnboarding } from \"./onboarding.js\";\n\nasync function buildContext(dir: string): Promise<AnalyzerContext> {\n return {\n rootDir: dir,\n gitAvailable: await isGitRepo(dir),\n };\n}\n\nexport async function analyzeProject(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const context = await buildContext(rootDir);\n const results = await runAll(context);\n\n // Lightweight project snapshot — pure file existence checks, no parsing\n const projectSnapshot = await detectProjectSnapshot(rootDir);\n\n const output = {\n project: projectSnapshot,\n analyzers: results.map((r) => ({\n name: r.analyzer,\n durationMs: r.durationMs,\n findings: r.findings.map((f) => ({\n category: f.category,\n confidence: f.confidence,\n summary: f.summary,\n evidence: f.evidence,\n suggestedRule: f.ruleCandidate,\n })),\n gaps: r.gaps.map((g) => ({\n question: g.question,\n context: g.context,\n })),\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nasync function detectProjectSnapshot(rootDir: string): Promise<Record<string, unknown>> {\n // Build config files present (what exists, not what's in them)\n const access = await createFileAccess(rootDir);\n const buildFiles = [\n \"package.json\", \"tsconfig.json\",\n \"build.gradle.kts\", \"build.gradle\", \"settings.gradle.kts\", \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \"Cargo.toml\", \"go.mod\", \"go.sum\",\n \"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\",\n \"Gemfile\", \"Package.swift\",\n \"Makefile\", \"CMakeLists.txt\",\n \"Dockerfile\", \"docker-compose.yml\", \"docker-compose.yaml\",\n \".github/workflows\", \".gitlab-ci.yml\", \"Jenkinsfile\",\n ];\n\n const present: string[] = [];\n for (const file of buildFiles) {\n try {\n await fs.access(path.join(rootDir, file));\n present.push(file);\n } catch {\n // Not found\n }\n }\n\n // Test directories and file counts\n const testDirs = [\n \"test\", \"tests\", \"__tests__\", \"spec\",\n \"src/test\", \"src/tests\",\n \"**/src/test\", \"**/src/androidTest\", \"**/src/iosTest\",\n ];\n const testInfo: Record<string, number> = {};\n for (const pattern of testDirs) {\n const files = await access.list(`${pattern}/**/*`);\n if (files.length > 0) {\n testInfo[pattern] = files.length;\n }\n }\n\n // Also count test files by naming convention\n const testFilePatterns = [\n { pattern: \"**/*.test.*\", label: \"*.test.*\" },\n { pattern: \"**/*.spec.*\", label: \"*.spec.*\" },\n { pattern: \"**/*Test.kt\", label: \"*Test.kt\" },\n { pattern: \"**/*Test.java\", label: \"*Test.java\" },\n { pattern: \"**/test_*.py\", label: \"test_*.py\" },\n { pattern: \"**/*_test.go\", label: \"*_test.go\" },\n { pattern: \"**/*Tests.swift\", label: \"*Tests.swift\" },\n { pattern: \"**/*_test.rs\", label: \"*_test.rs\" },\n ];\n for (const { pattern, label } of testFilePatterns) {\n const files = await access.list(pattern);\n if (files.length > 0) {\n testInfo[label] = files.length;\n }\n }\n\n // Source file counts by extension\n const sourceFiles = await access.list();\n const fileCounts: Record<string, number> = {};\n for (const file of sourceFiles) {\n const ext = path.extname(file).slice(1);\n fileCounts[ext] = (fileCounts[ext] ?? 0) + 1;\n }\n\n return {\n configFilesPresent: present,\n sourceFileCounts: fileCounts,\n totalSourceFiles: sourceFiles.length,\n testInfo: Object.keys(testInfo).length > 0 ? testInfo : undefined,\n };\n}\n\nexport async function getCodeSamples(\n dir: string,\n count: number = 15\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const samples = await sampleFiles(rootDir, count);\n\n const output = {\n note: \"These are previews (first ~60 lines). Read the file directly with your own tools to see it in full.\",\n files: samples.map((s) => ({\n path: s.path,\n reason: s.reason,\n totalLines: s.totalLines,\n sizeBytes: s.sizeBytes,\n preview: s.preview,\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nconst UNINIT_MAX_DIRECTORIES = 40;\nconst UNINIT_MAX_TEST_PAIRS = 30;\n\n/** Keep architecture requests useful when the optional map is absent. */\nasync function unmappedContextResponse(rootDir: string): Promise<string> {\n const [structureRaw, analyzerResults, testMap] = await Promise.all([\n getProjectStructure(rootDir),\n runAll(await buildContext(rootDir)).catch(() => []),\n import(\"../test-map.js\")\n .then((m) => m.buildTestMap(rootDir))\n .catch(() => null),\n ]);\n\n const structure = JSON.parse(structureRaw);\n structure.directories = (structure.directories ?? [])\n .sort(\n (a: { fileCount: number }, b: { fileCount: number }) =>\n b.fileCount - a.fileCount\n )\n .slice(0, UNINIT_MAX_DIRECTORIES);\n\n const gitSignals = analyzerResults.flatMap((r) =>\n r.findings.map((f) => ({\n category: f.category,\n summary: f.summary,\n evidence: f.evidence.slice(0, 5),\n }))\n );\n\n return JSON.stringify({\n exists: false,\n map: { status: \"missing\" },\n hint:\n `No Mason concept map exists here yet. Use the context below plus your own reads to answer now — ` +\n `get_context, save_decision, and get_impact work without a map. For an optional map, mason_init with mode: \"map\" provides the generate_snapshot_batch workflow.`,\n structure,\n gitSignals,\n testPairs: testMap?.paired?.slice(0, UNINIT_MAX_TEST_PAIRS) ?? [],\n });\n}\n\nexport async function getProjectStructure(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Get all files\n const allFiles = await (await createFileAccess(rootDir)).list(\"**/*\");\n\n // Build directory summary with file counts and extension breakdown\n const dirInfo = new Map<\n string,\n { fileCount: number; extensions: Map<string, number> }\n >();\n\n for (const file of allFiles) {\n const parts = file.split(\"/\");\n // Track up to 2 levels deep\n for (let depth = 1; depth <= Math.min(parts.length, 2); depth++) {\n const dirPath = parts.slice(0, depth).join(\"/\");\n if (!dirInfo.has(dirPath)) {\n dirInfo.set(dirPath, { fileCount: 0, extensions: new Map() });\n }\n const info = dirInfo.get(dirPath)!;\n info.fileCount++;\n const ext = path.extname(file).slice(1);\n if (ext) {\n info.extensions.set(ext, (info.extensions.get(ext) ?? 0) + 1);\n }\n }\n }\n\n // Format directories sorted by path\n const directories = [...dirInfo.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([dirPath, info]) => {\n const extensions: Record<string, number> = {};\n for (const [ext, count] of info.extensions) {\n extensions[ext] = count;\n }\n return { path: dirPath, fileCount: info.fileCount, extensions };\n });\n\n // Top-level files\n const topLevelFiles = allFiles.filter((f) => !f.includes(\"/\"));\n\n const output = {\n totalFiles: allFiles.length,\n topLevelFiles,\n directories,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nexport async function getTestMap(dir: string): Promise<string> {\n const { buildTestMap } = await import(\"../test-map.js\");\n const result = await buildTestMap(dir);\n return JSON.stringify(result, null, 2);\n}\n\nconst STALE_DIFF_PREVIEW_LINES = 60;\nconst STALE_DIFF_MAX_FILES = 25;\n\nasync function buildChangedFilePreviews(\n rootDir: string,\n changedFiles: string[]\n): Promise<Array<{ path: string; totalLines: number; preview: string }>> {\n const access = await createFileAccess(rootDir);\n const capped = changedFiles.slice(0, STALE_DIFF_MAX_FILES);\n const previews: Array<{ path: string; totalLines: number; preview: string }> = [];\n for (const filePath of capped) {\n const full = await access.read(filePath);\n if (!full) continue;\n const lines = full.content.split(\"\\n\");\n previews.push({\n path: full.path,\n totalLines: full.totalLines,\n preview: lines.slice(0, STALE_DIFF_PREVIEW_LINES).join(\"\\n\"),\n });\n }\n return previews;\n}\n\nexport async function getSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const snapshot = await loadSnapshot(rootDir);\n\n if (!snapshot) {\n return unmappedContextResponse(rootDir);\n }\n\n // Staleness is per entry, not just top-level — a partially refreshed map\n // can be pinned to HEAD while individual entries lag behind.\n const drift = await computeDrift(rootDir);\n const isStale = drift?.stale ?? false;\n\n // Return compact format: feature/flow names -> file lists only.\n // Descriptions and metadata stay in the full snapshot on disk.\n // Deduplicate files that appear in multiple features.\n const seenFiles = new Set<string>();\n const compactFeatures: Record<\n string,\n { files: string[]; tests?: string[]; type: FeatureType }\n > = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n const unique = feat.files.filter((f) => !seenFiles.has(f));\n if (unique.length === 0) continue; // Skip fully duplicate features\n for (const f of unique) seenFiles.add(f);\n const entry: { files: string[]; tests?: string[]; type: FeatureType } = {\n files: unique,\n type: normalizeFeatureType(feat.type),\n };\n if (feat.tests && feat.tests.length > 0) {\n entry.tests = feat.tests;\n }\n compactFeatures[name] = entry;\n }\n\n const compactFlows: Record<string, string[]> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n compactFlows[name] = flow.chain; // Flows keep all files (order matters)\n }\n\n const output: Record<string, unknown> = {\n exists: true,\n map: { status: \"available\" },\n updatedAt: snapshot.updatedAt,\n features: compactFeatures,\n flows: compactFlows,\n stale: isStale,\n };\n\n // Compact decision index — titles only, no bodies (up to 150 × 1.5KB is\n // too heavy for the orientation call). Full text via get_context or the\n // record file itself.\n const { loadDecisionStore } = await import(\"../decisions/decisions.js\");\n const store = await loadDecisionStore(rootDir);\n const decisionRecords = store.records;\n const decisionDrift = await computeDecisionDrift(rootDir, decisionRecords);\n const readTrust = createSnapshotTrustReader(rootDir);\n const trust: { features: Record<string, TrustState>; flows: Record<string, TrustState>; decisions: Record<string, TrustState> } = {\n ...await readSnapshotTrustIndex(readTrust, snapshot, drift),\n decisions: Object.fromEntries(decisionRecords.filter(d => d.status === \"active\").map(d => [d.id, decisionTrust(effectiveDecision(d), decisionDrift.freshness?.[d.id] ?? \"unknown\")])),\n };\n output.trust = trust;\n output.workingTree = drift?.workingTree;\n output.diagnostics = store.diagnostics;\n if (decisionRecords.length > 0) {\n const compactDecisions: Record<\n string,\n ReturnType<typeof compactDecisionKnowledge>\n > = {};\n for (const d of decisionRecords) {\n if (d.status !== \"active\") continue;\n compactDecisions[d.id] = compactDecisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\");\n }\n output.decisions = compactDecisions;\n output.decisionsHint =\n DECISION_GUIDANCE + \" Full bodies via get_context; full history via review_decision.\";\n }\n\n if (isStale && drift) {\n output.hint = driftHint(drift);\n output.drift = {\n historyAvailable: drift.historyAvailable,\n staleFeatures: drift.staleFeatures,\n staleFlows: drift.staleFlows,\n unmappedFiles: drift.unmappedFiles,\n ghostFiles: drift.ghostFiles,\n renames: drift.renames,\n recommendation: drift.recommendation,\n };\n if (drift.historyAvailable && drift.changedFiles.length > 0) {\n const samples = await buildChangedFilePreviews(\n rootDir,\n drift.changedFiles\n );\n output.diff = {\n changedFiles: drift.changedFiles,\n samples,\n truncated: drift.changedFiles.length > STALE_DIFF_MAX_FILES,\n };\n }\n }\n\n output.hint = [output.hint, trustHint([...Object.values(trust.features), ...Object.values(trust.flows), ...Object.values(trust.decisions)]), store.diagnostics.length ? \"Some decision records are invalid; consult diagnostics.\" : \"\"].filter(Boolean).join(\" \");\n return JSON.stringify(output);\n}\n\nfunction driftHint(report: DriftReport): string {\n if (!report.stale) {\n return \"No committed changes affect the map. Consult verification and working-tree evidence before relying on it.\";\n }\n if (!report.historyAvailable) {\n return \"Snapshot is stale but its commit is unreachable (shallow clone or rewritten history), so per-feature drift cannot be computed. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.recommendation === \"full-rebuild\") {\n return \"Drift is too large for an incremental update. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.changedFiles.length + report.unmappedFiles.length > STALE_DIFF_MAX_FILES) {\n return \"Many files drifted — use a scoped refresh instead of reading them all inline: call generate_snapshot_batch(dir, files=[...changedFiles, ...unmappedFiles]) repeatedly (same list every call) with save_partial_snapshot per batch, then reduce_snapshot and save_snapshot. Entries untouched by the drift are preserved in the reduce step.\";\n }\n const nothingToRemap =\n Object.keys(report.staleFeatures).length === 0 &&\n Object.keys(report.staleFlows).length === 0 &&\n report.unmappedFiles.length === 0 &&\n report.ghostFiles.length === 0;\n if (nothingToRemap) {\n return \"Changes since the snapshot don't touch any mapped files. Call save_snapshot with empty features/flows to re-pin the snapshot to HEAD.\";\n }\n return \"Read the changed files under staleFeatures/staleFlows, update those entries (fold unmappedFiles into the right features), and call save_snapshot with only the affected entries — unchanged entries are preserved. Drop ghostFiles from any entries that reference them, and delete features/flows that no longer exist via save_snapshot's removeFeatures/removeFlows.\";\n}\n\nexport async function checkDrift(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n\n const report = await computeDrift(rootDir);\n if (!report) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists to check. Decisions and impact work without one; mason_init with mode: \\\"map\\\" provides the optional map workflow.\",\n });\n }\n\n // Report recorded correctness verdicts alongside freshness evidence.\n const snapshot = await loadSnapshot(rootDir);\n let verification: Record<string, unknown> | undefined;\n let hint = driftHint(report);\n if (snapshot) {\n const all = [\n ...Object.values(snapshot.features),\n ...Object.values(snapshot.flows),\n ];\n const failedNames = [\n ...Object.entries(snapshot.features)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ...Object.entries(snapshot.flows)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ];\n verification = {\n neverVerified: all.filter((e) => !e.verifiedAt).length,\n failed: failedNames,\n };\n if (failedNames.length > 0) {\n hint += ` Verification previously FAILED for [${failedNames.join(\", \")}] — re-map those entries before trusting them.`;\n }\n }\n\n return JSON.stringify({ exists: true, ...report, verification, hint });\n}\n\nexport async function generateSnapshotBatch(\n dir: string,\n offset: number = 0,\n batchSize: number = DEFAULT_BATCH_SIZE,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const scoped = files !== undefined && files.length > 0;\n const scopeFiles = scoped ? sanitizePaths(rootDir, files) : undefined;\n const batch = await prepareSnapshotBatch(dir, offset, batchSize, scopeFiles);\n\n if (scoped && batch.totalFiles > 0) {\n // Mark this partial run as a scoped refresh so reduce_snapshot merges\n // into the existing map instead of rebuilding it from partials alone.\n await saveScope(rootDir, scopeFiles!);\n } else if (!scoped) {\n // A full build must never inherit a scope marker left behind by an\n // abandoned refresh run — its reduce step would wrongly merge instead\n // of rebuilding.\n await clearScope(rootDir);\n }\n\n const task = scoped\n ? \"Refresh the concept map for a scoped set of drifted files (batch step).\"\n : \"Build a concept-to-files map for this project (batch step).\";\n\n if (batch.totalFiles === 0) {\n return JSON.stringify(\n {\n task,\n offset: 0,\n nextOffset: null,\n totalFiles: 0,\n batchId: batchIdFor(0),\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: scoped\n ? \"(None of the requested files exist as source files in this project.)\"\n : \"(No source files found to map.)\",\n next: scoped\n ? \"None of the requested files matched project source files. Check the paths passed in `files` — they must be repo-relative.\"\n : \"No source files were found. Skip the rest of the playbook and call mason_complete_init.\",\n },\n null,\n 2\n );\n }\n\n const batchId = batchIdFor(batch.offset);\n const continueCall = scoped\n ? `generate_snapshot_batch(dir, offset=${batch.nextOffset}, files=<the same list>)`\n : `generate_snapshot_batch(dir, offset=${batch.nextOffset})`;\n\n return JSON.stringify(\n {\n task,\n offset: batch.offset,\n nextOffset: batch.nextOffset,\n totalFiles: batch.totalFiles,\n batchId,\n batchSize: batch.batchSize,\n filesInBatch: batch.skeletons.length,\n scoped,\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: buildBatchPrompt(batch),\n next:\n batch.nextOffset === null\n ? `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). This is the last batch — after saving, proceed to reduce_snapshot.`\n : `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). Then call ${continueCall} to continue.`,\n },\n null,\n 2\n );\n}\n\nexport async function saveSnapshotPartial(\n dir: string,\n batchId: string,\n offset: number,\n features: Record<\n string,\n { description: string; files: string[]; tests?: string[]; type?: FeatureType }\n >,\n flows: Record<string, { description: string; chain: string[] }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Sanitize all file paths to prevent path traversal in stored partials, and\n // normalize the capability/infrastructure classification so it survives reduce.\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n await savePartial(rootDir, {\n batchId,\n offset,\n features,\n flows,\n savedAt: new Date().toISOString(),\n });\n\n const all = await loadAllPartials(rootDir);\n return JSON.stringify(\n {\n status: \"stored\",\n batchId,\n partialsStored: all.length,\n hint:\n \"Partial saved. Continue with the next generate_snapshot_batch call, or proceed to reduce_snapshot when nextOffset is null.\",\n },\n null,\n 2\n );\n}\n\nexport async function reduceSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const partials = await loadAllPartials(rootDir);\n\n if (partials.length === 0) {\n return JSON.stringify(\n {\n status: \"error\",\n error:\n \"No partial snapshots found. Run generate_snapshot_batch and save_partial_snapshot at least once before calling reduce_snapshot.\",\n },\n null,\n 2\n );\n }\n\n // A scope marker means these partials re-analyzed only a drifted subset —\n // merge them into the existing map instead of rebuilding from scratch.\n const scope = await loadScope(rootDir);\n const existing =\n scope && scope.length > 0 ? await loadSnapshot(rootDir) : null;\n\n if (scope && existing) {\n // Strip bookkeeping fields — the assistant shouldn't echo them back.\n const cleanFeatures = Object.fromEntries(\n Object.entries(existing.features).map(([name, feat]) => [\n name,\n {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n },\n ])\n );\n const cleanFlows = Object.fromEntries(\n Object.entries(existing.flows).map(([name, flow]) => [\n name,\n { description: flow.description, chain: flow.chain },\n ])\n );\n\n return JSON.stringify(\n {\n task: \"Merge a scoped refresh into the existing concept map.\",\n partialsCount: partials.length,\n refreshedFiles: scope.length,\n instructions: REFRESH_REDUCE_SYSTEM_PROMPT,\n prompt: buildRefreshReducePrompt(\n { features: cleanFeatures, flows: cleanFlows },\n scope,\n partials\n ),\n next: \"Follow `instructions` to produce the COMPLETE updated features/flows (entries untouched by the refresh copied through unchanged), then call save_snapshot(dir, features, flows). Partials and the scope marker are cleaned up automatically after save_snapshot succeeds.\",\n },\n null,\n 2\n );\n }\n\n return JSON.stringify(\n {\n task: \"Merge partial concept maps into one unified map.\",\n partialsCount: partials.length,\n instructions: REDUCE_SYSTEM_PROMPT,\n prompt: buildReducePrompt(partials),\n next: \"Follow `instructions` to produce the unified features/flows, then call save_snapshot(dir, features, flows). Partial files will be cleaned up automatically after save_snapshot succeeds. Finish with mason_complete_init(dir).\",\n },\n null,\n 2\n );\n}\n\nexport async function fullAnalysis(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const [analysis, structure, samples, testMap, snapshot] = await Promise.all([\n analyzeProject(dir),\n getProjectStructure(dir),\n getCodeSamples(dir, 25),\n getTestMap(dir),\n loadSnapshot(rootDir),\n ]);\n\n const output: Record<string, unknown> = {\n note: \"Full project analysis. Code samples are previews (~60 lines). Read files directly with your own tools to see them in full.\",\n analysis: JSON.parse(analysis),\n structure: JSON.parse(structure),\n codeSamples: JSON.parse(samples),\n testMap: JSON.parse(testMap),\n };\n\n if (snapshot) {\n output.conceptMap = {\n updatedAt: snapshot.updatedAt,\n features: snapshot.features,\n flows: snapshot.flows,\n };\n output.note =\n \"Full project analysis with concept map. The concept map shows which files implement each feature and how data flows through them. Use it to jump straight to relevant files instead of exploring, then read them directly with your own tools.\";\n }\n\n return JSON.stringify(output, null, 2);\n}\n\nfunction sanitizePaths(\n rootDir: string,\n files: string[]\n): string[] {\n return sanitizeRepoPaths(files);\n}\n\nexport async function saveSnapshotData(\n dir: string,\n features: Record<\n string,\n {\n description: string;\n files: string[];\n tests?: string[];\n refreshedHash?: string;\n type?: FeatureType;\n }\n >,\n flows: Record<\n string,\n { description: string; chain: string[]; refreshedHash?: string }\n >,\n removeFeatures: string[] = [],\n removeFlows: string[] = []\n): Promise<string> {\n const rootDir = path.resolve(dir);\n return updateSnapshot(rootDir, async previous => {\n const gitHash = await getCurrentGitHash(rootDir);\n const now = new Date().toISOString();\n\n // Sanitize all file paths to prevent path traversal, and normalize the\n // capability/infrastructure classification (defaults to \"capability\").\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n // If partials exist we're consolidating a Map-Reduce run: replace the\n // snapshot wholesale. Merging here would pollute the unified map with any\n // earlier (possibly hallucinated) call to save_snapshot. Outside of\n // Map-Reduce — incremental refresh of one feature — fall back to merge.\n const partials = await loadAllPartials(rootDir);\n const replaceMode = partials.length > 0;\n const existing = replaceMode ? null : previous;\n // Copy-through entries must not silently lose a failed verification during\n // a scoped rebuild. A changed description/path set requires a new verdict.\n const preserveVerification = (next: FeatureEntry | FlowEntry, old?: FeatureEntry | FlowEntry) => {\n delete next.verifiedAt;\n delete next.verifiedHash;\n delete next.verificationToken;\n delete next.verificationFailed;\n delete next.verificationNote;\n if (!old) return;\n if (JSON.stringify(snapshotEntryContent(next)) !== JSON.stringify(snapshotEntryContent(old))) return;\n next.verificationToken = old.verificationToken;\n next.verifiedAt = old.verifiedAt;\n next.verifiedHash = old.verifiedHash;\n next.verificationFailed = old.verificationFailed;\n next.verificationNote = old.verificationNote;\n };\n for (const [name, entry] of Object.entries(features)) preserveVerification(entry, previous?.features[name]);\n for (const [name, entry] of Object.entries(flows)) preserveVerification(entry, previous?.flows[name]);\n\n if (existing) {\n // Entries not re-sent in this call are only verified as of the previous\n // hash — record that before the top-level gitHash moves to HEAD, so\n // drift detection can still see which entries were skipped.\n if (existing.gitHash !== \"unknown\") {\n for (const feat of Object.values(existing.features)) {\n feat.refreshedHash ??= existing.gitHash;\n }\n for (const flow of Object.values(existing.flows)) {\n flow.refreshedHash ??= existing.gitHash;\n }\n }\n\n const removedFeatures = removeFeatures.filter(\n (name) => name in existing.features\n );\n const removedFlows = removeFlows.filter((name) => name in existing.flows);\n for (const name of removedFeatures) delete existing.features[name];\n for (const name of removedFlows) delete existing.flows[name];\n\n if (gitHash !== \"unknown\") {\n for (const feat of Object.values(features)) feat.refreshedHash = gitHash;\n for (const flow of Object.values(flows)) flow.refreshedHash = gitHash;\n }\n\n existing.features = { ...existing.features, ...features };\n existing.flows = { ...existing.flows, ...flows };\n existing.updatedAt = now;\n existing.gitHash = gitHash;\n return { snapshot: existing, afterSave: () => clearAllPartials(rootDir), result: JSON.stringify({\n status: \"updated\",\n mode: \"merged\",\n features: Object.keys(existing.features).length,\n flows: Object.keys(existing.flows).length,\n removedFeatures: removedFeatures.length,\n removedFlows: removedFlows.length,\n }) };\n }\n\n const snapshot: Snapshot = {\n version: 2,\n createdAt: now,\n updatedAt: now,\n gitHash,\n features,\n flows,\n };\n\n return { snapshot, afterSave: () => clearAllPartials(rootDir), result: JSON.stringify({\n status: replaceMode ? \"replaced\" : \"created\",\n mode: replaceMode ? \"replaced-from-partials\" : \"fresh\",\n features: Object.keys(features).length,\n flows: Object.keys(flows).length,\n }) };\n });\n}\n\nexport async function configureProject(\n dir: string,\n config: {\n patterns?: string[];\n alwaysInclude?: string[];\n ignore?: string[];\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = (await readStoreJson(rootDir, \".mason/config.json\") ?? {}) as Record<string, unknown>;\n\n if (config.patterns) existing.patterns = config.patterns;\n if (config.alwaysInclude) existing.alwaysInclude = config.alwaysInclude;\n if (config.ignore) existing.ignore = config.ignore;\n\n await writeStoreJson(rootDir, \".mason/config.json\", existing);\n\n return JSON.stringify({\n status: \"saved\",\n path: path.join(rootDir, \".mason/config.json\"),\n config: existing,\n });\n}\n\nexport async function getImpact(\n dir: string,\n files: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { analyzeImpact } = await import(\"../impact/impact.js\");\n const result = await analyzeImpact(rootDir, files);\n return JSON.stringify(result, null, 2);\n}\n\nconst VERIFY_DEFAULT_SAMPLE = 5;\n\n/**\n * Verification closes the day-one hole drift can't: drift proves the map is\n * current against git, but nothing proves an entry was CORRECT when written.\n * Sample entries weighted toward never-verified, then oldest-verified.\n */\nexport async function verifySnapshot(\n dir: string,\n sample: number = VERIFY_DEFAULT_SAMPLE\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists yet — nothing to verify.\",\n });\n }\n\n const entries = [\n ...Object.entries(snapshot.features).map(([name, e]) => ({\n name,\n kind: \"feature\" as const,\n description: e.description,\n files: e.files,\n verifiedAt: e.verifiedAt,\n })),\n ...Object.entries(snapshot.flows).map(([name, e]) => ({\n name,\n kind: \"flow\" as const,\n description: e.description,\n files: e.chain,\n verifiedAt: e.verifiedAt,\n })),\n ];\n\n entries.sort((a, b) => {\n if (!a.verifiedAt && !b.verifiedAt) return a.name.localeCompare(b.name);\n if (!a.verifiedAt) return -1;\n if (!b.verifiedAt) return 1;\n return a.verifiedAt.localeCompare(b.verifiedAt);\n });\n\n const access = await createFileAccess(rootDir);\n const picked = entries.slice(0, Math.max(1, sample));\n const toVerify = [];\n for (const entry of picked) {\n const stored = entry.kind === \"feature\" ? snapshot.features[entry.name] : snapshot.flows[entry.name];\n toVerify.push({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n lastVerified: entry.verifiedAt ?? \"never\",\n ...await prepareSnapshotReview(access, entry.kind, entry.name, stored),\n });\n }\n\n const neverVerified = entries.filter((e) => !e.verifiedAt).length;\n\n return JSON.stringify({\n exists: true,\n totalEntries: entries.length,\n neverVerified,\n entries: toVerify,\n instructions:\n 'Judge whether the files implement each claimed feature/flow, then call save_verification with verdicts: {\"<entry name>\": {\"kind\": \"<feature|flow from the entry>\", \"reviewToken\": \"<token from the entry>\", \"ok\": true|false, \"note\": \"<required when ok is false>\"}}. Tokens cover the entry and full contents of the previewed files (at most 8), including unavailable-file markers; previews themselves are truncated. This is a spot-check, not proof of unshown files. A conflict requires verify_snapshot and a fresh review; never reuse a verdict for changed content. If a feature and flow share a name, submit their verdicts in separate calls.'\n });\n}\n\nexport async function saveVerification(\n dir: string,\n verdicts: Record<string, SnapshotVerdict>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n return updateSnapshot(rootDir, async snapshot => {\n if (!snapshot) {\n return { snapshot: null, result: JSON.stringify({ exists: false, stamped: [], hint: \"No concept map exists. Build it and run verify_snapshot before recording verdicts.\" }) };\n }\n\n const stamped: string[] = [], unknown: string[] = [], failed: string[] = [];\n const conflicts: string[] = [], reviewRequired: string[] = [], invalid: string[] = [];\n const candidates: Array<{ name: string; verdict: SnapshotVerdict; entry: FeatureEntry | FlowEntry }> = [];\n let access: Awaited<ReturnType<typeof createFileAccess>> | undefined;\n for (const [name, verdict] of Object.entries(verdicts)) {\n if (!verdict.kind || ![\"feature\", \"flow\"].includes(verdict.kind) || !/^[a-f0-9]{64}$/.test(verdict.reviewToken ?? \"\")) {\n reviewRequired.push(name);\n continue;\n }\n if (typeof verdict.ok !== \"boolean\" || (!verdict.ok && !verdict.note?.trim())) {\n invalid.push(name);\n continue;\n }\n const collection = verdict.kind === \"feature\" ? snapshot.features : snapshot.flows;\n if (!Object.hasOwn(collection, name)) {\n unknown.push(name);\n conflicts.push(name);\n continue;\n }\n const entry = collection[name];\n access ??= await createFileAccess(rootDir);\n const current = await prepareSnapshotReview(access, verdict.kind, name, entry);\n if (current.reviewToken !== verdict.reviewToken) conflicts.push(name);\n else candidates.push({ name, verdict, entry });\n }\n\n const verifiedHash = candidates.length ? await getCurrentGitHash(rootDir) : \"unknown\";\n // Refresh the inventory and source reads before committing a multi-entry batch.\n // Editors do not take our lock; the persisted token identifies the evidence\n // actually checked, while normal drift reporting handles later source edits.\n const freshAccess = candidates.length ? await createFileAccess(rootDir) : null;\n const now = new Date().toISOString();\n for (const { name, verdict, entry } of candidates) {\n const current = await prepareSnapshotReview(freshAccess!, verdict.kind!, name, entry);\n if (current.reviewToken !== verdict.reviewToken) {\n conflicts.push(name);\n continue;\n }\n entry.verifiedAt = now;\n entry.verifiedHash = verifiedHash;\n entry.verificationToken = verdict.reviewToken;\n if (verdict.ok) {\n delete entry.verificationFailed;\n delete entry.verificationNote;\n } else {\n entry.verificationFailed = true;\n entry.verificationNote = verdict.note!.trim();\n failed.push(name);\n }\n stamped.push(name);\n }\n\n const rejected = conflicts.length + reviewRequired.length + invalid.length;\n const status = rejected ? (stamped.length ? \"partial\" : conflicts.length ? \"conflict\" : reviewRequired.length ? \"review_required\" : \"invalid\")\n : stamped.length ? \"saved\" : \"unchanged\";\n const hints: string[] = [];\n if (conflicts.length) hints.push(`Entries [${conflicts.join(\", \")}] changed or were deleted after review. Run verify_snapshot and review current evidence before retrying.`);\n if (reviewRequired.length) hints.push(`Entries [${reviewRequired.join(\", \")}] need kind and reviewToken from verify_snapshot. Inspect that evidence before submitting a verdict.`);\n if (invalid.length) hints.push(`Entries [${invalid.join(\", \")}] need a boolean ok and a non-empty note when ok is false.`);\n if (failed.length) hints.push(`Entries [${failed.join(\", \")}] are mis-mapped. Re-map them: read their actual files, correct the entries, and call save_snapshot with only those entries (plus removeFeatures/removeFlows if a concept no longer exists). Then run verify_snapshot for fresh review tokens.`);\n if (!hints.length) hints.push(stamped.length ? \"All submitted entries verified against the reviewed evidence. Re-run verify_snapshot periodically.\" : \"No verdicts submitted; nothing changed.\");\n if (stamped.length) snapshot.updatedAt = now;\n return { snapshot: stamped.length ? snapshot : null, result: JSON.stringify({\n status, stamped, unknown, failed, conflicts, reviewRequired, invalid, hint: hints.join(\" \"),\n }) };\n });\n}\n\nexport async function saveDecision(\n dir: string,\n input: UpsertDecisionInput\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { upsertDecision } = await import(\"../decisions/decisions.js\");\n const result = await upsertDecision(rootDir, input);\n return JSON.stringify(result);\n}\n\nexport async function reviewDecision(dir: string, input: ReviewDecisionInput): Promise<string> {\n return JSON.stringify(await runDecisionReview(path.resolve(dir), input));\n}\n\nexport async function getContext(\n dir: string,\n task: string,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { assembleContext } = await import(\"../context/assemble.js\");\n const bundle = await assembleContext(rootDir, task, files);\n return JSON.stringify(bundle);\n}\n\n// ===== Init MCP tools =====\n\nexport async function masonAutomation(dir: string, action: \"status\" | \"check\"): Promise<string> {\n try {\n const { automate, automationStatus, summarize } = await import(\"../automation/runtime.js\");\n const { installedAutomation } = await import(\"../automation/install.js\");\n if (action === \"status\") {\n const { setupStatus } = await import(\"../setup/status.js\");\n return JSON.stringify({ ...await automationStatus(dir), configured: await installedAutomation(dir), setup: await setupStatus(dir) });\n }\n if (action !== \"check\") throw new Error(\"Expected status or check.\");\n const { report } = await automate(dir, { event: \"task_end\" });\n const { findings, ...summary } = report;\n return JSON.stringify({ ...summary, findings: findings.slice(0, 5), truncated: findings.length > 5, summary: summarize(report) });\n } catch (error) {\n const { automationFailure } = await import(\"../automation/execution.js\");\n const failure = automationFailure(error);\n return JSON.stringify({ version: 1, status: \"unavailable\", error: failure.message, failure });\n }\n}\n\nexport async function masonReviewAdvisory(dir: string, options: AdvisoryReviewInput): Promise<string> {\n try { return JSON.stringify(await reviewAdvisory(dir, options), null, 2); }\n catch (error) { return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) }); }\n}\n\nexport async function masonRepair(dir: string, options: { action: \"prepare\" | \"verify\"; baselinePath?: string; checks?: CheckName[] }): Promise<string> {\n try {\n if (options.action === \"verify\") {\n if (!options.baselinePath || options.checks) throw new Error(\"Verification requires baselinePath and uses the original checks; do not pass checks.\");\n return JSON.stringify(await verifyRepair(dir, options.baselinePath), null, 2);\n }\n if (options.action !== \"prepare\" || options.baselinePath) throw new Error(\"Preparation accepts checks, not an existing baselinePath.\");\n const result = await prepareRepair(dir, options.checks);\n return JSON.stringify({ ...result, workOrder: formatFixPrompt(result.report, result.baselinePath) }, null, 2);\n } catch (error) {\n return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nexport async function masonInit(dir: string, options: { mode?: InitMode; host?: \"codex\" | \"claude\"; base?: string; evidence?: string[] } = {}): Promise<string> {\n if (options.mode === \"setup\") {\n const { setupProject } = await import(\"../setup/setup.js\");\n return JSON.stringify(await setupProject(dir, options), null, 2);\n }\n if (options.host) throw new Error(\"host applies only to mode: setup.\");\n const rootDir = path.resolve(dir);\n const marker = await loadProjectMarker(rootDir);\n const { loadSetup } = await import(\"../setup/model.js\");\n const setup = await loadSetup(rootDir);\n const mode = options.mode ?? \"quickstart\";\n const findings = await inspectOnboarding(rootDir, options.base, options.evidence);\n return JSON.stringify(\n {\n initialized: marker !== null || setup !== null,\n ...(marker ? { initializedAt: marker.initializedAt } : {}),\n confluenceConfigured: (await loadProjectFeatures(rootDir)).confluence === true,\n mode,\n ...findings,\n playbook: setupPlaybook(mode),\n },\n null,\n 2\n );\n}\n\nexport async function masonCompleteInit(\n dir: string,\n options: { confluenceConfigured?: boolean } = {}\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = await loadProjectMarker(rootDir);\n const features = await loadProjectFeatures(rootDir);\n const marker: ProjectMarker = {\n version: 1,\n initializedAt: existing?.initializedAt ?? new Date().toISOString(),\n features: {\n ...features,\n ...(options.confluenceConfigured === undefined ? {} : { confluence: options.confluenceConfigured }),\n },\n };\n await saveProjectMarker(rootDir, marker);\n return JSON.stringify(\n {\n status: \"initialized\",\n marker,\n hint: \"Assistant setup recorded. Save decisions as you learn, review and commit them, and retrieve them with get_context. A concept map is optional.\",\n },\n null,\n 2\n );\n}\n\n// ===== Confluence MCP tools =====\n\nexport async function masonSetConfluence(input: {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey?: string;\n parentPageId?: string;\n}): Promise<string> {\n const { createConfluenceClient } = await import(\"../confluence/client.js\");\n const { saveConfluenceConfig } = await import(\"../llm/config.js\");\n const { normalizeAtlassianBaseUrl } = await import(\"../confluence/url.js\");\n\n let baseUrl: string;\n try {\n baseUrl = normalizeAtlassianBaseUrl(input.baseUrl);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n if (!input.email.includes(\"@\")) {\n return JSON.stringify({\n status: \"error\",\n error: `Email looks invalid: \"${input.email}\".`,\n });\n }\n if (!input.apiToken.trim()) {\n return JSON.stringify({\n status: \"error\",\n error: \"API token is required.\",\n });\n }\n\n const probeConfig = {\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey ?? \"\",\n parentPageId: input.parentPageId,\n };\n const client = createConfluenceClient(probeConfig);\n\n let spaces;\n try {\n spaces = await client.listSpaces();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"401\") || msg.includes(\"403\")) {\n return JSON.stringify({\n status: \"error\",\n error:\n \"Credentials rejected by Confluence. Re-check the email and that the API token hasn't expired or been revoked.\",\n });\n }\n return JSON.stringify({\n status: \"error\",\n error: `Confluence validation failed: ${msg}`,\n });\n }\n\n if (!input.spaceKey) {\n // Step 1 — return spaces for the assistant to relay to the user.\n return JSON.stringify(\n {\n status: \"spaces_listed\",\n baseUrl,\n spaces: spaces.map((s) => ({ key: s.key, name: s.name })),\n hint:\n spaces.length === 0\n ? \"Authenticated, but no spaces are visible to this account. Create one in Confluence first, then re-run mason_set_confluence.\"\n : \"Ask the user which space to use, then call mason_set_confluence again with the same baseUrl/email/apiToken plus the chosen spaceKey.\",\n },\n null,\n 2\n );\n }\n\n const match = spaces.find((s) => s.key === input.spaceKey);\n if (!match) {\n return JSON.stringify({\n status: \"error\",\n error: `Space key \"${input.spaceKey}\" was not found among the spaces visible to this account. Available keys: ${spaces.map((s) => s.key).join(\", \") || \"(none)\"}.`,\n });\n }\n\n await saveConfluenceConfig({\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey,\n parentPageId: input.parentPageId,\n });\n\n return JSON.stringify(\n {\n status: \"saved\",\n spaceKey: input.spaceKey,\n spaceName: match.name,\n hint:\n \"Confluence is configured. The credentials are stored in ~/.mason/config.json. Call export_to_confluence to sync the concept map.\",\n },\n null,\n 2\n );\n}\n\nexport async function exportToConfluenceTool(\n dir: string,\n overrides?: {\n spaceKey?: string;\n parentPageId?: string;\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const { loadConfig } = await import(\"../llm/config.js\");\n const { exportToConfluence } = await import(\"../confluence/sync.js\");\n\n const config = await loadConfig();\n if (!config?.confluence) {\n return JSON.stringify({\n status: \"error\",\n error:\n 'No Confluence credentials configured. Call mason_set_confluence first.',\n });\n }\n\n const merged = {\n ...config,\n confluence: {\n ...config.confluence,\n spaceKey: overrides?.spaceKey ?? config.confluence.spaceKey,\n parentPageId: overrides?.parentPageId ?? config.confluence.parentPageId,\n },\n };\n\n try {\n const summary = await exportToConfluence(rootDir, merged, {\n indexPageTitle: overrides?.indexPageTitle,\n changelogPageTitle: overrides?.changelogPageTitle,\n featurePagePrefix: overrides?.featurePagePrefix,\n });\n return JSON.stringify({ status: \"ok\", ...summary }, null, 2);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","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\";\nimport { findingId } from \"./findings.js\";\nimport { runAdvisoryCli } from \"./advisory-cli.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits README.md and agent instruction files at any depth, preserving filename case\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\nUse mason audit review --help to prepare and record an authorized advisory assessment.\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 reviewed = new Set(report.advisoryReviews?.filter(review => review.status === \"current\").map(review => review.id));\n const open = report.advisories.filter(finding => !reviewed.has(findingId(finding)));\n const suppressed = (report.suppressedAdvisories ?? []).filter(finding => !reviewed.has(findingId(finding)));\n const reviewCount = open.length + suppressed.length;\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 (open.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of open) {\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 if (reviewed.size) lines.push(`${reviewed.size} advisories have recorded assessments covering current evidence (see --json).`);\n for (const review of report.advisoryReviews ?? []) if (review.status !== \"current\") lines.push(` [${review.status}] ${review.reason}`);\n for (const advisory of suppressed) {\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: review whether the directory needs documenting; an omission alone does not establish a defect. Preserve scope and describe only what you verified.\"\n );\n lines.push(\n \"- Historical ADVISORIES require a separate authorized assessment using review_advisory with the baselinePath and findingId from verification. Prepare and inspect evidence first; record addressed, inapplicable or deferred with the actual reviewer, note and reviewToken. Decision findings use review_decision. Candidates marked resolution: recheck can be rerun to see whether the condition remains; this does not establish semantic approval. Report what remains unknown.\"\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 documents and supported claims; application behavior and code examples 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 if (argv[0] === \"review\") return runAdvisoryCli(argv.slice(1), io);\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 README.md or agent instruction files 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 path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { reviewAdvisory, type AdvisoryReviewInput } from \"./advisory-review.js\";\n\nconst USAGE = `Usage: mason audit review --baseline <path> --finding <id> [options]\n\nPrepare an advisory assessment against retained evidence (read-only by default).\n --dir <path> Repository root (default: current directory)\n --baseline <path> Original repair baseline\n --finding <id> findingId from repair verification or automation\n --outcome <value> Record addressed, inapplicable, or deferred\n --reviewer <name> Actual authorized reviewer\n --note <reason> Assessment reason\n --token <token> reviewToken returned by preparation\n --json Full evidence and review history\n\nRecording requires prior preparation and committed relevant edits. Review records\nbelong in Git under .mason/reviews/advisories/. Deferral remains outstanding.\nDecision findings use review_decision; this command never approves decisions.\nExit 0: prepared/recorded; 2: unavailable, conflict, or decision review required.`;\n\nexport async function runAdvisoryCli(args: string[], io = { out: (text: string) => console.log(text), err: (text: string) => console.error(text) }): Promise<number> {\n if (args.includes(\"--help\") || args.includes(\"-h\")) { io.out(USAGE); return 0; }\n try {\n const flags: Record<string, string> = {}; let json = false;\n for (let i = 0; i < args.length; i++) {\n const flag = args[i];\n if (flag === \"--json\") { json = true; continue; }\n if (![\"--dir\", \"--baseline\", \"--finding\", \"--outcome\", \"--reviewer\", \"--note\", \"--token\"].includes(flag) || flags[flag]) throw new Error(\"Unexpected or repeated argument: \" + flag);\n const value = args[++i]; if (!value || value.startsWith(\"--\")) throw new Error(flag + \" requires a value.\");\n flags[flag] = value;\n }\n if (!flags[\"--outcome\"] && [\"--reviewer\", \"--note\", \"--token\"].some(key => flags[key])) throw new Error(\"Use --outcome to record an assessment.\");\n const input = { baselinePath: flags[\"--baseline\"], findingId: flags[\"--finding\"],\n action: flags[\"--outcome\"] ?? \"prepare\", reviewer: flags[\"--reviewer\"], note: flags[\"--note\"], reviewToken: flags[\"--token\"] } as AdvisoryReviewInput;\n const result = await reviewAdvisory(path.resolve(flags[\"--dir\"] ?? process.cwd()), input);\n if (json) io.out(JSON.stringify(result, null, 2));\n else {\n const lines = [`Advisory review: ${result.status}.`];\n if (\"finding\" in result && result.finding && result.evidence) lines.push(`[${result.finding.type}] ${result.finding.anchor.doc}: ${result.finding.message}`,\n `Finding: ${result.findingId}`, `Prepared against commit ${result.evidence.head.slice(0, 12)}.`,\n result.evidence.dirty ? \"Relevant files have uncommitted edits; commit them and prepare again before recording.\" : \"Relevant files are committed.\",\n `Review token: ${result.reviewToken}`, ...(result.diff ? [\"Scoped changes:\", result.diff] : []), ...(result.diffNote ? [result.diffNote] : []));\n if (\"event\" in result) lines.push(`${result.event.outcome} — ${result.event.reviewer}: ${result.event.note}`, `Record: ${result.recordPath}`);\n lines.push(result.hint);\n io.out(stripVTControlCharacters(lines.join(\"\\n\")));\n }\n return result.status === \"decision-review-required\" ? 2 : 0;\n } catch (error) { io.err(stripVTControlCharacters(error instanceof Error ? error.message : String(error))); return 2; }\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { BaseAnalyzer } from \"./base.js\";\nimport type { AnalyzerContext, AnalyzerResult, Finding, Gap } from \"../types.js\";\n\nconst exec = promisify(execFile);\n\nexport class GitHistoryAnalyzer extends BaseAnalyzer {\n name = \"git-history\";\n\n async analyze(context: AnalyzerContext): Promise<AnalyzerResult> {\n const startTime = Date.now();\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n if (!context.gitAvailable) {\n return this.createResult([], [], startTime);\n }\n\n const [staleFindings, staleGaps] = await this.findStaleDirectories(context);\n findings.push(...staleFindings);\n gaps.push(...staleGaps);\n\n const hotFindings = await this.findHotFiles(context);\n findings.push(...hotFindings);\n\n const commitFindings = await this.analyzeCommitPatterns(context);\n findings.push(...commitFindings);\n\n return this.createResult(findings, gaps, startTime);\n }\n\n private async git(\n args: string[],\n cwd: string\n ): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", args, { cwd, maxBuffer: 10_000_000 });\n return stdout.trim();\n } catch {\n return \"\";\n }\n }\n\n private async findStaleDirectories(\n context: AnalyzerContext\n ): Promise<[Finding[], Gap[]]> {\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n // Get top-level directories with their last commit date\n const output = await this.git(\n [\"log\", \"--all\", \"--format=%ci\", \"--name-only\", \"--diff-filter=AMCR\", \"-n\", \"500\"],\n context.rootDir\n );\n\n if (!output) return [findings, gaps];\n\n const dirLastTouch = new Map<string, Date>();\n let currentDate: Date | null = null;\n\n for (const line of output.split(\"\\n\")) {\n if (!line) continue;\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(line)) {\n currentDate = new Date(line);\n } else if (currentDate) {\n const topDir = line.split(\"/\")[0];\n if (\n topDir &&\n !topDir.startsWith(\".\") &&\n !topDir.includes(\"node_modules\")\n ) {\n const existing = dirLastTouch.get(topDir);\n if (!existing || currentDate > existing) {\n dirLastTouch.set(topDir, currentDate);\n }\n }\n }\n }\n\n const sixMonthsAgo = new Date();\n sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);\n\n for (const [dir, lastTouch] of dirLastTouch) {\n if (lastTouch < sixMonthsAgo) {\n const monthsStale = Math.floor(\n (Date.now() - lastTouch.getTime()) / (1000 * 60 * 60 * 24 * 30)\n );\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.7,\n summary: `Directory \"${dir}\" hasn't been modified in ${monthsStale} months`,\n evidence: [\n { filePath: dir, detail: `Last commit: ${lastTouch.toISOString().split(\"T\")[0]}` },\n ],\n ruleCandidate: `Do not refactor or modify files in \"${dir}/\" unless explicitly asked — this area has been stable for ${monthsStale} months and may be legacy code.`,\n })\n );\n gaps.push({\n analyzer: this.name,\n question: `Directory \"${dir}\" hasn't been touched in ${monthsStale} months. Is it deprecated, stable, or legacy?`,\n context: `Last modified: ${lastTouch.toISOString().split(\"T\")[0]}`,\n answerKey: `stale-dir-${dir}`,\n });\n }\n }\n\n return [findings, gaps];\n }\n\n private async findHotFiles(context: AnalyzerContext): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n // Most frequently changed files in the last 3 months\n const output = await this.git(\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const fileCounts = new Map<string, number>();\n for (const line of output.split(\"\\n\")) {\n if (!line || line.startsWith(\".\") || line.includes(\"node_modules\")) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const sorted = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10);\n\n if (sorted.length > 0 && sorted[0][1] >= 5) {\n const hotFiles = sorted.filter(([, count]) => count >= 5);\n if (hotFiles.length > 0) {\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.8,\n summary: `${hotFiles.length} files changed frequently in the last 3 months`,\n evidence: hotFiles.map(([file, count]) => ({\n filePath: file,\n detail: `${count} commits`,\n })),\n ruleCandidate: `These files change frequently and are high-risk for conflicts: ${hotFiles.map(([f]) => f).join(\", \")}. Take extra care when modifying them.`,\n })\n );\n }\n }\n\n return findings;\n }\n\n private async analyzeCommitPatterns(\n context: AnalyzerContext\n ): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n const output = await this.git(\n [\"log\", \"--format=%s\", \"-n\", \"100\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const messages = output.split(\"\\n\").filter(Boolean);\n\n // Check for conventional commits\n const conventionalPattern = /^(feat|fix|chore|docs|style|refactor|test|perf|ci|build|revert)(\\(.+\\))?:/;\n const conventionalCount = messages.filter((m) =>\n conventionalPattern.test(m)\n ).length;\n const conventionalRatio = conventionalCount / messages.length;\n\n if (conventionalRatio > 0.5) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: Math.min(conventionalRatio + 0.1, 1),\n summary: `${Math.round(conventionalRatio * 100)}% of recent commits use conventional commit format`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${conventionalCount} of ${messages.length} commits match`,\n },\n ],\n ruleCandidate:\n \"Use conventional commit format: type(scope): description (e.g., feat(auth): add login endpoint)\",\n })\n );\n }\n\n // Check for ticket/issue references\n const ticketPattern = /[A-Z]+-\\d+|#\\d+/;\n const ticketCount = messages.filter((m) => ticketPattern.test(m)).length;\n const ticketRatio = ticketCount / messages.length;\n\n if (ticketRatio > 0.3) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: ticketRatio,\n summary: `${Math.round(ticketRatio * 100)}% of commits reference issue/ticket IDs`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${ticketCount} of ${messages.length} commits have ticket refs`,\n },\n ],\n ruleCandidate:\n \"Include issue/ticket references in commit messages when applicable.\",\n })\n );\n }\n\n return findings;\n }\n}\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport type {\n AnalyzerContext,\n AnalyzerResult,\n Finding,\n FindingCategory,\n} from \"../types.js\";\n\nexport abstract class BaseAnalyzer {\n abstract name: string;\n abstract analyze(context: AnalyzerContext): Promise<AnalyzerResult>;\n\n protected async findFiles(\n patterns: string[],\n root: string\n ): Promise<string[]> {\n return fg(patterns, {\n cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/.git/**\"],\n absolute: true,\n });\n }\n\n protected async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, \"utf-8\");\n }\n\n protected createFinding(partial: {\n category: FindingCategory;\n confidence: number;\n summary: string;\n evidence?: Finding[\"evidence\"];\n ruleCandidate?: string | null;\n }): Finding {\n return {\n analyzer: this.name,\n category: partial.category,\n confidence: partial.confidence,\n summary: partial.summary,\n evidence: partial.evidence ?? [],\n ruleCandidate: partial.ruleCandidate ?? null,\n };\n }\n\n protected createResult(\n findings: Finding[],\n gaps: AnalyzerResult[\"gaps\"],\n startTime: number\n ): AnalyzerResult {\n return {\n analyzer: this.name,\n findings,\n gaps,\n durationMs: Date.now() - startTime,\n };\n }\n}\n","import type { AnalyzerContext, AnalyzerResult } from \"../types.js\";\nimport type { BaseAnalyzer } from \"./base.js\";\nimport { GitHistoryAnalyzer } from \"./git-history.js\";\n\nconst analyzers: BaseAnalyzer[] = [new GitHistoryAnalyzer()];\n\nexport async function runAll(\n context: AnalyzerContext\n): Promise<AnalyzerResult[]> {\n return Promise.all(analyzers.map((a) => a.analyze(context)));\n}\n","import { execGit } from \"./git-read.js\";\n\n\nexport async function isGitRepo(dir: string): Promise<boolean> {\n try {\n await execGit([\"rev-parse\", \"--git-dir\"], { cwd: dir });\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_EXTENSIONS } from \"../utils/files.js\";\nexport type { ProjectConfig } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\n\nconst CONFIG_FILES = [\n // Build & project config\n \"package.json\",\n \"tsconfig.json\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"Gemfile\",\n \"*.csproj\",\n // Version catalogs & dependency locks\n \"gradle/libs.versions.toml\",\n // Code quality & formatting\n \".editorconfig\",\n \".eslintrc.*\",\n \"eslint.config.*\",\n \".prettierrc\",\n \"rustfmt.toml\",\n \".swiftlint.yml\",\n // CI/CD\n \".github/workflows/*.yml\",\n \".gitlab-ci.yml\",\n \"Jenkinsfile\",\n // Containerization\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n];\n\nconst ENTRY_POINT_PATTERNS = [\n \"src/main.*\",\n \"src/index.*\",\n \"src/app.*\",\n \"main.*\",\n \"index.*\",\n \"app.*\",\n \"App.*\",\n \"**/Main.kt\",\n \"**/Application.kt\",\n \"**/main.py\",\n \"**/main.go\",\n \"**/main.rs\",\n \"**/lib.rs\",\n \"**/Program.cs\",\n];\n\n// Filename patterns that reveal architectural patterns and conventions.\n// These are language-agnostic — the suffixes appear across ecosystems.\n// Ordered by architectural importance — most distinctive patterns first.\nconst ARCHITECTURAL_PATTERNS = [\n // State/data flow\n { glob: \"**/*ViewModel.*\", category: \"state\", reason: \"viewmodel (state management)\" },\n { glob: \"**/*Store.*\", category: \"state\", reason: \"store (state management)\" },\n { glob: \"**/*Reducer.*\", category: \"state\", reason: \"reducer (state management)\" },\n // Data layer — interface\n { glob: \"**/*Repository.*\", category: \"data-interface\", reason: \"repository interface (data layer contract)\" },\n { glob: \"**/*Dao.*\", category: \"data-interface\", reason: \"DAO (data access)\" },\n { glob: \"**/*DataSource.*\", category: \"data-interface\", reason: \"data source\" },\n // Data layer — implementation (where actual patterns live: mappers, retry, IO dispatchers)\n { glob: \"**/*RepositoryImpl.*\", category: \"data-impl\", reason: \"repository implementation (data layer patterns)\" },\n { glob: \"**/*ServiceImpl.*\", category: \"data-impl\", reason: \"service implementation\" },\n { glob: \"**/*Impl.*\", category: \"data-impl\", reason: \"implementation (concrete patterns)\" },\n // Data transformation\n { glob: \"**/*Mapper.*\", category: \"transform\", reason: \"mapper (data transformation)\" },\n { glob: \"**/*Converter.*\", category: \"transform\", reason: \"converter (data transformation)\" },\n { glob: \"**/*Adapter.*\", category: \"transform\", reason: \"adapter (interface adaptation)\" },\n // Dependency injection / wiring\n { glob: \"**/*Module.*\", category: \"di\", reason: \"module (DI/wiring)\" },\n { glob: \"**/*Provider.*\", category: \"di\", reason: \"provider (DI/wiring)\" },\n { glob: \"**/*Container.*\", category: \"di\", reason: \"container (DI/wiring)\" },\n { glob: \"**/*Factory.*\", category: \"di\", reason: \"factory (object creation)\" },\n // API / network\n { glob: \"**/*Service.*\", category: \"api\", reason: \"service (business/API layer)\" },\n { glob: \"**/*Client.*\", category: \"api\", reason: \"client (API/network layer)\" },\n { glob: \"**/*Api.*\", category: \"api\", reason: \"API interface definition\" },\n // Interface contracts / protocols\n { glob: \"**/*Interface.*\", category: \"contract\", reason: \"interface definition\" },\n { glob: \"**/*Protocol.*\", category: \"contract\", reason: \"protocol definition\" },\n { glob: \"**/*Trait.*\", category: \"contract\", reason: \"trait definition\" },\n // Routing / navigation\n { glob: \"**/*Router.*\", category: \"routing\", reason: \"router (navigation/routing)\" },\n { glob: \"**/*Route.*\", category: \"routing\", reason: \"route definition\" },\n { glob: \"**/*NavHost.*\", category: \"routing\", reason: \"navigation host\" },\n { glob: \"**/*Controller.*\", category: \"routing\", reason: \"controller (request handling)\" },\n { glob: \"**/*Handler.*\", category: \"routing\", reason: \"handler (request handling)\" },\n // Middleware / interceptors\n { glob: \"**/*Middleware.*\", category: \"middleware\", reason: \"middleware (request pipeline)\" },\n { glob: \"**/*Interceptor.*\", category: \"middleware\", reason: \"interceptor (cross-cutting)\" },\n { glob: \"**/*Plugin.*\", category: \"middleware\", reason: \"plugin (extensibility)\" },\n // Models / types\n { glob: \"**/*Model.*\", category: \"model\", reason: \"model (domain types)\" },\n { glob: \"**/*Entity.*\", category: \"model\", reason: \"entity (persistence types)\" },\n { glob: \"**/*Dto.*\", category: \"model\", reason: \"DTO (data transfer types)\" },\n { glob: \"**/*Schema.*\", category: \"model\", reason: \"schema (data validation)\" },\n // Use cases / commands\n { glob: \"**/*UseCase.*\", category: \"usecase\", reason: \"use case (business logic)\" },\n { glob: \"**/*Interactor.*\", category: \"usecase\", reason: \"interactor (business logic)\" },\n { glob: \"**/*Command.*\", category: \"usecase\", reason: \"command (CQRS pattern)\" },\n];\n\nconst PREVIEW_LINES = 60;\n\nexport interface SampledFile {\n path: string;\n preview: string;\n totalLines: number;\n sizeBytes: number;\n reason: string;\n}\n\nexport async function sampleFiles(\n rootDir: string,\n maxFiles: number = 25\n): Promise<SampledFile[]> {\n const selected = new Map<string, string>(); // path -> reason\n const access = await createFileAccess(rootDir);\n const projectConfig = access.config;\n\n // 0. Always-include files from project config (highest priority)\n for (const filePath of projectConfig.alwaysInclude ?? []) {\n if (selected.size >= maxFiles) break;\n // Validate path stays within project root\n const resolvedPath = path.resolve(rootDir, filePath);\n if (!resolvedPath.startsWith(path.resolve(rootDir))) continue;\n selected.set(filePath, \"always-include (project config)\");\n }\n\n // 1. Config files (cap at 5)\n let configCount = 0;\n for (const pattern of CONFIG_FILES) {\n if (configCount >= 5) break;\n const matches = await access.list(pattern, {\n deep: 3,\n });\n for (const match of matches) {\n if (configCount >= 5 || selected.size >= maxFiles) break;\n selected.set(match, \"config file\");\n configCount++;\n }\n }\n\n // 2. Module build/config files — build files from subdirectories reveal dependency graph\n const moduleBuildPatterns = [\n // Gradle\n \"**/build.gradle.kts\",\n \"**/build.gradle\",\n // Cargo workspace members\n \"**/Cargo.toml\",\n // Node workspaces\n \"**/package.json\",\n // Go sub-modules\n \"**/go.mod\",\n ];\n let moduleBuildCount = 0;\n for (const pattern of moduleBuildPatterns) {\n const matches = await access.list(pattern, {\n deep: 4,\n });\n // Skip root-level files (already captured as config)\n const subMatches = matches.filter((m) => m.includes(\"/\"));\n for (const match of subMatches) {\n if (moduleBuildCount >= 4 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"module build file (reveals dependency graph)\");\n moduleBuildCount++;\n }\n }\n if (moduleBuildCount >= 4) break;\n }\n\n // 3. Entry points (cap at 2)\n let entryCount = 0;\n for (const pattern of ENTRY_POINT_PATTERNS) {\n if (entryCount >= 2) break;\n const matches = await access.list(pattern, {\n deep: 5,\n });\n for (const match of matches) {\n if (entryCount >= 2 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"entry point\");\n entryCount++;\n }\n }\n }\n\n // 4. Hot files from git (up to 5)\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const fileCounts = new Map<string, number>();\n for (const line of stdout.split(\"\\n\")) {\n if (!line) continue;\n if (\n line.includes(\"node_modules\") ||\n line.includes(\"/build/\") ||\n line.includes(\".gradle\") ||\n line.includes(\"/generated/\")\n )\n continue;\n const ext = path.extname(line).slice(1);\n if (!SOURCE_EXTENSIONS.includes(ext)) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const hotFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n for (const [file, count] of hotFiles) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, `frequently changed (${count} commits in 3 months)`);\n }\n }\n } catch {\n // No git\n }\n\n // 5. Architectural pattern files — one per category (cap at 8)\n const seenCategories = new Set<string>();\n let patternCount = 0;\n for (const pattern of ARCHITECTURAL_PATTERNS) {\n if (patternCount >= 8 || selected.size >= maxFiles) break;\n if (seenCategories.has(pattern.category)) continue;\n\n const matches = await access.list(pattern.glob, {\n });\n\n if (matches.length > 0) {\n for (const match of matches) {\n if (!selected.has(match)) {\n selected.set(match, pattern.reason);\n seenCategories.add(pattern.category);\n patternCount++;\n break;\n }\n }\n }\n }\n\n // 5b. Custom patterns from project config\n for (const customGlob of projectConfig.patterns ?? []) {\n if (selected.size >= maxFiles) break;\n const matches = await access.list(customGlob, {\n });\n for (const match of matches) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"custom pattern (project config)\");\n break; // one per pattern\n }\n }\n }\n\n // 6. Test examples — diverse across file types (cap at 3)\n const testPatternGroups = [\n // JS/TS tests\n { patterns: [\"**/*.test.*\", \"**/*.spec.*\"], label: \"JS/TS test\" },\n // JVM tests\n { patterns: [\"**/*Test.kt\", \"**/*Test.java\"], label: \"JVM test\" },\n // Python tests\n { patterns: [\"**/test_*.py\", \"**/*_test.py\"], label: \"Python test\" },\n // Go tests\n { patterns: [\"**/*_test.go\"], label: \"Go test\" },\n // Swift tests\n { patterns: [\"**/*Tests.swift\", \"**/*Test.swift\"], label: \"Swift test\" },\n // Rust tests\n { patterns: [\"**/*_test.rs\"], label: \"Rust test\" },\n ];\n let testCount = 0;\n for (const group of testPatternGroups) {\n if (testCount >= 3 || selected.size >= maxFiles) break;\n const testFiles = await access.list(group.patterns, {\n });\n if (testFiles.length > 0) {\n for (const file of testFiles) {\n if (!selected.has(file)) {\n selected.set(file, `test example (${group.label})`);\n testCount++;\n break;\n }\n }\n }\n }\n\n // 7. Directory breadth — fill remaining slots with one file per top-level dir\n const sourceGlobs = SOURCE_EXTENSIONS.map((ext) => `**/*.${ext}`);\n const allSourceFiles = await access.list(sourceGlobs, {\n });\n\n const dirRepresentatives = new Map<string, string>();\n const boringFiles = /\\.(gradle|gradle\\.kts|json|toml|yaml|yml|xml|properties)$/;\n for (const file of allSourceFiles) {\n const topDir = file.split(\"/\")[0];\n if (!dirRepresentatives.has(topDir) && !boringFiles.test(file)) {\n dirRepresentatives.set(topDir, file);\n }\n }\n\n for (const [, file] of dirRepresentatives) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, \"directory representative\");\n }\n }\n\n // Read file previews\n const results: SampledFile[] = [];\n for (const [filePath, reason] of selected) {\n try {\n const full = await access.read(filePath);\n if (!full || Buffer.byteLength(full.content) > 100_000) continue;\n const lines = full.content.split(\"\\n\");\n const preview = lines.slice(0, PREVIEW_LINES).join(\"\\n\");\n\n results.push({\n path: filePath,\n preview,\n totalLines: lines.length,\n sizeBytes: Buffer.byteLength(full.content),\n reason,\n });\n } catch {\n // Skip\n }\n }\n\n return results;\n}\n\nexport async function readFullFile(\n rootDir: string,\n filePath: string\n): Promise<{ path: string; content: string; totalLines: number } | null> {\n return (await createFileAccess(rootDir)).read(filePath);\n}\n","import { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { loadDecisionStore, saveDecisionRecord, withDecisionWrite } from \"./decisions.js\";\nimport { decisionApproval, decisionAnchors, decisionContent, decisionProvenance, effectiveDecision, importLegacy, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { anchorMatches, matchingPaths } from \"../utils/paths.js\";\nimport { createFileAccess } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\nconst requestSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).default(\"prepare\"),\n reviewer: z.string().trim().min(1).max(200).optional(),\n note: z.string().trim().min(1).max(1500).optional(),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n});\nexport type ReviewDecisionInput = z.input<typeof requestSchema>;\n\nasync function reviewState(root: string, record: DecisionRecord) {\n const [headHash, workingTree, changes] = await Promise.all([\n getCurrentGitHash(root), getWorkingTree(root), getChangesWithStatus(root, record.refreshedHash),\n ]);\n const anchors = decisionAnchors(record);\n const committed = (changes ?? []).filter(c => [c.path, ...(c.previousPath ? [c.previousPath] : [])].some(file => anchors.some(anchor => anchorMatches(anchor, file))));\n const evidence = {\n baseHash: record.refreshedHash, headHash, historyAvailable: changes !== null,\n changedFiles: touchedPaths(committed), localChanges: matchingPaths(anchors, workingTree.changedFiles),\n };\n const reviewToken = createHash(\"sha256\").update(JSON.stringify({ record, evidence, workingTreeAvailable: workingTree.available })).digest(\"hex\");\n return { reviewToken, evidence, committed, workingTreeAvailable: workingTree.available };\n}\n\nasync function previews(root: string, record: DecisionRecord, state: Awaited<ReturnType<typeof reviewState>>) {\n const access = await createFileAccess(root);\n const anchors = decisionAnchors(record);\n const candidates = [...new Set([...state.evidence.changedFiles, ...state.evidence.localChanges, ...anchors,\n ...(await access.list()).filter(file => anchors.some(anchor => anchorMatches(anchor, file))),\n ])];\n const files: Array<{ path: string; preview: string; totalLines: number }> = [];\n const omittedFiles: string[] = [];\n const diffPaths: string[] = [];\n for (const file of candidates) {\n if (files.length >= 6) { omittedFiles.push(file); continue; }\n const source = await access.read(file);\n if (!source) { omittedFiles.push(file); continue; }\n files.push({ path: source.path, preview: source.content.slice(0, 2000), totalLines: source.totalLines });\n if (state.evidence.changedFiles.includes(file)) diffPaths.push(file);\n }\n let diff: string | null = null;\n let diffUnavailable: string | undefined;\n if (state.evidence.historyAvailable && diffPaths.length) {\n try {\n const { stdout } = await exec(\"git\", [\"--literal-pathspecs\", \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", record.refreshedHash, state.evidence.headHash, \"--\", ...diffPaths], { cwd: root, maxBuffer: 1024 * 1024 });\n diff = stdout.slice(0, 16000);\n if (stdout.length > diff.length) diffUnavailable = \"Diff preview was truncated; inspect the full diff before reviewing.\";\n } catch { diffUnavailable = \"Diff preview could not be read within its size bound; inspect the diff separately.\"; }\n }\n return { files, diff, diffUnavailable, omittedFiles, hint: \"Bounded source and diff previews only. Deleted, excluded, sensitive, oversized, or additional files may be omitted. Inspect relevant evidence beyond these previews before recording a verdict.\" };\n}\n\n/** Prepare first, then attest to that exact record and committed code revision. */\nexport async function reviewDecision(root: string, input: ReviewDecisionInput) {\n const parsed = requestSchema.safeParse(input);\n if (!parsed.success) return { status: \"error\", error: parsed.error.message };\n const request = parsed.data;\n const read = async () => {\n const store = await loadDecisionStore(root);\n return { ...store, record: store.records.find(record => record.id === request.id) };\n };\n if (request.action === \"prepare\") {\n const { record, diagnostics } = await read();\n if (!record) return { status: \"error\", error: `No readable decision with id \"${request.id}\"`, diagnostics };\n const state = await reviewState(root, record);\n const operativeDecision = effectiveDecision(record);\n return {\n status: \"prepared\", record, ...(operativeDecision !== record ? { operativeDecision } : {}), provenance: decisionProvenance(record), ...state, diagnostics,\n previews: await previews(root, record, state),\n hint: \"Inspect the proposed content, operativeDecision, sources, history, and code changes. A pending proposal leaves the prior accepted revision operative; accepting it replaces that revision, and retirement withdraws the entire decision including its proposal. Evidence covers both revisions' anchors. Only record acceptance or reaffirmation when the user or cited team review has authorized it. Supply that reviewer's identity, a reason, and this reviewToken. Do not invent identities or infer agreement from unchanged code. Acceptance and reaffirmation require committed anchor changes; retirement is available independently. Missing old history remains visible in the event even if a reviewer establishes a new baseline at HEAD. Saved reviews are local assertions for normal PR review, not authenticated approvals.\",\n };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) return { status: \"error\", error: \"Prepare the review first, then provide reviewToken, reviewer, and note.\" };\n return withDecisionWrite(root, async () => {\n const { record: original, diagnostics } = await read();\n if (diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before recording a review.\", diagnostics };\n if (!original) return { status: \"error\", error: `No decision with id \"${request.id}\"` };\n const state = await reviewState(root, original);\n if (state.reviewToken !== request.reviewToken) return { status: \"conflict\", error: \"The decision or code revision changed after preparation. Prepare and inspect a new review.\" };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived decisions cannot be reviewed again; create a new proposal.\" };\n const approval = decisionApproval(original);\n if (request.action === \"accept\" && approval === \"accepted\") return { status: \"error\", error: \"This decision is already accepted. Use reaffirm to record a new review.\" };\n if (request.action === \"reaffirm\" && approval !== \"accepted\") return { status: \"error\", error: \"Only accepted decisions can be reaffirmed. Review and accept this proposal or legacy record first.\" };\n const now = new Date().toISOString();\n const record = importLegacy(original, now);\n if (request.action !== \"retire\") {\n if (!record.owner || !record.sources.length) return { status: \"error\", error: \"Acceptance requires an owner and at least one source. Add them with save_decision, then prepare a new review.\" };\n if (state.evidence.headHash === \"unknown\" || !state.workingTreeAvailable || state.evidence.localChanges.length) return { status: \"error\", error: \"Acceptance requires readable Git HEAD and working-tree evidence with no uncommitted anchor changes. Commit the anchor changes and prepare a new review.\", evidence: state.evidence };\n }\n const status = request.action === \"retire\" ? \"retired\" : \"active\";\n const nextApproval = request.action === \"retire\" ? record.approval : \"accepted\";\n const refreshedHash = request.action === \"retire\" ? record.refreshedHash : state.evidence.headHash;\n const event = { kind: request.action === \"accept\" ? \"accepted\" : request.action === \"reaffirm\" ? \"reaffirmed\" : \"retired\",\n at: now, actor: request.reviewer, note: request.note, revision: record.revision, content: decisionContent(record),\n approval: nextApproval, status, refreshedHash, evidence: state.evidence,\n } as const;\n const updated: ReviewedDecisionRecord = { ...record, status, approval: nextApproval, refreshedHash, updatedAt: now, history: [...record.history, event] };\n // Detect an external Git operation during review preparation, too.\n if ((await reviewState(root, original)).reviewToken !== state.reviewToken) return { status: \"conflict\", error: \"Code changed while the review was being recorded. Prepare a new review.\" };\n await saveDecisionRecord(root, updated);\n return { status: event.kind, id: record.id, event, hint: \"Review recorded locally. Review and commit the decision file through the normal project workflow.\" };\n });\n}\n","export const BATCH_SYSTEM_PROMPT = `You are Mason, building one piece of a larger concept-to-files map via a Map-Reduce pattern.\n\nYou are seeing ONE batch of files from this project — not the whole codebase. Other batches will be processed separately and merged with yours in a final reduce step.\n\nYour job for this batch: identify the features and flows that involve the files in this batch, and return a partial concept map.\n\nRespond with ONLY a JSON object. No markdown, no explanation, no code fences. Just the raw JSON. Same shape as the full map (\\`{\"features\": {...}, \"flows\": {...}}\\`).\n\nCRITICAL: name features in PRODUCT-NATURAL language (e.g., \"home screen\", \"authentication\", \"checkout\"). Do NOT add platform or layer suffixes — call both the Android and iOS home-screen files part of a feature named \"home screen\". This is what lets the reduce step merge platform variants from other batches into a single product feature.\n\nOther rules:\n- Only include files that you see in this batch. Don't predict files in other batches.\n- Use the FULL relative file paths exactly as given.\n- Classify each feature with a \"type\": \"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, configuration, logging, adapters, build tooling). When unsure, use \"capability\".\n- Each feature should have 1–8 files from this batch — partials can be narrow.\n- Flows in a partial only make sense if all their chain steps are in this batch. Skip flows that span batches; the reduce step will assemble them.\n- Include test files in \"tests\" when present in this batch.\n- Two views of the batch: FILE HEADERS (every file in the batch, skeleton-level) and REPRESENTATIVE BODIES (deeper read of a few for grounding). Use the bodies to learn the codebase's domain vocabulary; use the headers to know which files exist.`;\n\nexport const REDUCE_SYSTEM_PROMPT = `You are Mason, merging partial concept maps from a Map-Reduce pass into a single unified map.\n\nYou will receive an array of \\`partials\\`, each produced from one batch of files. Your job: merge them into one coherent concept-to-files map for the whole project.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\`. No markdown, no preamble.\n\nMerge rules:\n- If two partials use the same feature name (e.g., both have \"home screen\"), MERGE them — combine their \\`files\\` and \\`tests\\` arrays (dedupe), and reconcile descriptions by picking the more product-natural wording or merging the two.\n- If two partials use *near-duplicate* feature names that clearly refer to the same product concept (\"home screen\" vs \"home view\", \"auth\" vs \"authentication\"), merge them under the more product-natural name.\n- If a partial split what should be one feature by platform (\"home Android\" + \"home iOS\"), merge into a single platform-agnostic feature (\"home screen\").\n- Preserve each feature's \"type\" (\"capability\" or \"infrastructure\"). When merged partials disagree on a feature's type, prefer \"capability\". If a partial omitted the type, infer it: user-facing functionality is \"capability\"; internal plumbing with no end user (DI/service wiring, config, logging, adapters) is \"infrastructure\".\n- For flows that were skipped by partials because they span batches, reconstruct them when you can see the full chain across multiple partials.\n- Every file that appears in any partial MUST end up in some feature in the unified map. Don't silently drop files.\n- Feature descriptions in the final map should be 1–2 sentences, written for a product/PM audience — concrete and specific, but free of code-level detail.\n- Each feature should have 2–8 files. If merging produces a feature with 20+ files, consider whether it should be split into sub-features.`;\n\nexport function buildBatchPrompt(\n batch: {\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): string {\n const skeletonBlocks = batch.skeletons\n .map(\n (f) =>\n `--- ${f.path} ---\\n${f.content}${f.content.length >= 500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const sampleBlocks = batch.samples\n .map(\n (f) =>\n `=== ${f.path} (deeper read) ===\\n${f.content}${f.content.length >= 1500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const batchInfo = `Batch ${Math.floor(batch.offset / batch.batchSize) + 1}: files ${batch.offset + 1}–${batch.offset + batch.skeletons.length} of ${batch.totalFiles}.`;\n\n let prompt = `${batchInfo}\n\n=== FILE HEADERS (every file in this batch) ===\n\n${skeletonBlocks}\n\n=== REPRESENTATIVE BODIES (for grounding) ===\n\n${sampleBlocks}`;\n\n if (batch.testPairs && batch.testPairs.length > 0) {\n const testBlock = batch.testPairs\n .map((p) => `${p.test} → ${p.source}`)\n .join(\"\\n\");\n prompt += `\\n\\n=== TEST → SOURCE MAPPINGS (for this batch) ===\\n\\n${testBlock}`;\n }\n\n return prompt;\n}\n\nexport function buildReducePrompt(\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge the following ${partials.length} partial concept maps into a single unified map.\n\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\nexport const REFRESH_REDUCE_SYSTEM_PROMPT = `You are Mason, merging a scoped refresh into an existing concept-to-files map.\n\nOnly a subset of the project's files was re-analyzed (they changed since the map was built). You receive the existing full map, the list of re-analyzed file paths, and partial concept maps derived from ONLY those files.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\` — the COMPLETE updated map. No markdown, no preamble.\n\nMerge rules:\n- Entries in the existing map that reference none of the re-analyzed files: copy them through UNCHANGED.\n- Entries that reference re-analyzed files: update them using the partials — adjust descriptions, add new files, drop files that moved elsewhere.\n- Merge partial features into existing features when they're the same product concept, even if named slightly differently (\"auth\" vs \"authentication\") — keep the existing name unless the new one is clearly more product-natural.\n- Features whose files were all deleted or renamed away: remove them by omitting them from your output.\n- Every file that appears in any partial MUST end up in some feature. Don't silently drop files.\n- Do not invent or alter entries for files you haven't seen.`;\n\nexport function buildRefreshReducePrompt(\n existingMap: {\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n },\n refreshedFiles: string[],\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge this scoped refresh into the existing concept map.\n\n=== EXISTING MAP ===\n${JSON.stringify(existingMap, null, 2)}\n\n=== RE-ANALYZED FILES ===\n${refreshedFiles.join(\"\\n\")}\n\n=== PARTIALS (derived from the re-analyzed files only) ===\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\n","import { withSnapshotWrite } from \"./lock.js\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\nimport { featureSchema, flowSchema } from \"./snapshot.js\";\nimport type { FeatureEntry, FlowEntry } from \"./snapshot.js\";\n\nexport interface Partial {\n batchId: string;\n offset: number;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n savedAt: string;\n}\n\nconst DIRECTORY = \".mason/partial-snapshots\";\nconst partialSchema = z.object({\n batchId: z.string().regex(/^[a-zA-Z0-9_-]+$/), offset: z.number().int().nonnegative(),\n features: z.record(featureSchema), flows: z.record(flowSchema), savedAt: z.string(),\n});\nconst scopeSchema = z.object({ files: z.array(z.string()), savedAt: z.string() });\n\nexport async function savePartial(rootDir: string, partial: Partial): Promise<void> {\n if (!/^[a-zA-Z0-9_-]+$/.test(partial.batchId)) throw new Error(`Invalid batchId: ${partial.batchId}`);\n await withSnapshotWrite(rootDir, () => writeStoreJson(rootDir, `${DIRECTORY}/${partial.batchId}.json`, partialSchema.parse(partial)));\n}\n\nexport async function loadAllPartials(rootDir: string): Promise<Partial[]> {\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, DIRECTORY)); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n const partials: Partial[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry === \"scope.json\") continue;\n const partial = partialSchema.parse(await readStoreJson(rootDir, `${DIRECTORY}/${entry}`));\n if (entry !== `${partial.batchId}.json`) throw new Error(`Invalid partial filename: ${entry}`);\n partials.push(partial);\n }\n return partials.sort((a, b) => a.offset - b.offset);\n}\n\nexport async function saveScope(rootDir: string, files: string[]): Promise<void> {\n await withSnapshotWrite(rootDir, () => writeStoreJson(rootDir, `${DIRECTORY}/scope.json`, { files, savedAt: new Date().toISOString() }));\n}\n\nexport async function loadScope(rootDir: string): Promise<string[] | null> {\n const raw = await readStoreJson(rootDir, `${DIRECTORY}/scope.json`);\n return raw === null ? null : scopeSchema.parse(raw).files;\n}\n\nexport async function clearScope(rootDir: string): Promise<void> {\n await withSnapshotWrite(rootDir, async () => {\n await fs.rm(await storePath(rootDir, `${DIRECTORY}/scope.json`), { force: true });\n });\n}\n\n/** Called only after a snapshot commit, while updateSnapshot holds the write lock. */\nexport async function clearAllPartials(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, DIRECTORY), { recursive: true, force: true });\n}\n\nexport function batchIdFor(offset: number): string {\n return `batch-${String(offset).padStart(6, \"0\")}`;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { withLock } from \"../automation/store.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { standaloneLocation, automaticUpdatesAllowed, currentInstallation, newerStableVersion, readInstallation, type InstallRecord } from \"./state.js\";\nimport { verifyBundle } from \"./bundle.js\";\nimport { pruneUnusedVersions } from \"./runtime.js\";\nimport { prepareStandaloneMcp } from \"./install.js\";\n\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\nexport const RELEASE_AGE_MS = 24 * 60 * 60 * 1000;\nconst releaseBase = \"https://github.com/adrianczuczka/mason/releases\";\nconst releaseListSchema = z.array(z.object({ tag_name: z.string(), draft: z.boolean(), prerelease: z.boolean(), published_at: z.string().nullable() }));\nexport const updateManifestSchema = z.object({\n format: z.literal(1), version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/), publishedAt: z.string().datetime(),\n assets: z.record(z.string().regex(/^[a-f0-9]{64}$/)),\n}).strict();\nconst statusSchema = z.object({ lastAttempt: z.number(), availableVersion: z.string().optional(), error: z.string().optional() });\n\nasync function boundedDownload(url: string): Promise<Buffer> {\n const response = await fetch(url, { signal: AbortSignal.timeout(15000), redirect: \"follow\" });\n if (!response.ok || !response.body) throw new Error(`Update metadata request failed (HTTP ${response.status}).`);\n if (Number(response.headers.get(\"content-length\")) > 1024 * 1024) throw new Error(\"Update metadata is too large.\");\n const reader = response.body.getReader(), chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n size += value.length;\n if (size > 1024 * 1024) throw new Error(\"Update metadata is too large.\");\n chunks.push(value);\n }\n } finally { await reader.cancel(); }\n return Buffer.concat(chunks);\n}\n\n/** Bind both the release contents and exact tag workflow identity before using a download hash. */\nexport async function fetchVerifiedRelease(home: string, now = Date.now()) {\n // Select the newest eligible release, not just /latest: daily releases must\n // not keep every automatic update perpetually inside the waiting period.\n const releases = releaseListSchema.parse(JSON.parse((await boundedDownload(\"https://api.github.com/repos/adrianczuczka/mason/releases?per_page=30\")).toString(\"utf8\")));\n const installed = (await readInstallation(home)).version;\n let selected: string | undefined;\n for (const release of releases) {\n const version = release.tag_name.replace(/^v/, \"\");\n if (release.tag_name !== \"v\" + version || release.draft || release.prerelease || !release.published_at\n || !(now - Date.parse(release.published_at) >= RELEASE_AGE_MS) || !newerStableVersion(version, installed)) continue;\n if (!selected || newerStableVersion(version, selected)) selected = version;\n }\n if (!selected) return null;\n const bytes = await boundedDownload(`${releaseBase}/download/v${selected}/update.json`);\n const manifest = updateManifestSchema.parse(JSON.parse(bytes.toString(\"utf8\")));\n if (manifest.version !== selected) throw new Error(\"Signed manifest does not match the selected release.\");\n const signature = JSON.parse((await boundedDownload(`${releaseBase}/download/v${manifest.version}/update.sigstore.json`)).toString(\"utf8\"));\n // DSSE verifies its embedded payload, ignoring an external artifact argument.\n // Accept only detached message signatures that bind these exact manifest bytes.\n if (!signature?.messageSignature || signature.dsseEnvelope) throw new Error(\"Update metadata requires a detached message signature.\");\n const { verify } = await import(\"sigstore\");\n await verify(signature, bytes, {\n certificateIdentityURI: `https://github.com/adrianczuczka/mason/.github/workflows/publish.yml@refs/tags/v${manifest.version}`,\n certificateIssuer: \"https://token.actions.githubusercontent.com\",\n tufCachePath: await storePath(home, \"sigstore-cache\"), timeout: 10000, retry: 0,\n ctLogThreshold: 1, tlogThreshold: 1,\n });\n return manifest;\n}\n\nasync function runInstaller(home: string, version: string, digest: string, revision: string) {\n const record = await readInstallation(home);\n const bundle = await storePath(home, \"versions/\" + record.current);\n await verifyBundle(bundle);\n const windows = process.platform === \"win32\", script = path.join(bundle, windows ? \"install.ps1\" : \"install.sh\");\n await new Promise<void>((resolve, reject) => {\n const child = spawn(windows ? \"powershell.exe\" : \"sh\", windows\n ? [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script] : [script], {\n cwd: home, windowsHide: true, stdio: [\"ignore\", \"ignore\", \"pipe\"], timeout: 10 * 60 * 1000,\n env: { ...process.env, MASON_HOME: home, MASON_BIN_DIR: record.bin, MASON_VERSION: version,\n MASON_RELEASE_BASE: \"\", MASON_EXPECTED_SHA256: digest, MASON_UPDATE_POLICY_REVISION: revision },\n });\n let diagnostic = \"\";\n child.stderr!.on(\"data\", bytes => { diagnostic = (diagnostic + bytes).slice(-4000); });\n child.on(\"error\", reject);\n child.on(\"close\", code => code === 0 ? resolve() : reject(new Error(`Update download failed (${code}): ${diagnostic.trim()}`)));\n });\n}\n\n/** Separate worker: no inherited MCP/hook streams, one attempt per installation per day. */\nexport async function runAutomaticUpdate(home: string, dependencies = { fetchRelease: fetchVerifiedRelease, install: runInstaller }, now = Date.now()) {\n await withLock(home, \".update-lock\", async () => {\n const record = await readInstallation(home);\n if (!automaticUpdatesAllowed(record)) return;\n const old = statusSchema.safeParse(await readStoreJson(home, \"update-status.json\"));\n if (old.success && now - old.data.lastAttempt < CHECK_INTERVAL_MS && old.data.lastAttempt <= now) return;\n const status: z.infer<typeof statusSchema> = { lastAttempt: now };\n await writeStoreJson(home, \"update-status.json\", status);\n try {\n await pruneUnusedVersions(home).catch(() => {});\n const release = await dependencies.fetchRelease(home);\n if (!release) return;\n status.availableVersion = release.version;\n const age = now - Date.parse(release.publishedAt);\n if (age >= RELEASE_AGE_MS && newerStableVersion(release.version, record.version)\n && (!record.pending || newerStableVersion(release.version, record.pending.version))) {\n const asset = `mason-${process.platform}-${process.arch}.${process.platform === \"win32\" ? \"zip\" : \"tar.gz\"}`;\n const digest = release.assets[asset];\n if (!digest) throw new Error(\"Signed release has no archive for this platform.\");\n // Users may disable, pin, manually upgrade, or uninstall while network requests run.\n const fresh = await readInstallation(home);\n if (automaticUpdatesAllowed(fresh) && fresh.updates?.revision === record.updates!.revision\n && newerStableVersion(release.version, fresh.version)) {\n await dependencies.install(home, release.version, digest, record.updates!.revision);\n }\n }\n } catch (error) { status.error = error instanceof Error ? error.message : String(error); }\n // Do not recreate an installation removed while the worker was downloading.\n if (await fs.access(path.join(home, \"install.json\")).then(() => true, () => false)) await writeStoreJson(home, \"update-status.json\", status);\n }, 0);\n}\n\nexport async function scheduleAutomaticUpdate(): Promise<void> {\n try {\n const { home, record } = await currentInstallation();\n if (!automaticUpdatesAllowed(record)) return;\n const status = statusSchema.safeParse(await readStoreJson(home, \"update-status.json\"));\n const now = Date.now();\n if (status.success && status.data.lastAttempt <= now && now - status.data.lastAttempt < CHECK_INTERVAL_MS) return;\n const bundle = await storePath(home, \"versions/\" + record.current);\n const child = spawn(path.join(bundle, process.platform === \"win32\" ? \"node.exe\" : \"node\"),\n [path.join(bundle, \"app/dist/mason.js\"), \"internal-update\"],\n { cwd: home, env: process.env, stdio: \"ignore\", detached: true, windowsHide: true });\n child.on(\"error\", () => {});\n child.unref();\n } catch { /* npm, offline, read-only, or damaged installations must still run. */ }\n}\n\nexport async function updateSettings(home: string, action: \"enable\" | \"disable\" | \"pin\" | \"unpin\") {\n return withLock(home, \".install-lock\", async () => {\n const record = await readInstallation(home);\n const updates: NonNullable<InstallRecord[\"updates\"]> = { ...(record.updates ?? { enabled: false }), revision: randomUUID() };\n if (action === \"enable\") updates.enabled = true;\n if (action === \"disable\") updates.enabled = false;\n if (action === \"pin\") updates.pinnedVersion = record.version;\n if (action === \"unpin\") delete updates.pinnedVersion;\n record.updates = updates;\n delete record.pending;\n await writeStoreJson(home, \"install.json\", record);\n return record;\n });\n}\n\nexport async function updateStatus(home: string) {\n const record = await readInstallation(home);\n const lastCheck = statusSchema.parse(await readStoreJson(home, \"update-status.json\") ?? { lastAttempt: 0 });\n return { version: record.version, enabled: record.updates?.enabled ?? false,\n effective: automaticUpdatesAllowed(record), pinnedVersion: record.updates?.pinnedVersion ?? null,\n mirror: record.updates?.mirror ?? null, pendingVersion: record.pending?.version ?? null,\n lastCheck: lastCheck.lastAttempt ? lastCheck : null };\n}\n\n/** The MCP process holds a lease for its lifetime; pending versions activate before the first new server. */\nexport async function startMcpWithUpdates(start: (onClose?: () => void) => Promise<void>) {\n const current = standaloneLocation();\n if (!current) { await start(); return; }\n // A standalone server must never run without a lease: another process could\n // otherwise treat it as idle and activate an update underneath that server.\n const session = await prepareStandaloneMcp(current.home);\n if (session.bundle !== current.bundle) {\n const child = spawn(path.join(session.bundle, process.platform === \"win32\" ? \"node.exe\" : \"node\"),\n [path.join(session.bundle, \"app/dist/mason-mcp.js\"), ...process.argv.slice(2)], { stdio: \"inherit\", windowsHide: true });\n const interrupt = () => { child.kill(\"SIGINT\"); }, terminate = () => { child.kill(\"SIGTERM\"); };\n process.on(\"SIGINT\", interrupt); process.on(\"SIGTERM\", terminate);\n try {\n process.exitCode = await new Promise<number>((resolve, reject) => {\n child.on(\"error\", reject); child.on(\"exit\", code => resolve(code ?? 1));\n });\n } finally {\n process.off(\"SIGINT\", interrupt); process.off(\"SIGTERM\", terminate);\n await session.release();\n }\n return;\n }\n const timer = setInterval(() => { void scheduleAutomaticUpdate(); }, 60 * 60 * 1000);\n timer.unref();\n const stop = () => { clearInterval(timer); void session?.release(); };\n try { await start(stop); void scheduleAutomaticUpdate(); }\n catch (error) { stop(); throw error; }\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { pathChangeSchema } from \"./path.js\";\n\nexport const releaseVersion = z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/);\nconst bundleId = z.string().regex(/^[a-f0-9]{24}$/);\nexport const updatePolicySchema = z.object({\n enabled: z.boolean(), revision: z.string(), pinnedVersion: releaseVersion.optional(), mirror: z.string().optional(),\n});\nexport const recordSchema = z.object({\n format: z.literal(1), home: z.string(), bin: z.string(), current: bundleId, version: releaseVersion,\n launchers: z.record(z.string()), previousLaunchers: z.record(z.string()).optional(),\n pathChanges: z.array(pathChangeSchema).optional(), updates: updatePolicySchema.optional(),\n previous: z.object({ id: bundleId, version: releaseVersion }).optional(),\n pending: z.object({ id: bundleId, version: releaseVersion, policyRevision: z.string() }).optional(),\n});\nexport type InstallRecord = z.infer<typeof recordSchema>;\nexport const defaultHome = () => process.env.MASON_HOME ?? (process.platform === \"win32\"\n ? path.join(process.env.LOCALAPPDATA ?? os.homedir(), \"Mason\") : path.join(os.homedir(), \".local/share/mason\"));\n\nexport async function readInstallation(home: string): Promise<InstallRecord> {\n const raw = await readStoreJson(home, \"install.json\");\n if (!raw) throw new Error(\"Run this command from a standalone installation. npm users can upgrade with npm.\");\n const record = recordSchema.parse(raw);\n if (record.home !== await fs.realpath(home)) throw new Error(\"Invalid standalone installation receipt.\");\n return record;\n}\n\nexport function standaloneLocation() {\n // Distribution modules are bundled into app/dist/mason.js (or mason-mcp.js).\n const bundle = path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"../..\");\n const home = path.dirname(path.dirname(bundle));\n if (path.dirname(bundle) !== path.join(home, \"versions\") || !/^[a-f0-9]{24}$/.test(path.basename(bundle))) {\n return null;\n }\n return { home, bundle };\n}\n\nexport async function currentInstallation() {\n const location = standaloneLocation();\n if (!location) throw new Error(\"Run this command from a standalone installation. npm users can upgrade with npm.\");\n const { home, bundle } = location;\n const record = await readInstallation(home);\n return { home, bundle, record };\n}\n\nexport function automaticUpdatesAllowed(record: InstallRecord, env: NodeJS.ProcessEnv = process.env): boolean {\n return record.updates?.enabled === true && !record.updates.pinnedVersion && !record.updates.mirror\n && !env.CI && env.MASON_NO_AUTO_UPDATE !== \"1\" && !env.MASON_RELEASE_BASE && !env.MASON_VERSION;\n}\n\n/** Automatic updates accept stable releases only and never downgrade. */\nexport function newerStableVersion(candidate: string, installed: string): boolean {\n if (!/^\\d+\\.\\d+\\.\\d+$/.test(candidate)) return false;\n const a = candidate.split(\".\").map(BigInt), b = installed.split(\"-\")[0].split(\".\").map(BigInt);\n for (let i = 0; i < 3; i++) { if (a[i] !== b[i]) return a[i] > b[i]; }\n return installed.includes(\"-\");\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\n\nconst execute = promisify(execFile);\nexport const pathChangeSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"profile\"), file: z.string(), block: z.string(), created: z.boolean() }),\n z.object({ kind: z.literal(\"windows\"), entry: z.string(), created: z.boolean() }),\n]);\nexport type PathChange = z.infer<typeof pathChangeSchema>;\nexport type PathResult = { status: \"configured\" | \"manual\"; message: string; changes: PathChange[] };\nexport type PathOptions = { platform?: NodeJS.Platform; userHome?: string; env?: NodeJS.ProcessEnv };\nconst quote = (s: string) => \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n\n// Store the ownership intent before changing settings, so interrupted installs\n// can resume and uninstall can distinguish our addition from existing settings.\nexport async function configurePath(bin: string, previous: PathChange[], save: (changes: PathChange[]) => Promise<void>, options: PathOptions = {}): Promise<PathResult> {\n const env = options.env ?? process.env, platform = options.platform ?? process.platform;\n const changes = [...previous];\n // Profile/registry changes affect future shells. The inherited PATH tells us\n // whether this terminal already has the installation directory available.\n const currentPath = platform === \"win32\" ? Object.entries(env).find(([key]) => key.toLowerCase() === \"path\")?.[1] : env.PATH;\n const alreadyOnPath = platform === \"win32\" ? hasWindowsEntry(currentPath ?? null, bin, env)\n : (currentPath ?? \"\").split(\":\").some(entry => path.posix.isAbsolute(entry) && path.posix.resolve(entry) === path.posix.resolve(bin));\n const setupHint = \"To connect a project, run one of these inside its directory:\\n Codex: mason setup --host codex\\n Claude Code: mason setup --host claude\";\n const message = (alreadyOnPath ? \"\" : \"Open a new terminal to use mason.\\n\") + setupHint;\n const manual = (reason: string): PathResult => ({ status: \"manual\", changes, message: `${reason}\\n${alreadyOnPath ? \"\" : `Add ${bin} to your PATH.\\n`}${setupHint}` });\n if (env.MASON_NO_MODIFY_PATH === \"1\") return manual(\"Automatic PATH setup is disabled (MASON_NO_MODIFY_PATH=1).\");\n if (/[\\r\\n\\0]/.test(bin) || bin.includes(platform === \"win32\" ? \";\" : \":\")) return manual(\"This installation path cannot be represented safely in PATH.\");\n try {\n if (platform === \"win32\") {\n const current = await windowsPath(\"read\");\n if (!hasWindowsEntry(current.value, bin)) {\n if (!changes.some(c => c.kind === \"windows\" && c.entry === bin)) {\n changes.push({ kind: \"windows\", entry: bin, created: current.value === null }); await save(changes);\n }\n await windowsPath(\"add\", bin, current);\n }\n return { status: \"configured\", changes, message };\n }\n const shell = path.basename(env.SHELL ?? os.userInfo().shell ?? \"\");\n const userHome = options.userHome ?? os.homedir();\n let profiles: string[];\n if (![\"bash\", \"zsh\", \"sh\"].includes(shell)) return manual(`Automatic PATH setup is unavailable for ${shell || \"an unknown shell\"}.`);\n if (env.MASON_PROFILE) profiles = [path.resolve(env.MASON_PROFILE)];\n else if (shell === \"zsh\") profiles = [path.join(env.ZDOTDIR || userHome, \".zshrc\")];\n else if (shell === \"sh\") profiles = [path.join(userHome, \".profile\")];\n else {\n const candidates = [\".bash_profile\", \".bash_login\", \".profile\"].map(name => path.join(userHome, name));\n let login = candidates[2];\n for (const file of candidates) if (await fs.lstat(file).then(() => true, error => { if (error.code === \"ENOENT\") return false; throw error; })) { login = file; break; }\n profiles = [path.join(userHome, \".bashrc\"), login];\n }\n const marker = `# >>> mason PATH ${createHash(\"sha256\").update(bin).digest(\"hex\").slice(0, 12)} >>>`;\n for (const profile of profiles) {\n // Preserve symlinked dotfiles by updating their target. A dangling link is\n // an error, not permission to replace the link with an unrelated file.\n const stat = await fs.lstat(profile).catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n const file = stat?.isSymbolicLink() ? await fs.realpath(profile) : path.resolve(profile);\n const original = await fs.readFile(file).catch(error => { if (error.code === \"ENOENT\" && !stat) return null; throw error; });\n if (original && !Buffer.from(original.toString(\"utf8\")).equals(original)) return manual(`Shell profile is not UTF-8: ${profile}.`);\n const text = original?.toString(\"utf8\") ?? \"\";\n const owned = changes.find((c): c is Extract<PathChange, { kind: \"profile\" }> => c.kind === \"profile\" && c.file === file);\n if (owned && text.includes(owned.block)) continue;\n if (text.includes(marker) || (owned && text.includes(\"# <<< mason PATH\"))) return manual(`Mason's PATH block was edited; retained ${profile}.`);\n const newline = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const block = owned?.block ?? (\"\\n\" + marker + \"\\ncase \\\":${PATH-}:\\\" in\\n *:\" + quote(bin) + \":*) ;;\\n *) export PATH=\" + quote(bin) + \":\\\"${PATH-}\\\" ;;\\nesac\\n# <<< mason PATH <<<\\n\").replaceAll(\"\\n\", newline);\n if (!owned) { changes.push({ kind: \"profile\", file, block, created: original === null }); await save(changes); }\n await fs.mkdir(path.dirname(file), { recursive: true });\n // Append without rewriting existing bytes, modes or symlinks. Recheck the\n // bytes on the opened file to detect edits since the preflight read.\n const handle = await fs.open(file, original === null ? \"ax+\" : \"a+\", 0o600);\n try {\n if (!(await handle.readFile()).equals(original ?? Buffer.alloc(0))) throw new Error(`Shell profile changed during installation: ${profile}`);\n await handle.writeFile(block); await handle.sync();\n } finally { await handle.close(); }\n }\n return { status: \"configured\", changes, message };\n } catch (error) { return manual(`Could not configure PATH: ${error instanceof Error ? error.message : String(error)}`); }\n}\n\nexport async function removePath(changes: PathChange[]): Promise<string[]> {\n const warnings: string[] = [];\n for (const change of changes) {\n try {\n if (change.kind === \"windows\") {\n const current = await windowsPath(\"read\");\n if (!(current.value ?? \"\").split(\";\").includes(change.entry) && hasWindowsEntry(current.value, change.entry)) throw new Error(\"PATH entry was edited\");\n await windowsPath(\"remove\", change.entry, current, change.created); continue;\n }\n const stat = await fs.lstat(change.file).catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n if (!stat) continue;\n if (!stat.isFile()) throw new Error(\"profile type changed\");\n const bytes = await fs.readFile(change.file), text = bytes.toString(\"utf8\");\n if (!Buffer.from(text).equals(bytes)) throw new Error(\"profile encoding changed\");\n const index = text.indexOf(change.block);\n if (index < 0 || text.indexOf(change.block, index + change.block.length) >= 0) throw new Error(\"PATH block was edited or removed\");\n const prefix = text.slice(0, index), suffix = text.slice(index + change.block.length);\n const separator = prefix && suffix && !prefix.endsWith(\"\\n\") ? (change.block.startsWith(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\") : \"\";\n const next = Buffer.from(prefix + separator + suffix);\n const temporary = change.file + \".mason-\" + randomUUID();\n try {\n if (stat.nlink > 1) throw new Error(\"profile has multiple hard links\");\n const handle = await fs.open(temporary, \"wx\", stat.mode & 0o777);\n try {\n await handle.writeFile(next); await handle.chmod(stat.mode & 0o777);\n if (process.platform !== \"win32\") await handle.chown(stat.uid, stat.gid);\n await handle.sync();\n } finally { await handle.close(); }\n const current = await fs.lstat(change.file);\n if (!current.isFile() || current.ino !== stat.ino || !(await fs.readFile(change.file)).equals(bytes)) throw new Error(\"profile changed during uninstall\");\n await fs.rename(temporary, change.file);\n } finally { await fs.rm(temporary, { force: true }); }\n // Empty created profiles are harmless; retain them to avoid masking any\n // dotfile another process created or linked since installation.\n } catch (error) { warnings.push(`Retained PATH setting ${change.kind === \"profile\" ? change.file : change.entry}: ${error instanceof Error ? error.message : String(error)}`); }\n }\n return warnings;\n}\n\nexport type WindowsPath = { value: string | null; kind: string | null };\nconst normalizeWindowsEntry = (value: string) => path.win32.normalize(value.trim().replace(/^\"(.*)\"$/, \"$1\")).replace(/[\\\\/]+$/, \"\").toLowerCase();\nexport const hasWindowsEntry = (value: string | null, entry: string, env: NodeJS.ProcessEnv = process.env) => {\n const variables = new Map(Object.entries(env).map(([key, value]) => [key.toLowerCase(), value]));\n const expand = (part: string) => part.replace(/%([^%]+)%/g, (match, key: string) => variables.get(key.toLowerCase()) ?? match);\n return (value ?? \"\").split(\";\").some(part => normalizeWindowsEntry(expand(part)) === normalizeWindowsEntry(entry));\n};\n\n// Read unexpanded registry text and preserve its value kind. No machine PATH,\n// setx truncation, or expanded copy of the process environment is written.\nexport async function windowsPath(action: \"read\" | \"add\" | \"remove\", entry = \"\", expected?: WindowsPath, removeEmpty = false): Promise<WindowsPath> {\n const payload = Buffer.from(JSON.stringify({ action, entry, expected, removeEmpty })).toString(\"base64\");\n const script = `$ErrorActionPreference = 'Stop'\n[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)\n$p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${payload}')) | ConvertFrom-Json\n$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')\ntry {\n $value = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)\n $kind = if ($null -eq $value) { $null } else { $key.GetValueKind('Path').ToString() }\n if ($null -ne $kind -and $kind -notin @('String','ExpandString')) { throw 'User PATH is not a string.' }\n if ($p.action -eq 'read') { @{ value = $value; kind = $kind } | ConvertTo-Json -Compress; exit 0 }\n if ($p.expected -and ($value -cne $p.expected.value -or $kind -cne $p.expected.kind)) { throw 'User PATH changed concurrently; retry the operation.' }\n $parts = if ($null -eq $value -or $value -eq '') { @() } else { @($value.Split(';')) }\n if ($p.action -eq 'add') { $next = (@($p.entry) + $parts) -join ';' }\n else { $next = (@($parts | Where-Object { $_ -cne $p.entry })) -join ';' }\n if ($next -cne $value) {\n $writeKind = if ($kind) { [Microsoft.Win32.RegistryValueKind]$kind } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }\n if ($p.action -eq 'remove' -and $p.removeEmpty -and $next -eq '') { $key.DeleteValue('Path', $false) }\n else { $key.SetValue('Path', $next, $writeKind) }\n Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class MasonEnvironment { [DllImport(\"user32.dll\", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, UIntPtr w, string l, uint f, uint t, out UIntPtr r); }'\n $result = [UIntPtr]::Zero\n [void][MasonEnvironment]::SendMessageTimeout([IntPtr]0xffff, 0x1a, [UIntPtr]::Zero, 'Environment', 2, 1000, [ref]$result)\n }\n @{ value = $next; kind = $kind } | ConvertTo-Json -Compress\n} finally { $key.Dispose() }\n`;\n const { stdout } = await execute(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", Buffer.from(script, \"utf16le\").toString(\"base64\")], { windowsHide: true, timeout: 15000, maxBuffer: 1024 * 1024 });\n return JSON.parse(stdout.replace(/^\\uFEFF/, \"\").trim());\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { storePath } from \"../utils/storage.js\";\n\nexport const targets = [\"darwin-arm64\", \"darwin-x64\", \"linux-arm64\", \"linux-x64\", \"win32-arm64\", \"win32-x64\"] as const;\nconst digest = z.string().regex(/^[a-f0-9]{64}$/);\nexport const bundleSchema = z.object({\n format: z.literal(1), version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/),\n target: z.enum(targets), nodeVersion: z.string(), files: z.record(digest),\n}).strict();\nexport const sha256 = (bytes: Buffer | string) => createHash(\"sha256\").update(bytes).digest(\"hex\");\n\nexport async function readBundle(root: string) {\n const bytes = await fs.readFile(await storePath(root, \"bundle.json\"));\n const manifest = bundleSchema.parse(JSON.parse(bytes.toString(\"utf8\")));\n const windows = manifest.target.startsWith(\"win32-\");\n for (const file of Object.keys(manifest.files)) {\n if (file.includes(\"\\\\\") || file.split(\"/\").some(p => !p || p === \".\" || p === \"..\") || path.isAbsolute(file)) {\n throw new Error(\"Unsafe path in Mason bundle: \" + file);\n }\n }\n for (const required of [windows ? \"node.exe\" : \"node\", \"app/package.json\", \"app/dist/mason.js\", \"app/dist/mason-auto.js\", \"app/dist/mason-mcp.js\"]) {\n if (!manifest.files[required]) throw new Error(\"Incomplete Mason bundle: \" + required);\n }\n return { manifest, manifestHash: sha256(bytes) };\n}\n\n/** Verify every shipped file before copying or selecting a standalone distribution. */\nexport async function verifyBundle(root: string, expectedHash?: string) {\n const bundle = await readBundle(root);\n if (expectedHash && bundle.manifestHash !== expectedHash) throw new Error(\"Mason bundle manifest changed.\");\n if (bundle.manifest.target !== `${process.platform}-${process.arch}`) throw new Error(\"Mason bundle is for another platform. Install this platform's bundle and rerun setup.\");\n const files = Object.keys(bundle.manifest.files);\n // Bound concurrent reads; Node itself is a large file.\n for (let i = 0; i < files.length; i += 8) await Promise.all(files.slice(i, i + 8).map(async file => {\n if (sha256(await fs.readFile(await storePath(root, file))) !== bundle.manifest.files[file]) throw new Error(\"Mason bundle checksum mismatch: \" + file);\n }));\n return bundle;\n}\n","import fs from \"node:fs/promises\";\nimport { unlinkSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { withLock } from \"../automation/store.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readInstallation, standaloneLocation } from \"./state.js\";\nimport { verifyBundle } from \"./bundle.js\";\n\nconst leaseSchema = z.object({ pid: z.number().int().positive(), host: z.string(), bundle: z.string().regex(/^[a-f0-9]{24}$/) });\n\n/** Every standalone entry point registers before executing application code. */\nexport async function registerRuntime() {\n const location = standaloneLocation();\n if (!location) return;\n const { home, bundle } = location;\n const name = `runtimes/${randomUUID()}.json`;\n await withLock(home, \".install-lock\", async () => {\n await readInstallation(home);\n await fs.access(bundle);\n await writeStoreJson(home, name, { pid: process.pid, host: os.hostname(), bundle: path.basename(bundle) });\n });\n const file = await storePath(home, name);\n process.once(\"exit\", () => { try { unlinkSync(file); } catch { /* Stale leases are recovered by the next worker. */ } });\n}\n\n/** Caller holds the update lock, before staging starts; startup shares the install lock. */\nexport async function pruneUnusedVersions(home: string) {\n // Full bundle verification and recursive deletion can be slow. Keep them\n // outside the lock needed by commands and new MCP sessions.\n const versions = await storePath(home, \"versions\");\n const candidates: { id: string; directory: string; retired: boolean }[] = [];\n const initial = await readInstallation(home);\n const initialKeep = new Set([initial.current, initial.previous?.id, initial.pending?.id]);\n for (const name of await fs.readdir(versions)) {\n const retired = /^\\.retired-([a-f0-9]{24})-[a-f0-9-]+$/.exec(name);\n const id = retired?.[1] ?? name;\n if (!/^[a-f0-9]{24}$/.test(id) || initialKeep.has(id)) continue;\n try {\n const directory = await storePath(home, `versions/${name}`);\n await fs.access(await storePath(directory, \"app/dist/mason-runtime.js\"));\n const bundle = await verifyBundle(directory);\n if (bundle.manifestHash.slice(0, 24) === id && bundle.manifest.files[\"app/dist/mason-runtime.js\"])\n candidates.push({ id, directory, retired: !!retired });\n } catch { /* Legacy, edited, or unknown bundles remain untouched. */ }\n }\n if (!candidates.length) return;\n const garbage: string[] = [];\n await withLock(home, \".install-lock\", async () => {\n const record = await readInstallation(home);\n const keep = new Set([record.current, record.previous?.id, record.pending?.id]);\n const directory = await storePath(home, \"runtimes\");\n const leases = await fs.readdir(directory).catch(error => { if (error.code === \"ENOENT\") return []; throw error; });\n for (const name of leases) {\n if (!/^[a-f0-9-]+\\.json$/.test(name)) return;\n try {\n const raw = await readStoreJson(home, `runtimes/${name}`);\n if (raw === null) continue;\n const lease = leaseSchema.parse(raw);\n if (lease.host !== os.hostname()) return;\n try { process.kill(lease.pid, 0); keep.add(lease.bundle); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") return;\n await fs.rm(await storePath(home, `runtimes/${name}`), { force: true });\n }\n } catch { return; } // Uncertain process ownership means no deletion.\n }\n for (const candidate of candidates) {\n if (keep.has(candidate.id)) continue;\n try {\n const retired = candidate.retired ? candidate.directory\n : await storePath(home, `versions/.retired-${candidate.id}-${randomUUID()}`);\n if (!candidate.retired) await fs.rename(candidate.directory, retired);\n garbage.push(retired);\n } catch { /* Busy files remain available for the next check. */ }\n }\n });\n for (const directory of garbage) await fs.rm(directory, { recursive: true }).catch(() => {});\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { execFile, spawn } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { randomUUID } from \"node:crypto\";\nimport { verifyBundle } from \"./bundle.js\";\nimport { storePath, readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { withLock } from \"../automation/store.js\";\nimport { configurePath, removePath } from \"./path.js\";\nimport type { Progress } from \"../utils/progress.js\";\nimport { automaticUpdatesAllowed, currentInstallation, defaultHome, newerStableVersion, readInstallation, recordSchema, type InstallRecord } from \"./state.js\";\nimport { hasRunningMcp, registerMcp } from \"./sessions.js\";\n\nexport { defaultHome } from \"./state.js\";\nconst shQuote = (s: string) => \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\nconst psQuote = (s: string) => \"'\" + s.replace(/'/g, \"''\") + \"'\";\n// Leave batch context before invoking PowerShell, as npm's cmd-shim does. A\n// continuing batch can lose the child exit code or reopen its deleted launcher.\n// https://github.com/npm/cmd-shim/blob/main/lib/index.js\nexport const WINDOWS_BATCH_LAUNCHER = '@echo off\\r\\ngoto #_mason_handoff_# 2>NUL || title %COMSPEC% & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"%~dp0mason-launcher.ps1\" %*\\r\\n';\nconst launcherNames = [\"mason\", \"mason.cmd\", \"mason.ps1\", \"mason-launcher.ps1\"];\n\nasync function replace(file: string, content: string, mode = 0o600) {\n const temp = file + \".tmp-\" + randomUUID();\n try { await fs.writeFile(temp, content, { mode, flag: \"wx\" }); await fs.rename(temp, file); }\n finally { await fs.rm(temp, { force: true }); }\n}\n\n/** User installation only. Project runtimes and host trust remain independent. */\nexport interface InstallOptions { stageOnly?: boolean; policyRevision?: string; preservePolicy?: boolean; rollback?: boolean }\n\nexport async function installStandalone(source: string, progress?: Progress, options: InstallOptions = {}) {\n progress?.step(\"Checking installation files and location\");\n const bundle = await verifyBundle(source);\n const selectedHome = path.resolve(defaultHome());\n if (!options.stageOnly) await fs.mkdir(selectedHome, { recursive: true });\n const home = await fs.realpath(selectedHome);\n if (options.stageOnly) {\n assertUpdatePolicy(await readInstallation(home), bundle.manifest.version, options.policyRevision);\n const destination = await storePath(home, \"versions/\" + bundle.manifestHash.slice(0, 24));\n // Copying and starting the candidate must not hold the lock MCP startup needs.\n // The worker's update lock serializes downloads; recheck policy at publication.\n await copyBundle(home, source, destination, bundle);\n const { stdout } = await promisify(execFile)(path.join(destination, process.platform === \"win32\" ? \"node.exe\" : \"node\"),\n [path.join(destination, \"app/dist/mason.js\"), \"--version\"],\n { timeout: 30000, windowsHide: true, env: { ...process.env, MASON_NO_AUTO_UPDATE: \"1\" } });\n if (stdout.trim() !== bundle.manifest.version) throw new Error(\"Downloaded Mason failed its version health check.\");\n }\n return withLock(home, \".install-lock\", () => installLocked(home, source, bundle, progress, options));\n}\n\nfunction assertUpdatePolicy(record: InstallRecord | null, version: string, revision?: string) {\n if (!record || !automaticUpdatesAllowed(record, { ...process.env, MASON_VERSION: \"\" })\n || record.updates?.revision !== revision || !newerStableVersion(version, record.version)) {\n throw new Error(\"Update policy or installed version changed; download was not activated.\");\n }\n}\n\nasync function installLocked(home: string, source: string, bundle: Awaited<ReturnType<typeof verifyBundle>>, progress: Progress | undefined, options: InstallOptions, alreadyStaged = false) {\n const raw = await readStoreJson(home, \"install.json\");\n const previous = raw === null ? null : recordSchema.parse(raw);\n if (options.stageOnly) assertUpdatePolicy(previous, bundle.manifest.version, options.policyRevision);\n if (!previous) for (const file of await fs.readdir(home)) {\n if (file === \".install-lock\") continue;\n // An interrupted preflight may leave an empty scaffold, never unowned content.\n const directory = path.join(home, file);\n const stat = await fs.lstat(directory);\n if (![\"versions\", \"bin\"].includes(file) || !stat.isDirectory() || (await fs.readdir(directory)).length) {\n throw new Error(\"Mason installation directory is not empty and has no ownership receipt.\");\n }\n }\n const selectedBin = path.resolve(process.env.MASON_BIN_DIR ?? previous?.bin ?? (process.platform === \"win32\"\n ? path.join(home, \"bin\") : path.join(os.homedir(), \".local/bin\")));\n await fs.mkdir(selectedBin, { recursive: true });\n const bin = await fs.realpath(selectedBin);\n if (previous && (previous.home !== home || previous.bin !== bin)) throw new Error(\"Installation paths differ from the existing Mason receipt.\");\n const id = bundle.manifestHash.slice(0, 24);\n const destination = await storePath(home, \"versions/\" + id);\n if (options.stageOnly) {\n const receipt: InstallRecord = { ...previous!, pending: { id, version: bundle.manifest.version, policyRevision: options.policyRevision! } };\n await writeStoreJson(home, \"install.json\", receipt);\n return { home, bin, version: bundle.manifest.version, previousVersion: previous!.version, path: { message: \"Update staged for a future MCP launch.\" } };\n }\n const launchers: Record<string, string> = process.platform === \"win32\" ? {\n \"mason.cmd\": WINDOWS_BATCH_LAUNCHER,\n \"mason-launcher.ps1\": `$ErrorActionPreference = 'Stop'\n$previousToken = $env:MASON_UNINSTALL_TOKEN\n$token = [Guid]::NewGuid().ToString()\n$env:MASON_UNINSTALL_TOKEN = $token\ntry {\n & ${psQuote(path.join(destination, \"node.exe\"))} ${psQuote(path.join(destination, \"app/dist/mason.js\"))} @args\n $code = $LASTEXITCODE\n if ($code -eq 0 -and $args.Count -eq 1 -and $args[0] -eq 'uninstall') {\n if ([IO.File]::ReadAllText(${psQuote(path.join(home, \".uninstall-request.txt\"))}) -cne $token) { throw 'Mason did not authorize installation cleanup.' }\n Remove-Item -LiteralPath ${psQuote(home)} -Recurse -Force\n Write-Output ${psQuote(\"Removed standalone installation: \" + home)}\n }\n exit $code\n} catch { [Console]::Error.WriteLine($_.Exception.Message); exit 2 }\nfinally { $env:MASON_UNINSTALL_TOKEN = $previousToken }\n`,\n } : { mason: `#!/bin/sh\\nexec ${shQuote(path.join(destination, \"node\"))} ${shQuote(path.join(destination, \"app/dist/mason.js\"))} \"$@\"\\n` };\n for (const [name, content] of Object.entries(launchers)) {\n const file = await storePath(bin, name);\n const old = await fs.readFile(file, \"utf8\").catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n if (old !== null && old !== previous?.launchers[name] && old !== previous?.previousLaunchers?.[name] && old !== content) throw new Error(\"Refusing to replace an unrelated or edited launcher: \" + file);\n }\n // The 0.14.0 mason.ps1 shadows mason.cmd in PowerShell, where default script\n // policy can block it. Keep the helper under a different command name and\n // remove the old one only when its recorded ownership still matches.\n const retired = Object.entries({ ...previous?.previousLaunchers, ...previous?.launchers }).filter(([name]) => !(name in launchers));\n const checkRetired = async (name: string, expected: string) => {\n if (!launcherNames.includes(name)) throw new Error(\"Invalid owned launcher name.\");\n const actual = await fs.readFile(await storePath(bin, name), \"utf8\").catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n if (actual !== null && actual !== expected) throw new Error(\"Retired launcher was edited; retained: \" + name);\n };\n for (const [name, expected] of retired) await checkRetired(name, expected);\n progress?.step(`Installing Mason ${bundle.manifest.version}`);\n const updates = options.preservePolicy && previous?.updates ? { ...previous.updates } : {\n ...(previous?.updates ?? { enabled: !previous && !process.env.CI && process.env.MASON_NO_AUTO_UPDATE !== \"1\" }),\n revision: randomUUID(),\n pinnedVersion: process.env.MASON_VERSION?.replace(/^v/, \"\") || undefined,\n mirror: process.env.MASON_RELEASE_BASE || previous?.updates?.mirror,\n };\n if (options.rollback) { updates.pinnedVersion = bundle.manifest.version; updates.revision = randomUUID(); }\n const receipt: InstallRecord = { format: 1, home, bin, current: id, version: bundle.manifest.version, launchers,\n pathChanges: previous?.pathChanges ?? [], updates,\n previous: previous && previous.current !== id ? { id: previous.current, version: previous.version } : previous?.previous };\n // Claim only the preflighted installation, retaining old launchers for interrupted upgrades.\n await writeStoreJson(home, \"install.json\", previous\n ? { ...previous, previousLaunchers: launchers }\n : receipt);\n try {\n if (!alreadyStaged) await copyBundle(home, source, destination, bundle);\n for (const [name, content] of Object.entries(launchers)) await replace(await storePath(bin, name, true), content, 0o755);\n for (const [name, expected] of retired) { await checkRetired(name, expected); await fs.rm(await storePath(bin, name), { force: true }); }\n await writeStoreJson(home, \"install.json\", receipt);\n } catch (error) {\n // Preserve the working version when an unattended activation fails.\n if (previous) {\n for (const [name, content] of Object.entries(previous.launchers)) await replace(await storePath(bin, name, true), content, 0o755);\n await writeStoreJson(home, \"install.json\", previous);\n }\n throw error;\n }\n if (options.preservePolicy) return { home, bin, version: receipt.version, previousVersion: previous?.version, path: { message: \"Installation selected.\" } };\n progress?.step(\"Checking terminal command availability\");\n const pathResult = await configurePath(bin, receipt.pathChanges ?? [], async changes => {\n receipt.pathChanges = changes;\n await writeStoreJson(home, \"install.json\", receipt);\n });\n return { home, bin, version: bundle.manifest.version, previousVersion: previous?.version, path: pathResult };\n}\n\nasync function copyBundle(home: string, source: string, destination: string, bundle: Awaited<ReturnType<typeof verifyBundle>>) {\n const exists = await fs.lstat(destination).then(() => true, error => { if (error.code === \"ENOENT\") return false; throw error; });\n if (exists) { await verifyBundle(destination, bundle.manifestHash); return; }\n const stage = await storePath(home, \"versions/.install-\" + randomUUID(), true);\n await fs.mkdir(stage);\n try {\n for (const file of [\"bundle.json\", ...Object.keys(bundle.manifest.files)]) {\n const from = await storePath(source, file), to = await storePath(stage, file, true);\n await fs.copyFile(from, to);\n await fs.chmod(to, (await fs.stat(from)).mode & 0o777);\n }\n await verifyBundle(stage, bundle.manifestHash);\n try { await fs.rename(stage, destination); }\n catch (error) {\n // A manual upgrade can finish the same immutable bundle while we stage it.\n try { await verifyBundle(destination, bundle.manifestHash); }\n catch { throw error; }\n }\n } finally { await fs.rm(stage, { recursive: true, force: true }); }\n}\n\n/** Activation and lease registration share a lock, including concurrent host launches. */\nexport async function prepareStandaloneMcp(home: string) {\n const before = await readInstallation(home), candidate = before.pending;\n let verified: Awaited<ReturnType<typeof verifyBundle>> | undefined, verificationError: unknown;\n if (candidate && automaticUpdatesAllowed(before) && !await hasRunningMcp(home)) {\n try {\n verified = await verifyBundle(await storePath(home, \"versions/\" + candidate.id));\n if (verified.manifestHash.slice(0, 24) !== candidate.id || verified.manifest.version !== candidate.version) throw new Error(\"Staged update changed.\");\n } catch (error) { verificationError = error; }\n }\n return withLock(home, \".install-lock\", async () => {\n let record = await readInstallation(home);\n const pending = record.pending;\n if (pending && candidate?.id === pending.id && (verified || verificationError) && automaticUpdatesAllowed(record) && pending.policyRevision === record.updates?.revision\n && newerStableVersion(pending.version, record.version) && !await hasRunningMcp(home)) {\n try {\n if (verificationError) throw verificationError;\n const source = await storePath(home, \"versions/\" + pending.id);\n await installLocked(home, source, verified!, undefined, { preservePolicy: true }, true);\n record = await readInstallation(home);\n } catch (error) {\n // A bad staged version must not repeatedly delay host startup.\n record = await readInstallation(home);\n delete record.pending;\n await writeStoreJson(home, \"install.json\", record);\n await writeStoreJson(home, \"update-status.json\", { lastAttempt: Date.now(), error: String(error) });\n }\n }\n const release = await registerMcp(home);\n return { bundle: await storePath(home, \"versions/\" + record.current), release };\n });\n}\n\nexport async function rollbackStandalone() {\n const { home } = await currentInstallation();\n return withLock(home, \".install-lock\", async () => {\n const record = await readInstallation(home);\n if (!record.previous) throw new Error(\"No previous installation is available.\");\n if (await hasRunningMcp(home)) throw new Error(\"Close running Mason MCP sessions before rolling back.\");\n const source = await storePath(home, \"versions/\" + record.previous.id);\n const bundle = await verifyBundle(source);\n if (bundle.manifestHash.slice(0, 24) !== record.previous.id || bundle.manifest.version !== record.previous.version) throw new Error(\"Previous installation changed.\");\n return installLocked(home, source, bundle, undefined, { preservePolicy: true, rollback: true });\n });\n}\n\nexport async function upgradeStandalone(version?: string, progress?: Progress) {\n if (version && !/^v?\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/.test(version)) throw new Error(\"Expected a release version such as 0.14.0.\");\n progress?.step(\"Checking current installation\");\n const { home, bundle, record } = await currentInstallation();\n await verifyBundle(bundle);\n const windows = process.platform === \"win32\";\n const script = path.join(bundle, windows ? \"install.ps1\" : \"install.sh\");\n // The installer owns progress from here; do not animate over its inherited IO.\n progress?.stop();\n return new Promise<number>((resolve, reject) => {\n const child = spawn(windows ? \"powershell.exe\" : \"sh\", windows ? [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script] : [script],\n { stdio: \"inherit\", windowsHide: true, env: { ...process.env, MASON_HOME: home, MASON_BIN_DIR: record.bin,\n MASON_RELEASE_BASE: process.env.MASON_RELEASE_BASE || record.updates?.mirror || \"\", MASON_VERSION: version ?? \"\",\n MASON_UPDATE_POLICY_REVISION: \"\", MASON_EXPECTED_SHA256: \"\" } });\n child.on(\"error\", reject); child.on(\"exit\", code => resolve(code ?? 2));\n });\n}\n\nexport async function uninstallStandalone() {\n const { home, record } = await currentInstallation();\n const token = process.env.MASON_UNINSTALL_TOKEN;\n if (process.platform === \"win32\" && (!token || !/^[a-f0-9-]{36}$/i.test(token))) {\n throw new Error(\"Run mason uninstall through the installed Windows launcher so it can remove Node after exit.\");\n }\n await withLock(home, \".install-lock\", async () => {\n for (const [name, expected] of Object.entries(record.launchers)) {\n if (!launcherNames.includes(name)) throw new Error(\"Invalid owned launcher name.\");\n const file = await storePath(record.bin, name);\n const actual = await fs.readFile(file, \"utf8\").catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n if (actual !== null && actual !== expected) throw new Error(\"Launcher was edited; retained: \" + file);\n }\n for (const warning of await removePath(record.pathChanges ?? [])) console.error(warning);\n if (process.platform === \"win32\") await replace(await storePath(home, \".uninstall-request.txt\", true), token!);\n for (const name of Object.keys(record.launchers)) await fs.rm(await storePath(record.bin, name), { force: true });\n });\n // The Windows launcher supervises Node and removes its locked executable only\n // after this process exits. Its exit status includes cleanup failures. Detached\n // PowerShell did not start reliably: https://github.com/nodejs/node/issues/51018\n if (process.platform !== \"win32\") await fs.rm(home, { recursive: true, force: true });\n return home;\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\n\nconst leaseSchema = z.object({ pid: z.number().int().positive(), host: z.string() });\n\n/** Called under the installation lock; uncertain ownership defers activation. */\nexport async function hasRunningMcp(home: string): Promise<boolean> {\n const directory = await storePath(home, \"sessions\");\n const files = await fs.readdir(directory).catch(error => { if (error.code === \"ENOENT\") return []; throw error; });\n for (const name of files) {\n if (!/^[a-f0-9-]+\\.json$/.test(name)) return true;\n const relative = \"sessions/\" + name;\n try {\n const raw = await readStoreJson(home, relative);\n if (raw === null) continue;\n const lease = leaseSchema.parse(raw);\n if (lease.host !== os.hostname()) return true;\n try { process.kill(lease.pid, 0); return true; }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") return true; }\n await fs.rm(await storePath(home, relative), { force: true });\n } catch { return true; }\n }\n return false;\n}\n\nexport async function registerMcp(home: string): Promise<() => Promise<void>> {\n const name = `sessions/${randomUUID()}.json`;\n await writeStoreJson(home, name, { pid: process.pid, host: os.hostname() });\n return async () => { await fs.rm(await storePath(home, name), { force: true }).catch(() => {}); };\n}\n","import { startMcpServer } from \"../src/mcp/server.js\";\nimport { startMcpWithUpdates } from \"../src/distribution/updates.js\";\n\nstartMcpWithUpdates(startMcpServer).catch((err) => {\n process.stderr.write(`Mason MCP server error: ${err}\\n`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAMlC,eAAsB,aAAgB,OAAe,KAAmC;AACtF,QAAM,SAAS,SAAS,SAAS;AACjC,MAAI,CAAC,OAAQ,QAAO,IAAI;AACxB,QAAM,QAAQ,YAAY,IAAI;AAC9B,MAAI;AAAE,WAAO,MAAM,IAAI;AA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,MAAM,IAAI,QAAgB,CAACC,UAAS,WAAW;AAChE,cAAM,GAAG,SAAS,MAAM;AAAG,cAAM,GAAG,QAAQ,UAAQA,SAAQ,QAAQ,CAAC,CAAC;AAAA,MACxE,CAAC;AAAA,IACH,UAAE;AACA,cAAQ,IAAI,UAAU,SAAS;AAAG,cAAQ,IAAI,WAAW,SAAS;AAClE,YAAM,QAAQ,QAAQ;AAAA,IACxB;AACA;AAAA,EACF;AACA,QAAM,QAAQ,YAAY,MAAM;AAAE,SAAK,wBAAwB;AAAA,EAAG,GAAG,KAAK,KAAK,GAAI;AACnF,QAAM,MAAM;AACZ,QAAM,OAAO,MAAM;AAAE,kBAAc,KAAK;AAAG,SAAK,SAAS,QAAQ;AAAA,EAAG;AACpE,MAAI;AAAE,UAAM,MAAM,IAAI;AAAG,SAAK,wBAAwB;AAAA,EAAG,SAClD,OAAO;AAAE,SAAK;AAAG,UAAM;AAAA,EAAO;AACvC;;;AO3LA,oBAAoB,cAAc,EAAE,MAAM,CAAC,QAAQ;AACjD,UAAQ,OAAO,MAAM,2BAA2B,GAAG;AAAA,CAAI;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["quote","text","hash","content","commands","path","path","configPath","resolve","content","AsyncLocalStorage","path","fs","path","fs","path","fg","readdir","lstat","count","fs","path","fg","priority","index","content","fs","path","fs","reason","resolve","path","count","path","fs","path","count","hash","path","message","fg","fs","path","text","count","path","content","path","message","text","scopes","content","text","path","text","z","index","content","message","fs","path","z","record","content","path","init_drift","init_drift","createHash","z","z","fs","z","git","evidenceSchema","record","events","event","loadRepairBaseline","eventSchema","commitSchema","init_drift","fs","path","hash","fs","path","randomUUID","z","content","head","count","fs","path","createHash","fg","z","git","text","commands","index","z","fs","path","git","execFile","promisify","fs","createHash","hash","content","reason","init_trust","fs","path","randomUUID","text","file","init_files","os","fs","randomUUID","z","message","randomUUID","z","git","verifications","text","fs","path","z","z","text","init_files","recordSchema","z","ancillaryEdits","applyEdit","ownershipEdit","completedHookOwnership","edit","init_files","parse","z","text","config","servers","index","planAutomationInstall","init_files","z","ancillaryEdits","configPath","init_files","execFile","promisify","exec","index","init_paths","message","init_types","z","index","count","init_paths","init_types","z","schema","resolve","rule","init_paths","init_types","z","schema","index","location","init_paths","init_types","path","z","index","checkSchema","previews","init_evidence","init_types","fs","path","execFile","promisify","exec","init_review","init_drift","init_evidence","MAX_FINDINGS","init_review","init_evidence","path","content","quote","targets","path","execFile","promisify","targets","exec","count","path","fs","targets","decisions","impact","relatedTests","stale","init_trust","init_drift","fs","z","isDeepStrictEqual","message","randomUUID","init_files","path","text","config_exports","fs","path","os","execFile","promisify","exec","init_config","escape","text","fs","path","createHash","execFile","promisify","resolve","exec","init_config","text","hash","hash","z","fs","path","execFile","promisify","path","path","execFile","promisify","fs","fg","promisify","execFile","count","path","execFile","promisify","exec","count","reason","createHash","execFile","promisify","z","exec","reviewToken","init_drift","init_trust","fs","z","scopeSchema","exec","promisify","execFile","path","fs","count","buildTestMap","previews","loadDecisionStore","path","analyzeImpact","upsertDecision","reviewDecision","assembleContext","automate","automationStatus","summarize","installedAutomation","setupStatus","automationFailure","setupProject","loadSetup","createConfluenceClient","saveConfluenceConfig","normalizeAtlassianBaseUrl","loadConfig","exportToConfluence","z","count","observeActivation","reviewDecision","fs","path","spawn","randomUUID","z","os","path","fs","z","fs","os","path","execFile","promisify","createHash","randomUUID","z","execute","message","reason","profiles","text","path","value","execute","z","recordSchema","recordSchema","fs","path","location","fs","path","createHash","z","digest","fs","os","path","randomUUID","z","z","fs","os","path","execFile","spawn","promisify","randomUUID","fs","os","randomUUID","z","leaseSchema","content","randomUUID","fs","installLocked","recordSchema","fs","path","os","receipt","content","randomUUID","z","statusSchema","statusSchema","spawn","path","spawn","path","resolve"]}