mason-context 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/automation/cli.ts","../src/automation/runtime.ts","../src/audit/repair.ts","../src/audit/audit.ts","../src/drift/drift.ts","../src/snapshot/snapshot.ts","../src/utils/files.ts","../src/utils/paths.ts","../src/utils/storage.ts","../src/test-map.ts","../src/audit/docs.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/audit/git.ts","../src/audit/types.ts","../src/audit/checks/deleted-reference.ts","../src/audit/checks/new-module.ts","../src/audit/checks/stale-count.ts","../src/audit/checks/dead-command.ts","../src/audit/checks/deps-changed.ts","../src/decisions/drift.ts","../src/decisions/decisions.ts","../src/context/lexical.ts","../src/decisions/provenance.ts","../src/audit/checks/decision-anchor.ts","../src/audit/checks/index.ts","../src/automation/evidence.ts","../src/automation/store.ts","../src/automation/adapters.ts","../src/automation/install.ts","../bin/mason-auto.ts"],"sourcesContent":["import { parseArgs } from \"node:util\";\nimport { automate, automationStatus, summarize } from \"./runtime.js\";\nimport { runAutomationHook, hookConfig } from \"./adapters.js\";\nimport { installAutomation, installedAutomation } from \"./install.js\";\nimport { hostSchema } from \"./store.js\";\n\nconst USAGE = `Usage: mason-auto <install|config|status|check|hook> [options]\n\n install --host claude|codex Merge lifecycle hooks into this project's host config\n config --host claude|codex Print the host config without writing\n status Read configured hooks and observed runtime events\n check Capture/resume and verify retained audit evidence\n hook --host claude|codex Handle host JSON on stdin\n\n --dir <path> Project directory (defaults to cwd)\n --command <prefix> Installed executable prefix for install/config\n --json Machine-readable check output (status always uses JSON)\n\ncheck exits 0 for verified checks, 1 for issues, 2 for incomplete/unavailable.\nHooks are advisory and exit 0; a failed capture is reported explicitly.\nLocal evidence is written under .mason/reports/. No LLM calls or source edits.`;\n\nexport async function runAutomationCli(argv: string[], stdin = \"\", io = {\n out: (s: string) => process.stdout.write(s + \"\\n\"), err: (s: string) => process.stderr.write(s + \"\\n\"),\n}): Promise<number> {\n try {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {\n dir: { type: \"string\" }, host: { type: \"string\" }, command: { type: \"string\" }, json: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n } });\n if (values.help || !positionals.length) { io.out(USAGE); return 0; }\n if (positionals.length !== 1) throw new Error(\"Expected one command.\");\n const [action] = positionals;\n const dir = values.dir ?? process.cwd();\n if (action === \"hook\") {\n const output = await runAutomationHook(hostSchema.parse(values.host), stdin);\n if (output) io.out(JSON.stringify(output));\n return 0;\n }\n if (action === \"install\" || action === \"config\") {\n const host = hostSchema.parse(values.host);\n io.out(JSON.stringify(action === \"install\" ? await installAutomation(dir, host, values.command) : hookConfig(host, values.command), null, 2));\n return 0;\n }\n if (values.host || values.command) throw new Error(\"--host and --command apply only to install/config/hook.\");\n if (action === \"status\") {\n io.out(JSON.stringify({ ...await automationStatus(dir), configured: await installedAutomation(dir) }, null, 2));\n return 0;\n }\n if (action !== \"check\") throw new Error(\"Unknown automation command: \" + action);\n const { report } = await automate(dir, { event: \"task_end\" });\n io.out(values.json ? JSON.stringify(report, null, 2) : summarize(report));\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n } catch (error) {\n const message = \"Mason automation unavailable: \" + (error instanceof Error ? error.message : String(error));\n if (argv.includes(\"hook\")) { io.out(JSON.stringify({ systemMessage: message })); return 0; }\n io.err(message);\n return 2;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { prepareRepair, verifyRepair, findingId, 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 } from \"./evidence.js\";\nimport { stateSchema, 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\"] };\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 claims no longer fail their checks; advisories need separate review. Repair 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\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\n/** Durable, host-neutral lifecycle. Only evidence/cache/receipts are written. */\nexport async function automate(dir: string, event: AutomationEvent) {\n const ws = await workspace(dir);\n return withLock(ws.root, ws.directory, async () => {\n const inputs = await readInputs(ws.root);\n const statePath = ws.directory + \"/state.json\";\n const raw = await readStoreJson(ws.root, statePath);\n const now = new Date().toISOString();\n const state: State = raw === null ? {\n version: 1, root: ws.root, gitDir: ws.gitDir, branch: ws.branch, baselines: [], sessions: {},\n updatedAt: now, fingerprint: null, latest: null,\n } : stateSchema.parse(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 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 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 // Receipts and notification dedupe are bounded; baselines are never evicted.\n const keys = Object.keys(state.sessions).sort((a, b) => state.sessions[a].lastUsed.localeCompare(state.sessions[b].lastUsed));\n for (const expired of keys.slice(0, Math.max(0, keys.length - 31))) delete state.sessions[expired];\n state.sessions[key] = { host: event.host!, seen: null, continued: false, initialIssues: [], 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 }\n if (!state.baselines.length && Object.values(inputs.docs).every(value => value === null)) {\n const report: AutomationReport = { version: 1, status: \"unavailable\", root: ws.root, branch: ws.branch, head: inputs.head,\n baselinePaths: [], reportPath: ws.directory + \"/checks/\" + randomUUID() + \".json\", findings: [],\n diagnostics: [\"No AGENTS.md, CLAUDE.md, or .claude/CLAUDE.md exists. 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 const notify = !session || session.seen !== \"no-docs\";\n if (session) session.seen = \"no-docs\";\n state.fingerprint = inputs.fingerprint; state.latest = report.reportPath; state.updatedAt = now;\n await writeStoreJson(ws.root, report.reportPath, report);\n await writeStoreJson(ws.root, statePath, state);\n return { report, message: notify ? summarize(report) : null, continueOnce: false };\n }\n let cached: unknown = null;\n const diagnostics: string[] = [];\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 const saveBaseline = async () => {\n if (state.baselines.length >= 128) throw new Error(\"128 retained baselines need review; automatic capture stopped without discarding original evidence.\");\n const prepared = await prepareRepair(ws.root, ALL_CHECKS, cache.options);\n state.baselines.push({ path: prepared.baselinePath, at: now, event: event.event, fingerprint: inputs.fingerprint });\n };\n if (!state.baselines.length) await saveBaseline();\n const verifications: RepairVerification[] = [];\n for (const baseline of state.baselines) verifications.push(await verifyRepair(ws.root, baseline.path, cache.options));\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 verifyRepair(ws.root, state.baselines.at(-1)!.path, cache.options));\n }\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 if (newSession && session) session.initialIssues = [...merged.values()].filter(f => f.status === \"unresolved\").map(f => f.id);\n const current = verifications.at(-1)!.currentAudit;\n const counts = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const finding of merged.values()) counts[finding.status]++;\n if (session) diagnostics.push(...session.coverageGaps);\n const capture = session && !session.coverageGaps.length && (session.events.session_start || session.events.before_tool) ? \"observed\" : \"unknown\";\n const after = await readInputs(ws.root);\n const currentWs = await 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 const report: AutomationReport = {\n version: 1,\n 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: state.baselines.map(b => b.path),\n reportPath: ws.directory + \"/checks/\" + randomUUID() + \".json\",\n findings: [...merged.values()], diagnostics: [...new Set(diagnostics)],\n checks: { ran: [...cache.ran], reused: [...cache.reused].filter(name => !cache.ran.has(name)), skipped: current?.skippedChecks ?? [] },\n counts, capture, scope: SCOPE,\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 &&\n !session.continued && !event.stopHookActive;\n const notify = !session || newSession || signature !== session.seen || continueOnce;\n if (session) {\n session.seen = signature;\n if (continueOnce) session.continued = true;\n }\n // Repeated tools with identical evidence need receipts, not another full report artifact.\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;\n state.fingerprint = inputs.fingerprint;\n state.latest = report.reportPath;\n // Publish complete evidence before publishing the pointer that refers to it.\n if (persistReport) await writeStoreJson(ws.root, report.reportPath, report);\n await writeStoreJson(ws.root, ws.directory + \"/cache.json\", cache.serialize());\n await writeStoreJson(ws.root, statePath, state);\n return { report, message: notify ? summarize(report) : null, continueOnce };\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 workspace(dir);\n const raw = await readStoreJson(ws.root, ws.directory + \"/state.json\");\n if (raw === null) return { version: 1, status: \"not-observed\", root: ws.root, branch: ws.branch, baselinePaths: [], hosts: {} };\n const state = stateSchema.parse(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 return { version: 1, status: 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: latest?.status ?? \"unavailable\", hosts,\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 { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit, type AuditOptions } from \"./audit.js\";\nimport { DOC_CANDIDATES } from \"./docs.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { isWithinRoot } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditAdvisory, AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nconst checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nconst commitSchema = z.object({ hash: z.string().regex(/^[a-f0-9]{40,64}$/), date: z.string(), subject: z.string() });\nconst anchorSchema = z.object({ doc: z.string(), line: z.number().int().positive().nullable(), excerpt: z.string().nullable() });\nconst count = z.number().int().nonnegative();\nconst evidenceSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"missing-path\"), claimed: z.string(), renamedTo: z.string().nullable(),\n deletedInCommit: commitSchema.nullable(), everTracked: z.boolean(), parentDirExists: z.boolean() }),\n z.object({ kind: z.literal(\"unmentioned-dir\"), dir: z.string(), sourceFileCount: count,\n firstCommit: commitSchema.nullable(), checkedDocs: z.array(z.string()) }),\n z.object({ kind: z.literal(\"count-mismatch\"), claimed: count, actual: count, unit: z.string(),\n countedFrom: z.string(), members: z.array(z.string()) }),\n z.object({ kind: z.literal(\"missing-script\"), scriptName: z.string(), invocation: z.string(),\n manifestsChecked: z.array(z.string()), availableScripts: z.array(z.string()) }),\n z.object({ kind: z.literal(\"doc-behind-manifests\"), docLastCommit: commitSchema,\n manifestCommits: z.array(commitSchema.extend({ files: z.array(z.string()) })), totalCommits: count }),\n z.object({ kind: z.literal(\"decision-anchor\"), decisionId: z.string(), title: z.string(),\n changedFiles: z.array(z.string()), refreshedHash: z.string(),\n provenance: z.object({}).passthrough().optional() }),\n]);\nconst findingSchema = z.object({ message: z.string(), anchor: anchorSchema, evidence: evidenceSchema });\nconst issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nconst advisorySchema = findingSchema.extend({ type: z.enum([\"deps-changed\", \"decision-anchor-drift\"]) });\nexport const checkResultSchema = z.object({\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skipped: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst reportSchema = z.object({\n version: z.literal(1), root: z.string(), gitAvailable: z.literal(true),\n headHash: commitSchema.shape.hash, checksRun: z.array(checkSchema).nonempty(),\n docs: z.array(z.object({ path: z.enum(DOC_CANDIDATES), lastCommit: commitSchema.nullable(),\n dirty: z.boolean(), lineCount: count })).nonempty(),\n decisionsChecked: z.boolean(), clean: z.boolean(),\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skippedChecks: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst baselineSchema = z.object({\n kind: z.literal(\"mason-audit-repair\"), version: z.literal(1),\n createdAt: z.string().datetime(), report: reportSchema, digest: z.string().regex(/^[a-f0-9]{64}$/),\n});\nconst digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\ntype Finding = AuditIssue | AuditAdvisory;\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n}\nexport interface RepairVerification {\n version: 1;\n action: \"verify\";\n baselinePath: string;\n baselineHead: string;\n currentHead: string | null;\n status: \"verified\" | \"issues-remain\" | \"incomplete\";\n findings: RepairFinding[];\n newFindings: Finding[];\n diagnostics: string[];\n currentAudit: AuditReport | null;\n counts: Record<RepairStatus, number>;\n scope: string;\n}\n\n/** Lines and wording can change without changing the underlying claim. */\nexport function findingId(finding: Finding): string {\n const e = finding.evidence;\n let key: unknown;\n switch (e.kind) {\n case \"missing-path\": key = e.claimed; break;\n case \"unmentioned-dir\": key = e.dir; break;\n case \"count-mismatch\": key = [e.unit.replace(/s$/, \"\"), e.countedFrom]; break;\n case \"missing-script\": key = e.scriptName; break;\n case \"doc-behind-manifests\": key = null; break;\n case \"decision-anchor\": key = [e.decisionId, e.provenance?.revision, e.provenance?.approval]; break;\n }\n return digest([finding.type, finding.anchor.doc, key]);\n}\nfunction allFindings(report: AuditReport): Finding[] {\n return [...report.issues, ...report.advisories, ...(report.suppressedAdvisories ?? [])];\n}\n\nasync function docState(root: string): Promise<string> {\n const docs = [];\n for (const doc of DOC_CANDIDATES) {\n try {\n const content = await readBoundedFile(await storePath(root, doc), 10 * 1024 * 1024);\n if (content === null) throw new Error(\"Context file is not regular or exceeds 10 MiB: \" + doc);\n docs.push([doc, digest(content)]);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n docs.push([doc, null]);\n }\n }\n return digest(docs);\n}\n\n/** Refuse a verification assembled across a commit or instruction-file edit. */\nasync function stableAudit(root: string, checks: CheckName[], options: AuditOptions = {}) {\n const head = await getCurrentGitHash(root);\n const before = await docState(root);\n const report = await computeAudit(root, { ...options, checks });\n if (head !== await getCurrentGitHash(root) || before !== await docState(root) ||\n (report && report.headHash !== head)) {\n throw new Error(\"HEAD or context files changed during the audit; retry against a stable checkout.\");\n }\n return report;\n}\n\nexport async function prepareRepair(rootDir: string, checks: CheckName[] = ALL_CHECKS, options: AuditOptions = {}) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await stableAudit(root, selected, options);\n if (!report) throw new Error(\"No context files found to prepare a repair.\");\n if (!report.gitAvailable) throw new Error(\"Readable Git history is required to prepare a repair.\");\n // Canonicalize before hashing; validation on read must yield the same bytes.\n const storedReport = reportSchema.parse(report);\n const payload = { kind: \"mason-audit-repair\" as const, version: 1 as const,\n createdAt: new Date().toISOString(), report: storedReport };\n const baselinePath = \".mason/reports/repairs/\" + randomUUID() + \".json\";\n await writeStoreJson(root, baselinePath, { ...payload, digest: digest(payload) });\n return { version: 1 as const, action: \"prepare\" as const, baselinePath, report };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string, options: AuditOptions = {}): Promise<RepairVerification> {\n const root = await fs.realpath(rootDir);\n const declaredRoot = path.resolve(rootDir);\n const relative = path.isAbsolute(baselinePath)\n ? path.relative(isWithinRoot(declaredRoot, baselinePath) ? declaredRoot : root, baselinePath)\n : baselinePath;\n const stored = baselineSchema.parse(await readStoreJson(root, relative));\n const { digest: savedDigest, ...payload } = stored;\n if (digest(payload) !== savedDigest) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n if (stored.report.root !== root) throw new Error(\"Repair baseline belongs to a different repository.\");\n const original = stored.report as AuditReport;\n const diagnostics: string[] = [];\n let current: AuditReport | null = null;\n try {\n current = await stableAudit(root, original.checksRun!, options);\n if (!current) diagnostics.push(\"No context files remain available to audit.\");\n else if (!current.gitAvailable) diagnostics.push(\"Git history is unavailable.\");\n for (const doc of original.docs) {\n if (!original.issues.some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await readBoundedFile(await storePath(root, doc.path), 10 * 1024 * 1024);\n if (content === null || !content.trim()) {\n diagnostics.push(\"Original context file \" + doc.path + \" is empty or unreadable; losing its claims does not verify a repair.\");\n }\n }\n if (await getChangesWithStatus(root, original.headHash!) === null) {\n diagnostics.push(\"The original audit commit is unavailable; repair history cannot be verified.\");\n }\n } catch (error) {\n diagnostics.push(error instanceof Error ? error.message : String(error));\n }\n const currentById = new Map((current ? allFindings(current) : []).map(f => [findingId(f), f]));\n const originalFindings = allFindings(original);\n const originalIds = new Set(originalFindings.map(findingId));\n const missingDocs = original.docs.filter(doc => !current?.docs.some(d => d.path === doc.path));\n for (const doc of missingDocs) diagnostics.push(\"Original context file \" + doc.path + \" is unavailable; removing it does not verify a repair.\");\n const findings = originalFindings.map((finding): RepairFinding => {\n const id = findingId(finding);\n const now = currentById.get(id);\n const base = { id, original: finding, ...(now ? { current: now } : {}) };\n if (diagnostics.length || !current) {\n return { ...base, status: \"unverified\", reason: \"The original audit scope could not be verified. See diagnostics.\" };\n }\n if (\"confidence\" in finding && now) {\n return { ...base, status: \"unresolved\", reason: \"The original check still reports this claim.\" };\n }\n const skipped = current.skippedChecks.filter(s => s.check === finding.type && (!s.doc || s.doc === finding.anchor.doc));\n if (!current.checksRun?.includes(finding.type) || skipped.length) {\n return { ...base, status: \"unverified\", reason: skipped.map(s => s.reason).join(\"; \") || \"The original check did not run.\" };\n }\n if (!(\"confidence\" in finding)) {\n return { ...base, status: \"review-required\",\n reason: \"An audit cannot establish that this advisory was reviewed. Retain its original evidence and report a separate assessment; editing or committing the doc is not approval.\" };\n }\n return { ...base, status: \"resolved\", reason: \"The original check ran and no longer reports this claim. Inspect the edit for semantic correctness.\" };\n });\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const counts: Record<RepairStatus, number> = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const f of findings) counts[f.status]++;\n const incomplete = diagnostics.length > 0 || counts.unverified > 0 || counts[\"review-required\"] > 0 ||\n (current?.skippedChecks.length ?? 0) > 0 || newFindings.some(f => !(\"confidence\" in f));\n const issuesRemain = counts.unresolved > 0 || newFindings.some(f => \"confidence\" in f);\n return {\n version: 1, action: \"verify\", baselinePath: relative, baselineHead: original.headHash!,\n currentHead: current?.gitAvailable ? current.headHash! : null,\n status: incomplete ? \"incomplete\" : issuesRemain ? \"issues-remain\" : \"verified\",\n findings, newFindings, diagnostics, currentAudit: current, counts,\n scope: \"Original audit checks over current context files and repository evidence. Resolved means no longer detected by that check. Advisories require separate review; this is not a certification of documentation or application correctness.\",\n };\n}\n\nexport function repairExitCode(report: RepairVerification): number {\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n}\n\nexport function formatRepairSummary(report: RepairVerification): string {\n return [\n \"Repair verification: \" + report.status + \". Baseline: \" + report.baselinePath,\n ...report.findings.map(f => \" [\" + f.status + \"] \" + f.original.type + \" \" + f.original.anchor.doc + \": \" + f.original.message + \"\\n \" + f.reason),\n ...report.newFindings.map(f => \" [new] \" + f.type + \" \" + f.anchor.doc + \": \" + f.message),\n ...report.diagnostics.map(d => \" [unverified] \" + d),\n ...(report.currentAudit?.skippedChecks ?? []).map(s => \" [skipped] \" + s.check + \": \" + s.reason),\n report.scope,\n ].join(\"\\n\");\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport type { FileChange } from \"../drift/drift.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { discoverDocs } from \"./docs.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { CHECKS } from \"./checks/index.js\";\nimport type { CheckContext, CheckResult } from \"./checks/index.js\";\n\nexport interface AuditOptions {\n /** Subset of checks to run; defaults to all. */\n checks?: CheckName[];\n /** Internal execution boundary used by the automation dependency cache. */\n runCheck?: (name: CheckName, context: CheckContext) => Promise<CheckResult>;\n}\n\n/**\n * Audit the repo's context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\n * against repo reality. Fully deterministic — git, filesystem, and lexical\n * extraction only; no LLM, no network. Returns null when no context file\n * exists.\n */\nexport async function computeAudit(\n rootDir: string,\n options: AuditOptions = {}\n): Promise<AuditReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const docs = await discoverDocs(resolvedRoot);\n if (docs.length === 0) return null;\n\n const headHash = await getCurrentGitHash(resolvedRoot);\n const report: AuditReport = {\n version: 1,\n root: resolvedRoot,\n gitAvailable: headHash !== \"unknown\",\n headHash,\n checksRun: [],\n docs: docs.map((d) => ({\n path: d.path,\n lastCommit: d.lastCommit,\n dirty: d.dirty,\n lineCount: d.lineCount,\n })),\n decisionsChecked: false,\n issues: [],\n advisories: [],\n suppressedAdvisories: [],\n skippedChecks: [],\n clean: true,\n };\n\n // Without git the provability gates cannot run — the caller treats this\n // as an error rather than silently degrading precision.\n if (!report.gitAvailable) return report;\n\n const changesSinceDoc = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n changesSinceDoc.set(\n doc.path,\n doc.lastCommit\n ? await getChangesWithStatus(resolvedRoot, doc.lastCommit.hash)\n : null\n );\n }\n\n let decisionsPresent = false;\n try {\n await fs.access(path.join(resolvedRoot, \".mason\", \"decisions\"));\n decisionsPresent = true;\n } catch {\n // No decision store — the check stays dark (zero-setup path).\n }\n report.decisionsChecked = decisionsPresent;\n\n const ctx: CheckContext = {\n root: resolvedRoot,\n docs,\n headHash,\n changesSinceDoc,\n decisionsPresent,\n };\n\n const selected = options.checks ?? ALL_CHECKS;\n for (const name of ALL_CHECKS) {\n if (!selected.includes(name)) continue;\n const { issues, advisories, suppressedAdvisories, skipped } = await (options.runCheck\n ? options.runCheck(name, ctx) : CHECKS[name](ctx));\n report.checksRun!.push(name);\n report.issues.push(...issues);\n report.advisories.push(...advisories);\n report.suppressedAdvisories!.push(...(suppressedAdvisories ?? []));\n report.skippedChecks.push(...skipped);\n }\n\n report.clean = report.issues.length === 0;\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport {\n loadSnapshot,\n getCurrentGitHash,\n listSourceFiles,\n} from \"../snapshot/snapshot.js\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\n\nconst exec = promisify(execFile);\n\n// Incremental refresh stops paying off once a large share of the map is\n// touched — but small absolute counts are always cheap to refresh in place,\n// so both thresholds must be exceeded before recommending a full rebuild.\nconst FULL_REBUILD_FRACTION = 0.4;\nconst FULL_REBUILD_MIN_CHANGED_MAPPED_FILES = 10;\n\nexport type ChangeStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\nexport interface FileChange {\n status: ChangeStatus;\n /** Current path (the new path for renames). */\n path: string;\n /** Pre-rename path, only present for renames. */\n previousPath?: string;\n}\n\nexport type DriftRecommendation = \"up-to-date\" | \"incremental\" | \"full-rebuild\";\n\nexport interface WorkingTreeReport {\n available: boolean;\n changedFiles: string[];\n untrackedFiles: string[];\n}\n\nexport interface DriftReport {\n /** Live entry state; committed drift alone continues to drive CLI exit codes. */\n featureFreshness?: Record<string, Freshness>;\n flowFreshness?: Record<string, Freshness>;\n workingTree?: WorkingTreeReport;\n verification?: { neverVerified: number; failed: string[] };\n stale: boolean;\n snapshotHash: string;\n headHash: string;\n /** Commits between the snapshot and HEAD; null when history is unavailable. */\n commitsBehind: number | null;\n /**\n * False when the snapshot commit is unreachable (shallow clone, rewritten\n * history) — staleFeatures/unmappedFiles/renames cannot be computed then.\n */\n historyAvailable: boolean;\n /** Current paths of every file changed since the snapshot. */\n changedFiles: string[];\n /** Stale feature name → the mapped files that changed under it. */\n staleFeatures: Record<string, string[]>;\n /** Stale flow name → the chain files that changed under it. */\n staleFlows: Record<string, string[]>;\n totalFeatures: number;\n totalFlows: number;\n /** New source files not referenced by any feature or flow. */\n unmappedFiles: string[];\n /** Files referenced by the map that no longer exist on disk. */\n ghostFiles: string[];\n renames: Array<{ from: string; to: string }>;\n recommendation: DriftRecommendation;\n}\n\nfunction parseChanges(output: string): FileChange[] {\n const fields = output.split(\"\\0\");\n const changes: FileChange[] = [];\n for (let i = 0; i < fields.length && fields[i];) {\n const code = fields[i++];\n const first = fields[i++];\n if (!first) break;\n const second = /^[RC]/.test(code) ? fields[i++] : undefined;\n const change: FileChange = second\n ? code.startsWith(\"R\") ? { status: \"renamed\", path: second, previousPath: first } : { status: \"added\", path: second }\n : { status: code === \"A\" ? \"added\" : code === \"D\" ? \"deleted\" : \"modified\", path: first };\n if (change.path.startsWith(\".mason/\") && (!change.previousPath || change.previousPath.startsWith(\".mason/\"))) continue;\n changes.push(change);\n }\n return changes;\n}\n\nexport function touchedPaths(changes: FileChange[]): string[] {\n return [...new Set(changes.flatMap(c => c.previousPath ? [c.previousPath, c.path] : [c.path]))].sort();\n}\n\nexport async function getChangesWithStatus(resolvedRoot: string, fromHash: string, toHash = \"HEAD\"): Promise<FileChange[] | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\") || !toHash || toHash === \"unknown\" || toHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", fromHash, toHash, \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 });\n return parseChanges(stdout);\n } catch { return null; }\n}\n\nexport async function getWorkingTree(resolvedRoot: string): Promise<WorkingTreeReport> {\n try {\n const [diff, untracked] = await Promise.all([\n exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n exec(\"git\", [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n ]);\n const untrackedFiles = untracked.stdout.split(\"\\0\").filter(f => f && !f.startsWith(\".mason/\"));\n return { available: true, changedFiles: [...new Set([...touchedPaths(parseChanges(diff.stdout)), ...untrackedFiles])].sort(), untrackedFiles };\n } catch { return { available: false, changedFiles: [], untrackedFiles: [] }; }\n}\n\nasync function countCommitsBehind(\n resolvedRoot: string,\n fromHash: string\n): Promise<number | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\"rev-list\", \"--count\", `${fromHash}..HEAD`],\n { cwd: resolvedRoot }\n );\n const count = Number.parseInt(stdout.trim(), 10);\n return Number.isNaN(count) ? null : count;\n } catch {\n return null;\n }\n}\n\nfunction collectMappedFiles(snapshot: Snapshot): Set<string> {\n const mappedFiles = new Set<string>();\n for (const feature of Object.values(snapshot.features)) {\n for (const f of feature.files) mappedFiles.add(f);\n for (const t of feature.tests ?? []) mappedFiles.add(t);\n }\n for (const flow of Object.values(snapshot.flows)) {\n for (const f of flow.chain) mappedFiles.add(f);\n }\n return mappedFiles;\n}\n\nasync function findGhostFiles(\n resolvedRoot: string,\n mappedFiles: Set<string>\n): Promise<string[]> {\n const ghosts: string[] = [];\n for (const file of mappedFiles) {\n try {\n await fs.access(path.join(resolvedRoot, file));\n } catch {\n ghosts.push(file);\n }\n }\n return ghosts.sort();\n}\n\n/**\n * Compare the concept map against HEAD and report feature-level drift.\n * Fully deterministic — git + filesystem only, no LLM involved.\n * Returns null when no snapshot exists.\n */\nexport async function computeDrift(rootDir: string): Promise<DriftReport | null> {\n const root = path.resolve(rootDir);\n const snapshot = await loadSnapshot(root);\n if (!snapshot) return null;\n const [headHash, workingTree] = await Promise.all([getCurrentGitHash(root), getWorkingTree(root)]);\n const hashFor = (entry: { refreshedHash?: string }) => entry.refreshedHash ?? snapshot.gitHash;\n const entries = [...Object.values(snapshot.features), ...Object.values(snapshot.flows)];\n const hashes = new Set([snapshot.gitHash, ...entries.map(hashFor)]);\n const changesByHash = new Map<string, FileChange[] | null>();\n await Promise.all([...hashes].map(async hash => {\n changesByHash.set(hash, hash === headHash && headHash !== \"unknown\" ? [] : await getChangesWithStatus(root, hash));\n }));\n const historyAvailable = headHash !== \"unknown\" && [...changesByHash.values()].every(changes => changes !== null);\n const mappedFiles = collectMappedFiles(snapshot);\n const report: DriftReport = {\n stale: !historyAvailable,\n snapshotHash: snapshot.gitHash, headHash,\n commitsBehind: 0, historyAvailable,\n changedFiles: [], staleFeatures: {}, staleFlows: {},\n totalFeatures: Object.keys(snapshot.features).length,\n totalFlows: Object.keys(snapshot.flows).length,\n unmappedFiles: [], ghostFiles: await findGhostFiles(root, mappedFiles), renames: [],\n recommendation: historyAvailable ? \"up-to-date\" : \"full-rebuild\",\n featureFreshness: {}, flowFreshness: {}, workingTree,\n verification: {\n neverVerified: entries.filter(e => !e.verifiedAt).length,\n failed: [...Object.entries(snapshot.features), ...Object.entries(snapshot.flows)].filter(([, e]) => e.verificationFailed).map(([name]) => name),\n },\n };\n const counts = await Promise.all([...hashes].map(hash => hash === headHash ? 0 : countCommitsBehind(root, hash)));\n const knownCounts = counts.filter((n): n is number => n !== null);\n report.commitsBehind = knownCounts.length ? Math.max(...knownCounts) : null;\n\n const check = (name: string, files: string[], hash: string, staleEntries: Record<string, string[]>, freshness: Record<string, Freshness>) => {\n const changes = changesByHash.get(hash);\n const committedHits = changes ? matchingPaths(files, touchedPaths(changes)) : [];\n if (committedHits.length) staleEntries[name] = committedHits;\n const localHits = matchingPaths(files, workingTree.changedFiles);\n freshness[name] = files.length === 0 || changes === null || changes === undefined || !workingTree.available ? \"unknown\"\n : committedHits.length || localHits.length || files.some(f => report.ghostFiles.includes(f)) ? \"changed\" : \"current\";\n };\n for (const [name, feature] of Object.entries(snapshot.features)) {\n check(name, [...feature.files, ...(feature.tests ?? [])], hashFor(feature), report.staleFeatures, report.featureFreshness!);\n }\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n check(name, flow.chain, hashFor(flow), report.staleFlows, report.flowFreshness!);\n }\n\n const allChanges = [...changesByHash.values()].flatMap(changes => changes ?? []);\n report.changedFiles = [...new Set(allChanges.map(c => c.path))].sort();\n // Complete coverage, including omissions from a map saved at HEAD. Untracked\n // files remain in workingTree and never change the committed-drift exit code.\n const sourceFiles = new Set(await listSourceFiles(root));\n let committedFiles: Set<string> = new Set();\n try {\n const { stdout } = await exec(\"git\", [\"ls-tree\", \"-r\", \"--name-only\", \"-z\", \"HEAD\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n committedFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch { report.historyAvailable = false; report.stale = true; }\n report.unmappedFiles = [...sourceFiles].filter(f => committedFiles.has(f) && !mappedFiles.has(f)).sort();\n const renames = new Map<string, { from: string; to: string }>();\n for (const change of allChanges) {\n if (change.status === \"renamed\" && change.previousPath) renames.set(`${change.previousPath}\\0${change.path}`, { from: change.previousPath, to: change.path });\n }\n report.renames = [...renames.values()];\n const changedMapped = new Set([...Object.values(report.staleFeatures).flat(), ...Object.values(report.staleFlows).flat()]);\n // A locally deleted file is a live-edit warning, not committed map drift.\n const committedGhosts = report.ghostFiles.filter(f => !workingTree.changedFiles.includes(f));\n report.stale ||= changedMapped.size > 0 || report.unmappedFiles.length > 0 || committedGhosts.length > 0;\n if (!report.historyAvailable) report.recommendation = \"full-rebuild\";\n else if (!report.stale) report.recommendation = \"up-to-date\";\n else report.recommendation = changedMapped.size >= FULL_REBUILD_MIN_CHANGED_MAPPED_FILES && changedMapped.size / Math.max(1, mappedFiles.size) > FULL_REBUILD_FRACTION ? \"full-rebuild\" : \"incremental\";\n return report;\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess } from \"../utils/files.js\";\nexport { SOURCE_GLOB, SOURCE_IGNORE } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { buildTestMap } from \"../test-map.js\";\n\nconst exec = promisify(execFile);\n\nexport interface FeatureEntry {\n description: string;\n files: string[];\n tests?: string[];\n /**\n * Commit this entry was last verified against. Entries updated by an\n * incremental save carry HEAD here; untouched entries keep the hash the\n * map had before the save, so drift stays visible per entry. Absent means\n * \"as of the snapshot's top-level gitHash\".\n */\n refreshedHash?: string;\n /**\n * Whether this is a user-facing capability or internal infrastructure\n * (DI wiring, config loading, logging, provider/transport plumbing).\n * Capabilities are published to product-facing docs (Confluence);\n * infrastructure stays in the AI concept map only. Defaults to \"capability\"\n * when absent (older snapshots) — see normalizeFeatureType.\n */\n type?: \"capability\" | \"infrastructure\";\n /**\n * When an assistant last confirmed this entry's files actually implement\n * the claimed feature (verify_snapshot flow). Absent on older snapshots\n * and never-verified entries. Drift checks freshness against git; this\n * checks the map was CORRECT in the first place.\n */\n verifiedAt?: string;\n verifiedHash?: string;\n /** Set when verification judged the entry wrong — re-map it. */\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport type FeatureType = \"capability\" | \"infrastructure\";\n\n/**\n * Coerce an arbitrary type value to a known classification. Anything that\n * isn't explicitly \"infrastructure\" defaults to \"capability\" — so older\n * snapshots and unclassified entries are treated as user-facing (published),\n * never silently hidden.\n */\nexport function normalizeFeatureType(value: unknown): FeatureType {\n return value === \"infrastructure\" ? \"infrastructure\" : \"capability\";\n}\n\nexport interface FlowEntry {\n description: string;\n chain: string[];\n /** See FeatureEntry.refreshedHash. */\n refreshedHash?: string;\n /** See FeatureEntry.verifiedAt / verificationFailed. */\n verifiedAt?: string;\n verifiedHash?: string;\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport interface Snapshot {\n version: 2;\n createdAt: string;\n updatedAt: string;\n gitHash: string;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nconst repoPath = z.string().refine(value => normalizeRepoPath(value) !== null, \"Expected a relative repository path\");\nconst verificationFields = {\n refreshedHash: z.string().optional(), verifiedAt: z.string().optional(),\n verifiedHash: z.string().optional(), verificationFailed: z.boolean().optional(),\n verificationNote: z.string().optional(),\n};\nexport const featureSchema = z.object({\n description: z.string(), files: z.array(repoPath), tests: z.array(repoPath).optional(),\n type: z.enum([\"capability\", \"infrastructure\"]).optional(), ...verificationFields,\n}).passthrough();\nexport const flowSchema = z.object({ description: z.string(), chain: z.array(repoPath), ...verificationFields }).passthrough();\nconst snapshotSchema = z.object({\n version: z.literal(2), createdAt: z.string(), updatedAt: z.string(), gitHash: z.string(),\n features: z.record(featureSchema), flows: z.record(flowSchema),\n}).passthrough();\n\nexport async function loadSnapshot(rootDir: string): Promise<Snapshot | null> {\n const parsed = await readStoreJson(rootDir, \".mason/snapshot.json\");\n if (parsed === null || (parsed as { version?: number }).version === 1) return null;\n const result = snapshotSchema.safeParse(parsed);\n if (!result.success) throw new Error(`Invalid Mason snapshot: ${result.error.message}`);\n return result.data;\n}\n\n/** Context and onboarding can use decisions even when the optional map is broken. */\nexport async function inspectSnapshot(rootDir: string): Promise<{\n status: \"available\" | \"missing\" | \"invalid\";\n snapshot: Snapshot | null;\n diagnostics: StoreDiagnostic[];\n}> {\n try {\n const raw = await readStoreJson(rootDir, \".mason/snapshot.json\");\n const snapshot = raw === null ? null : snapshotSchema.parse(raw);\n return { status: snapshot ? \"available\" : \"missing\", snapshot, diagnostics: [] };\n } catch (error) {\n return { status: \"invalid\", snapshot: null, diagnostics: [{\n path: \".mason/snapshot.json\", message: error instanceof Error ? error.message : String(error),\n }] };\n }\n}\n\nexport async function saveSnapshot(rootDir: string, snapshot: Snapshot): Promise<void> {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(snapshot));\n}\n\nexport async function getCurrentGitHash(rootDir: string): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"rev-parse\", \"HEAD\"], {\n cwd: rootDir,\n });\n return stdout.trim();\n } catch {\n return \"unknown\";\n }\n}\n\nexport const DEFAULT_BATCH_SIZE = 50;\nconst SKELETON_CHARS = 500;\nconst DEEP_SAMPLE_CHARS = 1500;\nconst DEEP_SAMPLES_PER_BATCH = 3;\n\nexport interface SnapshotBatch {\n offset: number;\n batchSize: number;\n nextOffset: number | null;\n totalFiles: number;\n skeletons: Array<{ path: string; content: string }>;\n samples: Array<{ path: string; content: string }>;\n testPairs: Array<{ test: string; source: string; confidence: string }>;\n}\n\nexport async function listSourceFiles(resolvedRoot: string): Promise<string[]> {\n return (await createFileAccess(resolvedRoot)).list();\n}\n\nexport async function prepareSnapshotBatch(\n rootDir: string,\n offset: number,\n batchSize: number = DEFAULT_BATCH_SIZE,\n scopeFiles?: string[]\n): Promise<SnapshotBatch> {\n const resolvedRoot = path.resolve(rootDir);\n const access = await createFileAccess(resolvedRoot);\n let allFiles = await access.list();\n if (scopeFiles) {\n // Intersect with the real source list: keeps ignore rules and path safety,\n // and silently drops scope entries that no longer exist on disk. An empty\n // scope stays empty — it must not fall back to walking the whole project.\n const scopeSet = new Set(scopeFiles);\n allFiles = allFiles.filter((f) => scopeSet.has(f));\n }\n const totalFiles = allFiles.length;\n const safeOffset = Math.max(0, Math.min(offset, totalFiles));\n const batchPaths = allFiles.slice(safeOffset, safeOffset + batchSize);\n\n const skeletons: Array<{ path: string; content: string }> = [];\n for (const filePath of batchPaths) {\n const full = await access.read(filePath);\n if (full) {\n skeletons.push({\n path: full.path,\n content: full.content.slice(0, SKELETON_CHARS),\n });\n }\n }\n\n // Pick a few files from this batch to read deeply for grounding. Spread\n // evenly across the batch so the deep samples represent the batch's range.\n const samples: Array<{ path: string; content: string }> = [];\n if (skeletons.length > 0) {\n const step = Math.max(1, Math.floor(skeletons.length / DEEP_SAMPLES_PER_BATCH));\n for (let i = 0; i < skeletons.length && samples.length < DEEP_SAMPLES_PER_BATCH; i += step) {\n const full = await access.read(skeletons[i].path);\n if (full) {\n samples.push({\n path: full.path,\n content: full.content.slice(0, DEEP_SAMPLE_CHARS),\n });\n }\n }\n }\n\n // Only include test pairs that involve files in this batch — keeps the\n // appendix relevant and small.\n const batchPathSet = new Set(batchPaths);\n const allTestPairs = (await buildTestMap(resolvedRoot)).paired;\n const testPairs = allTestPairs.filter(\n (p) => batchPathSet.has(p.test) || batchPathSet.has(p.source)\n );\n\n const nextOffset =\n safeOffset + batchSize >= totalFiles ? null : safeOffset + batchSize;\n\n return {\n offset: safeOffset,\n batchSize,\n nextOffset,\n totalFiles,\n skeletons,\n samples,\n testPairs,\n };\n}\n","import fs from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\nconst exec = promisify(execFile);\nexport const SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\", \"vue\", \"svelte\", \"kt\", \"kts\", \"java\", \"py\", \"go\", \"rs\", \"swift\", \"rb\", \"cs\", \"cpp\", \"c\", \"h\", \"hpp\", \"dart\", \"php\"];\nexport const SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(\",\")}}`;\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/.mason/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\", \"**/*.lock\",\n \"**/generated/**\", \"**/*.generated.*\", \"**/R.java\", \"**/BuildConfig.java\",\n \"**/package-lock.json\", \"**/yarn.lock\", \"**/pnpm-lock.yaml\",\n];\nexport const MAX_SOURCE_BYTES = 1024 * 1024;\nexport interface ProjectConfig { patterns?: string[]; alwaysInclude?: string[]; ignore?: string[] }\nexport interface SourceFile { path: string; content: string; totalLines: number }\n\nexport function isSensitiveFile(file: string): boolean {\n return file.split(/[\\\\/]/).some(part =>\n /^(?:\\.env(?:\\..*)?|id_rsa.*|id_ed25519.*)$|\\.(?:pem|key|p12|pfx|jks|keystore)$|credentials\\.|secret|^local\\.properties$/i.test(part)\n );\n}\n\n/** Bound reads even if a file grows after stat. Only read regular files. */\nexport async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {\n // Do not block on a FIFO or follow a symlink substituted after resolution.\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > maxBytes) return null;\n const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));\n let bytes = 0;\n while (bytes < buffer.length) {\n const result = await handle.read(buffer, bytes, buffer.length - bytes, null);\n if (result.bytesRead === 0) break;\n bytes += result.bytesRead;\n }\n return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString(\"utf8\");\n } finally { await handle.close(); }\n}\n\nexport async function loadProjectConfig(root: string): Promise<ProjectConfig> {\n try {\n const canonicalRoot = await fs.realpath(root);\n const configPath = await fs.realpath(path.join(root, \".mason/config.json\"));\n if (!isWithinRoot(canonicalRoot, configPath)) throw new Error(\"Project configuration resolves outside the repository\");\n const raw = await readBoundedFile(configPath, 64 * 1024);\n if (raw === null) throw new Error(\"Project configuration is not a regular file or exceeds 64 KiB\");\n const value = JSON.parse(raw);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Expected a configuration object\");\n const config: ProjectConfig = {};\n for (const key of [\"patterns\", \"alwaysInclude\", \"ignore\"] as const) {\n if (value[key] === undefined) continue;\n if (!Array.isArray(value[key]) || !value[key].every((s: unknown) => typeof s === \"string\")) {\n throw new Error(`Configuration ${key} must be an array of strings`);\n }\n config[key] = value[key];\n }\n return config;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new Error(`Cannot apply project file policy: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/** Scoped to one operation, so a later tool call sees newly edited files/ignores. */\nexport async function createFileAccess(rootDir: string) {\n const root = path.resolve(rootDir);\n const canonicalRoot = await fs.realpath(root).catch(() => root);\n const config = await loadProjectConfig(root);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n let gitFiles: Set<string> | null = null;\n try {\n const { stdout } = await exec(\"git\", [\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n gitFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch {\n // File-system projects are supported. Fail closed if this IS a Git repo.\n let inGit = false;\n try { await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: root }); inGit = true; } catch { /* no Git */ }\n if (inGit) throw new Error(\"Cannot enumerate Git files safely\");\n }\n\n async function resolve(file: string): Promise<string | null> {\n const relative = normalizeRepoPath(file);\n if (!relative || isSensitiveFile(relative) || (gitFiles && !gitFiles.has(relative))) return null;\n const candidate = path.join(root, relative);\n try {\n const real = await fs.realpath(candidate);\n if (!isWithinRoot(canonicalRoot, real) || isSensitiveFile(path.relative(canonicalRoot, real))) return null;\n const stat = await fs.stat(real);\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) return null;\n // A symlink must not bypass the target's ignore policy either.\n if (gitFiles && !gitFiles.has(path.relative(canonicalRoot, real).split(path.sep).join(\"/\"))) return null;\n return real;\n } catch { return null; }\n }\n\n async function list(patterns: string | string[] = SOURCE_GLOB, options: { deep?: number; dot?: boolean } = {}): Promise<string[]> {\n const found = await fg(patterns, { cwd: root, ignore, followSymbolicLinks: false, ...options });\n const safe = await Promise.all(found.map(async f => (await resolve(f)) ? f : null));\n return safe.filter((f): f is string => f !== null).sort();\n }\n\n async function read(file: string): Promise<SourceFile | null> {\n const relative = normalizeRepoPath(file);\n if (!relative) return null;\n const real = await resolve(relative);\n if (!real) return null;\n // Apply the same glob exclusions to explicit reads and symlink targets.\n for (const rel of new Set([relative, path.relative(canonicalRoot, real).split(path.sep).join(\"/\")])) {\n if (!(await fg(fg.escapePath(rel), { cwd: root, ignore, dot: true })).length) return null;\n }\n try {\n const content = await readBoundedFile(real, MAX_SOURCE_BYTES);\n return content === null ? null : { path: relative, content, totalLines: content.split(\"\\n\").length };\n } catch { return null; }\n }\n return { root, config, list, read };\n}\n","import path from \"node:path\";\n\n/** One canonical representation for stored paths and decision anchors. */\nexport function normalizeRepoPath(value: string): string | null {\n const slash = value.replace(/\\\\/g, \"/\");\n if (!slash || slash.includes(\"\\0\") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;\n if (slash.split(\"/\").includes(\"..\")) return null;\n const normalized = path.posix.normalize(slash).replace(/\\/$/, \"\");\n return normalized === \".\" ? null : normalized;\n}\n\nexport function sanitizeRepoPaths(files: string[]): string[] {\n return [...new Set(files.map(normalizeRepoPath).filter((p): p is string => p !== null))];\n}\n\nexport function isWithinRoot(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nexport function anchorMatches(anchor: string, file: string): boolean {\n const a = normalizeRepoPath(anchor);\n const f = normalizeRepoPath(file);\n return a !== null && f !== null && (a === f || f.startsWith(`${a}/`));\n}\n\nexport function matchingPaths(anchors: string[], files: Iterable<string>): string[] {\n return [...new Set(files)].filter(file => anchors.some(anchor => anchorMatches(anchor, file)));\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { normalizeRepoPath } from \"./paths.js\";\nimport { readBoundedFile } from \"./files.js\";\n\nexport interface StoreDiagnostic { path: string; message: string }\n\n/** Metadata paths may not contain symlinks, including their parent directories. */\nexport async function storePath(root: string, relative: string, createParents = false): Promise<string> {\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Invalid store path: ${relative}`);\n let current = await fs.realpath(root);\n const parts = normalized.split(\"/\");\n for (let i = 0; i < parts.length; i++) {\n current = path.join(current, parts[i]);\n let stat;\n try { stat = await fs.lstat(current); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n if (createParents && i < parts.length - 1) {\n try { await fs.mkdir(current); } catch (mkdirError) {\n if ((mkdirError as NodeJS.ErrnoException).code !== \"EEXIST\") throw mkdirError;\n }\n stat = await fs.lstat(current);\n }\n }\n if (stat?.isSymbolicLink()) throw new Error(`Symlink in store path: ${relative}`);\n }\n return current;\n}\n\nexport async function readStoreJson(root: string, relative: string): Promise<unknown | null> {\n try {\n const file = await storePath(root, relative);\n const raw = await readBoundedFile(file, 10 * 1024 * 1024);\n if (raw === null) throw new Error(\"file is not regular or exceeds 10 MiB\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null) throw new Error(\"expected a JSON object, received null\");\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new Error(`Invalid Mason store ${relative}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function writeStoreJson(root: string, relative: string, value: unknown): Promise<void> {\n const payload = JSON.stringify(value, null, 2) + \"\\n\";\n if (Buffer.byteLength(payload) > 10 * 1024 * 1024) {\n throw new Error(`Mason store ${relative} exceeds 10 MiB`);\n }\n const file = await storePath(root, relative, true);\n const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);\n try {\n const handle = await fs.open(temporary, \"wx\", 0o600);\n try { await handle.writeFile(payload, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n await fs.rename(temporary, file);\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import path from \"node:path\";\nimport { createFileAccess } from \"./utils/files.js\";\n\nexport interface TestPair {\n test: string;\n source: string;\n confidence: string;\n}\n\nexport interface TestMapResult {\n totalTestFiles: number;\n paired: TestPair[];\n unmatched: string[];\n}\n\nexport async function buildTestMap(dir: string): Promise<TestMapResult> {\n const rootDir = path.resolve(dir);\n const access = await createFileAccess(rootDir);\n\n // Find all test files\n const testPatterns = [\n \"**/*.test.*\", \"**/*.spec.*\",\n \"**/*Test.kt\", \"**/*Test.java\", \"**/*Tests.kt\", \"**/*Tests.java\",\n \"**/test_*.py\", \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\", \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n const testFiles = await access.list(testPatterns);\n\n // Find all source files\n const sourceFiles = await access.list();\n\n // Build source file index by base name (without extension)\n const sourceByBaseName = new Map<string, string[]>();\n for (const file of sourceFiles) {\n if (testFiles.includes(file)) continue; // Skip test files\n const baseName = path.basename(file).replace(/\\.[^.]+$/, \"\");\n const existing = sourceByBaseName.get(baseName) ?? [];\n existing.push(file);\n sourceByBaseName.set(baseName, existing);\n }\n\n // Match test files to source files by name\n const paired: TestPair[] = [];\n const unmatched: string[] = [];\n\n for (const testFile of testFiles) {\n const testBaseName = path.basename(testFile).replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes/prefixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (!sourceName) {\n unmatched.push(testFile);\n continue;\n }\n\n const candidates = sourceByBaseName.get(sourceName);\n if (candidates && candidates.length > 0) {\n // If multiple candidates, prefer one in a similar directory path\n const testDir = path.dirname(testFile);\n const bestMatch = candidates.reduce((best, candidate) => {\n const candidateDir = path.dirname(candidate);\n const bestDir = path.dirname(best);\n const candidateOverlap = commonSegments(testDir, candidateDir);\n const bestOverlap = commonSegments(testDir, bestDir);\n return candidateOverlap > bestOverlap ? candidate : best;\n });\n\n paired.push({\n test: testFile,\n source: bestMatch,\n confidence: candidates.length === 1 ? \"exact\" : \"best-guess\",\n });\n } else {\n unmatched.push(testFile);\n }\n }\n\n return { totalTestFiles: testFiles.length, paired, unmatched };\n}\n\nfunction commonSegments(pathA: string, pathB: string): number {\n const segsA = pathA.split(\"/\");\n const segsB = pathB.split(\"/\");\n let count = 0;\n for (let i = 0; i < Math.min(segsA.length, segsB.length); i++) {\n if (segsA[i] === segsB[i]) count++;\n else break;\n }\n return count;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * All context files audited in v1, in the precedence order the setup\n * playbook uses. Every candidate that exists is audited — a repo can\n * legitimately carry both AGENTS.md and CLAUDE.md, and drift can live in\n * either.\n */\nexport const DOC_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".claude/CLAUDE.md\",\n] as const;\n\nexport interface AuditDoc {\n /** Repo-relative posix path. */\n path: string;\n content: string;\n lineCount: number;\n /** Null when the doc is untracked. */\n lastCommit: CommitRef | null;\n /** Uncommitted edits present. */\n dirty: boolean;\n claims: DocClaims;\n}\n\nasync function isDirty(resolvedRoot: string, relPath: string): Promise<boolean> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"status\", \"--porcelain\", \"--\", relPath],\n { cwd: resolvedRoot }\n );\n return stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs: AuditDoc[] = [];\n for (const candidate of DOC_CANDIDATES) {\n let content: string;\n try {\n content = await fs.readFile(path.join(resolvedRoot, candidate), \"utf-8\");\n } catch {\n continue;\n }\n docs.push({\n path: candidate,\n content,\n lineCount: content.split(\"\\n\").length,\n lastCommit: await lastCommitOf(resolvedRoot, candidate),\n dirty: await isDirty(resolvedRoot, candidate),\n claims: extractClaims(content),\n });\n }\n return docs;\n}\n","import type { PathClaim } from \"./types.js\";\n\n/**\n * A fenced block is treated as a directory tree only when it clearly is one —\n * below this many branch-glyph lines it's more likely an ASCII sketch.\n */\nconst MIN_GLYPH_LINES = 3;\n\nconst GLYPHS = [\"├──\", \"└──\"] as const;\n\nfunction glyphIndex(line: string): number {\n for (const glyph of GLYPHS) {\n const idx = line.indexOf(glyph);\n if (idx !== -1) return idx;\n }\n return -1;\n}\n\n/** Tree furniture: blank, or only vertical bars and whitespace. */\nfunction isSpacerLine(line: string): boolean {\n return /^[\\s│|]*$/.test(line);\n}\n\n/**\n * Strip an inline comment/annotation from a tree entry. Entries commonly\n * carry `# comment` or column-aligned notes after two or more spaces.\n */\nfunction entryName(afterGlyph: string): string | null {\n let name = afterGlyph.replace(/^\\s+/, \"\");\n const hash = name.search(/\\s+#/);\n if (hash !== -1) name = name.slice(0, hash);\n const columns = name.search(/\\s{2,}/);\n if (columns !== -1) name = name.slice(0, columns);\n name = name.trim();\n // A name with remaining internal whitespace is not a path — treat the\n // line as malformed rather than guessing.\n if (!name || /\\s/.test(name)) return null;\n return name;\n}\n\n/**\n * Reconstruct full paths from an ASCII directory tree inside a fenced block.\n *\n * The failure mode must always be a missed claim, never an invented path: a\n * line that doesn't parse cleanly aborts reconstruction below it, and every\n * emitted path still passes the deleted-reference provability gate later.\n *\n * `blockLines` are the fence's content lines; `blockStartLine` is the 1-based\n * doc line number of the first content line.\n */\nexport function extractTreeClaims(\n blockLines: string[],\n blockStartLine: number\n): PathClaim[] {\n const glyphLines = blockLines.filter((l) => glyphIndex(l) !== -1).length;\n if (glyphLines < MIN_GLYPH_LINES) return [];\n\n const claims: PathClaim[] = [];\n // Directories on the path from the root to the current entry, keyed by the\n // column their branch glyph appeared at.\n const stack: Array<{ col: number; name: string }> = [];\n let rootPrefix = \"\";\n let started = false;\n\n for (let i = 0; i < blockLines.length; i++) {\n const line = blockLines[i];\n const col = glyphIndex(line);\n\n if (col === -1) {\n if (isSpacerLine(line)) continue;\n if (!started) {\n // A bare `src/` line above the first glyph names the tree's root.\n const candidate = line.trim();\n if (candidate.endsWith(\"/\") && !/\\s/.test(candidate)) {\n rootPrefix = candidate.replace(/\\/+$/, \"\");\n claims.push({\n path: rootPrefix,\n line: blockStartLine + i,\n excerpt: candidate,\n });\n }\n continue;\n }\n // Unparseable line after the tree began: stop here, keep what we have.\n return claims;\n }\n\n started = true;\n const name = entryName(line.slice(col + GLYPHS[0].length));\n if (name === null) return claims;\n\n while (stack.length > 0 && stack[stack.length - 1].col >= col) {\n stack.pop();\n }\n\n const isDir = name.endsWith(\"/\");\n const cleanName = name.replace(/\\/+$/, \"\");\n const segments = [\n ...(rootPrefix ? [rootPrefix] : []),\n ...stack.map((s) => s.name),\n cleanName,\n ];\n claims.push({\n path: segments.join(\"/\"),\n line: blockStartLine + i,\n excerpt: name,\n });\n\n if (isDir) stack.push({ col, name: cleanName });\n }\n\n return claims;\n}\n","import type {\n CommandClaim,\n CountClaim,\n DocClaims,\n PathClaim,\n} from \"./types.js\";\nimport { extractTreeClaims } from \"./tree.js\";\n\n/**\n * Single-segment names that count as path claims without containing a \"/\".\n * Anything else without a slash is prose (\"name your file `config.ts`\"), not\n * a claim about this repo.\n */\nconst ROOT_FILE_NAMES = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-workspace.yaml\",\n \"tsconfig.json\",\n \"tsup.config.ts\",\n \"vitest.config.ts\",\n \"Makefile\",\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"go.sum\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"manifest.json\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\",\n \"CLAUDE.md\",\n \"AGENTS.md\",\n \".gitignore\",\n \".env.example\",\n]);\n\nconst SHELL_FENCE_INFOS = new Set([\"\", \"bash\", \"sh\", \"shell\", \"console\", \"zsh\"]);\n\nconst COMMAND_RE = /\\b(npm|pnpm|yarn)\\s+run\\s+([A-Za-z0-9:_.-]+)/g;\nconst COUNT_RE = /(\\d+)\\s+(modules?|packages?|workspaces?|crates?)\\b/gi;\n/** \"3 package managers\" is not a package count. */\nconst COUNT_DENYLIST_RE = /^\\s*(manager|registr|lock|json)/i;\n\nconst IGNORE_LINE = \"<!-- mason:ignore -->\";\nconst IGNORE_START = \"<!-- mason:ignore-start -->\";\nconst IGNORE_END = \"<!-- mason:ignore-end -->\";\n\n/**\n * Normalize a candidate token into a repo-relative path claim, or return\n * null when the token is not a claim about this repo (URL, glob,\n * placeholder, relative import example, bare word).\n */\nexport function normalizePathToken(token: string): string | null {\n let t = token.trim();\n if (!t) return null;\n if (/\\s/.test(t)) return null;\n if (t.includes(\"://\") || t.includes(\"\\\\\")) return null;\n if (/[*?[\\]{}<>$`]/.test(t)) return null;\n if (t.startsWith(\"/\") || t.startsWith(\"~\") || t.startsWith(\"./\") || t.startsWith(\"../\")) {\n return null;\n }\n // `src/mcp/tools.ts:189` claims the file, not the line.\n t = t.replace(/:\\d+(?:-\\d+)?$/, \"\");\n if (t.includes(\":\")) return null;\n const normalized = t.replace(/\\/+$/, \"\");\n if (!normalized) return null;\n // `server/src/test/kotlin/...` — a dots-only segment is an \"and so on\"\n // placeholder, not a claim.\n if (normalized.split(\"/\").some((seg) => /^\\.+$/.test(seg))) return null;\n if (normalized.includes(\"/\")) return normalized;\n return ROOT_FILE_NAMES.has(normalized) ? normalized : null;\n}\n\n/** A fence line that is exactly one path-shaped token is a file-list claim. */\nfunction exactTokenPath(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed || /\\s/.test(trimmed) || !trimmed.includes(\"/\")) return null;\n return normalizePathToken(trimmed);\n}\n\nfunction computeIgnoredLines(lines: string[]): boolean[] {\n const ignored = new Array<boolean>(lines.length).fill(false);\n let inRegion = false;\n let ignoreNext = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.includes(IGNORE_START)) {\n inRegion = true;\n ignored[i] = true;\n continue;\n }\n if (line.includes(IGNORE_END)) {\n inRegion = false;\n ignored[i] = true;\n continue;\n }\n if (inRegion) {\n ignored[i] = true;\n continue;\n }\n if (ignoreNext) {\n if (line.trim().length === 0) continue; // skip blanks to the next real line\n ignored[i] = true;\n ignoreNext = false;\n continue;\n }\n if (line.includes(IGNORE_LINE)) {\n ignored[i] = true;\n const rest = line.replace(IGNORE_LINE, \"\").trim();\n if (rest.length === 0) ignoreNext = true;\n }\n }\n return ignored;\n}\n\n/**\n * Extract every checkable claim from a context-file's markdown. Deterministic\n * and purely lexical — precision comes from the checks' provability gates,\n * not from clever parsing here.\n */\nexport function extractClaims(content: string): DocClaims {\n const lines = content.split(\"\\n\");\n const ignored = computeIgnoredLines(lines);\n\n const paths = new Map<string, PathClaim>();\n const counts: CountClaim[] = [];\n const commands = new Map<string, CommandClaim>();\n\n const addPath = (claim: PathClaim): void => {\n if (!paths.has(claim.path)) paths.set(claim.path, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n if (!commands.has(claim.scriptName)) commands.set(claim.scriptName, claim);\n };\n\n let inFence = false;\n let fenceInfo = \"\";\n let fenceMarker = \"\";\n let blockLines: string[] = [];\n let blockStartLine = 0;\n\n const processBlock = (): void => {\n for (const claim of extractTreeClaims(blockLines, blockStartLine)) {\n addPath(claim);\n }\n for (let i = 0; i < blockLines.length; i++) {\n const exact = exactTokenPath(blockLines[i]);\n if (exact) {\n addPath({\n path: exact,\n line: blockStartLine + i,\n excerpt: blockLines[i].trim(),\n });\n }\n }\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNo = i + 1;\n const fenceMatch = line.match(/^\\s*(```+|~~~+)(.*)$/);\n\n if (fenceMatch) {\n if (!inFence) {\n inFence = true;\n fenceMarker = fenceMatch[1][0];\n fenceInfo = fenceMatch[2].trim().toLowerCase();\n blockLines = [];\n blockStartLine = lineNo + 1;\n } else if (fenceMatch[1][0] === fenceMarker) {\n inFence = false;\n processBlock();\n }\n continue;\n }\n\n if (inFence) {\n // Ignored lines become spacers so the rest of a tree still parses.\n blockLines.push(ignored[i] ? \"\" : line);\n if (!ignored[i] && SHELL_FENCE_INFOS.has(fenceInfo)) {\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n continue;\n }\n\n if (ignored[i]) continue;\n\n for (const m of line.matchAll(/`([^`]+)`/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(/\"([A-Za-z][\\w.@-]*(?:\\/[\\w.@-]+)+\\/?)\"/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(COUNT_RE)) {\n const rest = line.slice((m.index ?? 0) + m[0].length);\n if (COUNT_DENYLIST_RE.test(rest)) continue;\n counts.push({\n count: Number.parseInt(m[1], 10),\n unit: m[2].toLowerCase(),\n line: lineNo,\n excerpt: m[0],\n });\n }\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n\n // An unclosed fence still gets its block processed — trees at the end of a\n // truncated doc are claims too.\n if (inFence) processBlock();\n\n return {\n paths: [...paths.values()],\n counts,\n commands: [...commands.values()],\n };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CommitRef } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\nconst COMMIT_FORMAT = \"%H%x09%cI%x09%s\";\n\nfunction parseCommitLine(line: string): CommitRef | null {\n const parts = line.split(\"\\t\");\n if (parts.length < 3 || !parts[0]) return null;\n return { hash: parts[0], date: parts[1], subject: parts.slice(2).join(\"\\t\") };\n}\n\n/** Most recent commit touching a path, or null if the path was never tracked. */\nexport async function lastCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** The commit that deleted a path, or null if none did. */\nexport async function deletingCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n relPath,\n ],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** Oldest commit touching a path (used to date a directory's appearance). */\nexport async function firstCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\nexport interface RangeCommits {\n commits: Array<CommitRef & { files: string[] }>;\n total: number;\n}\n\n/**\n * Commits in fromHash..HEAD touching any of the pathspecs, newest first, with\n * the touched files per commit. Rev-range, not --since: immune to rebase date\n * skew and CI checkout mtimes. Returns null when the range is uncomputable\n * (unreachable base commit, shallow clone, no git).\n */\nexport async function commitsTouchingSince(\n resolvedRoot: string,\n fromHash: string,\n pathspecs: string[]\n): Promise<RangeCommits | null> {\n if (!fromHash || fromHash === \"unknown\") return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `${fromHash}..HEAD`,\n `--format=%x01${COMMIT_FORMAT}`,\n \"--name-only\",\n \"--\",\n ...pathspecs,\n ],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n\n const commits: Array<CommitRef & { files: string[] }> = [];\n // \\x01 marks each commit header so name-only file lists can't be\n // mistaken for headers.\n for (const block of stdout.split(\"\\x01\")) {\n if (!block.trim()) continue;\n const lines = block.split(\"\\n\").filter((l) => l.trim().length > 0);\n const ref = parseCommitLine(lines[0]);\n if (!ref) continue;\n commits.push({ ...ref, files: lines.slice(1).map((l) => l.trim()) });\n }\n return { commits, total: commits.length };\n } catch {\n return null;\n }\n}\n","import type { decisionProvenance } from \"../decisions/provenance.js\";\n\nexport type IssueType =\n | \"deleted-reference\"\n | \"new-module\"\n | \"stale-count\"\n | \"dead-command\";\n\nexport type AdvisoryType = \"deps-changed\" | \"decision-anchor-drift\";\n\nexport type CheckName = IssueType | AdvisoryType;\n\nexport const ALL_CHECKS: CheckName[] = [\n \"deleted-reference\",\n \"new-module\",\n \"stale-count\",\n \"dead-command\",\n \"deps-changed\",\n \"decision-anchor-drift\",\n];\n\n/**\n * \"certain\" — the claim is provably false (a tracked path is gone, a computed\n * count differs, a script exists in no manifest). \"likely\" — evidence-backed\n * but heuristic (an unmentioned directory; a never-tracked path whose parent\n * exists). Certain-class issues are safe to auto-fix; likely-class issues\n * deserve a look.\n */\nexport type Confidence = \"certain\" | \"likely\";\n\nexport interface CommitRef {\n hash: string;\n date: string;\n subject: string;\n}\n\nexport interface DocAnchor {\n /** Repo-relative doc path, e.g. \"CLAUDE.md\" or \".claude/CLAUDE.md\". */\n doc: string;\n /** 1-based line of the claim; null for doc-level issues (new-module). */\n line: number | null;\n /** The claim exactly as written, e.g. \"src/utils/logger.ts\". */\n excerpt: string | null;\n}\n\nexport type Evidence =\n | {\n kind: \"missing-path\";\n claimed: string;\n renamedTo: string | null;\n deletedInCommit: CommitRef | null;\n everTracked: boolean;\n parentDirExists: boolean;\n }\n | {\n kind: \"unmentioned-dir\";\n dir: string;\n sourceFileCount: number;\n firstCommit: CommitRef | null;\n checkedDocs: string[];\n }\n | {\n kind: \"count-mismatch\";\n claimed: number;\n actual: number;\n unit: string;\n /** Where the actual count came from, e.g. \"package.json workspaces\". */\n countedFrom: string;\n members: string[];\n }\n | {\n kind: \"missing-script\";\n scriptName: string;\n invocation: string;\n manifestsChecked: string[];\n availableScripts: string[];\n }\n | {\n kind: \"doc-behind-manifests\";\n docLastCommit: CommitRef;\n manifestCommits: Array<CommitRef & { files: string[] }>;\n totalCommits: number;\n }\n | {\n kind: \"decision-anchor\";\n provenance?: ReturnType<typeof decisionProvenance>;\n decisionId: string;\n title: string;\n changedFiles: string[];\n refreshedHash: string;\n };\n\nexport interface AuditIssue {\n type: IssueType;\n message: string;\n anchor: DocAnchor;\n confidence: Confidence;\n evidence: Evidence;\n}\n\n/**\n * Advisories are facts the fixing agent cannot close by editing the doc (a\n * manifest commit after the doc's commit stays true forever; decision records\n * must be re-verified by humans). They NEVER affect the exit code — same\n * precedent as decision staleness in mason-drift.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n}\n\nexport interface AuditDocInfo {\n path: string;\n lastCommit: CommitRef | null;\n /** Uncommitted edits present — deps-changed is suppressed for dirty docs. */\n dirty: boolean;\n lineCount: number;\n}\n\nexport interface AuditReport {\n /** Additive-only schema — this output is a CI contract. */\n version: 1;\n root: string;\n gitAvailable: boolean;\n /** Commit and exact check scope used by this run. */\n headHash?: string;\n checksRun?: CheckName[];\n docs: AuditDocInfo[];\n /** Whether .mason/decisions/ existed and was checked. */\n decisionsChecked: boolean;\n /** Drive exit code 1. */\n issues: AuditIssue[];\n /** Never drive the exit code. */\n advisories: AuditAdvisory[];\n /** Original committed evidence retained while local doc edits suppress reporting. */\n suppressedAdvisories?: AuditAdvisory[];\n skippedChecks: Array<{ check: string; reason: string; doc?: string }>;\n clean: boolean;\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CountClaim {\n count: number;\n unit: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CommandClaim {\n scriptName: string;\n invocation: string;\n line: number;\n excerpt: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport type { AuditIssue } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nasync function exists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A claimed path that is missing on disk is only flagged when the repo can\n * prove it was ever real: a rename since the doc's last commit, or git\n * history for the path, or at least an existing parent directory. Paths with\n * none of those are illustrative examples and are dropped silently.\n */\nexport async function checkDeletedReferences(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map<string, string>();\n for (const change of changes ?? []) {\n if (change.status === \"renamed\" && change.previousPath) {\n renames.set(change.previousPath, change.path);\n }\n }\n\n for (const claim of doc.claims.paths) {\n // Mason's own metadata is optional state, not repo structure — docs\n // legitimately describe .mason/ files that a given repo doesn't have.\n if (claim.path === \".mason\" || claim.path.startsWith(\".mason/\")) {\n continue;\n }\n if (await exists(path.join(ctx.root, claim.path))) continue;\n\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const renamedTo = renames.get(claim.path) ?? null;\n\n if (renamedTo) {\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` was renamed to \\`${renamedTo}\\``,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo,\n deletedInCommit: null,\n everTracked: true,\n parentDirExists: true,\n },\n });\n continue;\n }\n\n const tracked = await lastCommitOf(ctx.root, claim.path);\n if (tracked) {\n const deleted = await deletingCommitOf(ctx.root, claim.path);\n const detail = deleted\n ? ` – deleted in ${deleted.hash.slice(0, 7)} \"${deleted.subject}\" (${deleted.date.slice(0, 10)})`\n : \"\";\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` no longer exists${detail}`,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: deleted,\n everTracked: true,\n parentDirExists: await exists(\n path.join(ctx.root, path.dirname(claim.path))\n ),\n },\n });\n continue;\n }\n\n const parentDirExists = await exists(\n path.join(ctx.root, path.dirname(claim.path))\n );\n if (!parentDirExists) continue;\n\n const issue: AuditIssue = {\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` does not exist (never tracked in git – possible typo or invented path)`,\n anchor,\n confidence: \"likely\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: null,\n everTracked: false,\n parentDirExists: true,\n },\n };\n result.issues.push(issue);\n }\n }\n\n return result;\n}\n","import fg from \"fast-glob\";\nimport path from \"node:path\";\nimport { SOURCE_GLOB, SOURCE_IGNORE } from \"../../snapshot/snapshot.js\";\nimport { firstCommitOf } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Directories that are never \"modules\" worth documenting. */\nconst DIR_DENYLIST = new Set([\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \"coverage\",\n \"target\",\n \"vendor\",\n \"__pycache__\",\n \"venv\",\n \".venv\",\n \".git\",\n \".gradle\",\n \".mason\",\n \".claude\",\n \".github\",\n \".vscode\",\n \".idea\",\n]);\n\n/** Second-level dirs need a bit more substance before they count. */\nconst SECOND_LEVEL_MIN_SOURCE_FILES = 2;\n/**\n * Descend into a top-level dir only when the docs evidently enumerate its\n * children — at least this many of its subdirs already mentioned.\n */\nconst ENUMERATION_THRESHOLD = 2;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Word-boundary mention check across the union of all docs — `app` must not\n * match \"application\", and a dir mentioned only in AGENTS.md must not be\n * flagged against CLAUDE.md.\n */\nfunction isMentioned(combinedDocs: string, name: string): boolean {\n const re = new RegExp(\n `(^|[^A-Za-z0-9_-])${escapeRegExp(name)}(/|[^A-Za-z0-9_-]|$)`,\n \"im\"\n );\n return re.test(combinedDocs);\n}\n\nasync function listSubdirs(absDir: string): Promise<string[]> {\n const dirs = await fg(\"*\", {\n cwd: absDir,\n onlyDirectories: true,\n suppressErrors: true,\n });\n return dirs.filter((d) => !DIR_DENYLIST.has(d)).sort();\n}\n\nasync function countSourceFiles(absDir: string): Promise<number> {\n const files = await fg(SOURCE_GLOB, {\n cwd: absDir,\n ignore: SOURCE_IGNORE,\n suppressErrors: true,\n });\n return files.length;\n}\n\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = ctx.docs.map((d) => d.content).join(\"\\n\");\n const primaryDoc = ctx.docs[0].path;\n const checkedDocs = ctx.docs.map((d) => d.path);\n\n const flag = async (dir: string, sourceFileCount: number): Promise<void> => {\n result.issues.push({\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in any context file`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\n confidence: \"likely\",\n evidence: {\n kind: \"unmentioned-dir\",\n dir,\n sourceFileCount,\n firstCommit: await firstCommitOf(ctx.root, dir),\n checkedDocs,\n },\n });\n };\n\n for (const topDir of await listSubdirs(ctx.root)) {\n const absTop = path.join(ctx.root, topDir);\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(absTop);\n if (count >= 1) await flag(topDir, count);\n continue;\n }\n\n // The docs know this dir. If they enumerate its children (several\n // subdirs already mentioned), an unmentioned sibling is drift — this is\n // how a freshly added module under src/ gets caught.\n const subdirs = await listSubdirs(absTop);\n const mentioned = subdirs.filter((s) => isMentioned(combinedDocs, s));\n if (mentioned.length < ENUMERATION_THRESHOLD) continue;\n\n for (const sub of subdirs) {\n if (isMentioned(combinedDocs, sub)) continue;\n const count = await countSourceFiles(path.join(absTop, sub));\n if (count >= SECOND_LEVEL_MIN_SOURCE_FILES) {\n await flag(`${topDir}/${sub}`, count);\n }\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CountClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MEMBERS_CAP = 50;\n\ninterface CountSource {\n actual: number;\n countedFrom: string;\n members: string[];\n}\n\nasync function readIfExists(absPath: string): Promise<string | null> {\n try {\n return await fs.readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readIfExists(path.join(root, name));\n if (content === null) continue;\n // include(\":a\", \":b\") — count quoted project strings, not include() calls.\n const members: string[] = [];\n for (const call of content.matchAll(/include\\s*\\(([^)]*)\\)/g)) {\n for (const proj of call[1].matchAll(/[\"']([^\"']+)[\"']/g)) {\n members.push(proj[1]);\n }\n }\n if (members.length === 0) return null;\n return { actual: members.length, countedFrom: name, members };\n }\n return null;\n}\n\nasync function countNpmWorkspaces(root: string): Promise<CountSource | null> {\n const pkgRaw = await readIfExists(path.join(root, \"package.json\"));\n if (pkgRaw !== null) {\n try {\n const pkg = JSON.parse(pkgRaw);\n const globs: string[] = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n } catch {\n // Malformed package.json — nothing provable here.\n }\n }\n\n const pnpmRaw = await readIfExists(path.join(root, \"pnpm-workspace.yaml\"));\n if (pnpmRaw !== null) {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of pnpmRaw.split(\"\\n\")) {\n if (/^packages\\s*:/.test(line)) {\n inPackages = true;\n continue;\n }\n if (inPackages) {\n const entry = line.match(/^\\s*-\\s*[\"']?([^\"'#\\s]+)/);\n if (entry) {\n if (!entry[1].startsWith(\"!\")) globs.push(entry[1]);\n } else if (line.trim().length > 0 && !line.startsWith(\" \")) {\n inPackages = false;\n }\n }\n }\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"pnpm-workspace.yaml\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n return null;\n}\n\nasync function countCargoCrates(root: string): Promise<CountSource | null> {\n const content = await readIfExists(path.join(root, \"Cargo.toml\"));\n if (content === null) return null;\n const membersBlock = content.match(/members\\s*=\\s*\\[([\\s\\S]*?)\\]/);\n if (!membersBlock) return null;\n const entries = [...membersBlock[1].matchAll(/[\"']([^\"']+)[\"']/g)].map(\n (m) => m[1]\n );\n if (entries.length === 0) return null;\n\n // Workspace members may be globs (\"crates/*\") — resolve them against\n // directories that actually contain a Cargo.toml.\n const members = new Set<string>();\n for (const entry of entries) {\n if (/[*?[\\]{}]/.test(entry)) {\n const matched = await fg(`${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n cwd: root,\n ignore: [\"**/target/**\"],\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readIfExists(path.join(root, entry, \"Cargo.toml\"))) !== null\n ) {\n members.add(entry);\n }\n }\n if (members.size === 0) return null;\n return {\n actual: members.size,\n countedFrom: \"Cargo.toml workspace members\",\n members: [...members].sort(),\n };\n}\n\n/**\n * Map a claim's unit to the ecosystem that can prove it. When the mapped\n * ecosystem has no workspace manifest in this repo, the claim is skipped —\n * \"12 packages\" in a Gradle repo proves nothing either way.\n */\nasync function resolveCountSource(\n root: string,\n claim: CountClaim\n): Promise<CountSource | null> {\n const unit = claim.unit.replace(/s$/, \"\");\n if (unit === \"module\") return countGradleModules(root);\n if (unit === \"workspace\") return countNpmWorkspaces(root);\n if (unit === \"crate\") return countCargoCrates(root);\n // \"packages\" is ecosystem-ambiguous — first manifest that resolves wins.\n return (\n (await countNpmWorkspaces(root)) ??\n (await countCargoCrates(root)) ??\n (await countGradleModules(root))\n );\n}\n\nexport async function checkStaleCounts(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n for (const claim of doc.claims.counts) {\n const source = await resolveCountSource(ctx.root, claim);\n if (source === null) {\n result.skipped.push({ check: \"stale-count\", doc: doc.path,\n reason: `${doc.path}: cannot resolve a workspace manifest for \"${claim.excerpt}\"` });\n continue;\n }\n if (source.actual === claim.count) continue;\n result.issues.push({\n type: \"stale-count\",\n message: `says \"${claim.excerpt}\" but ${source.countedFrom} resolves to ${source.actual}`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"count-mismatch\",\n claimed: claim.count,\n actual: source.actual,\n unit: claim.unit,\n countedFrom: source.countedFrom,\n members: source.members.slice(0, MEMBERS_CAP),\n },\n });\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\n\nasync function scriptsOf(absManifest: string): Promise<string[] | null> {\n try {\n const pkg = JSON.parse(await fs.readFile(absManifest, \"utf-8\"));\n return pkg && typeof pkg.scripts === \"object\" && pkg.scripts !== null\n ? Object.keys(pkg.scripts)\n : [];\n } catch {\n return null;\n }\n}\n\n/**\n * `npm run <script>` claims checked against package.json scripts — the one\n * ecosystem where task discovery is a single JSON parse. A script missing\n * from the root manifest is searched in every workspace manifest before\n * being flagged; docs legitimately say \"in packages/foo run `npm run build`\".\n */\nexport async function checkDeadCommands(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n const commandClaims = ctx.docs.flatMap((doc) =>\n doc.claims.commands.map((claim) => ({ doc, claim }))\n );\n if (commandClaims.length === 0) return result;\n\n const rootScripts = await scriptsOf(path.join(ctx.root, \"package.json\"));\n if (rootScripts === null) {\n result.skipped.push({\n check: \"dead-command\",\n reason: \"no package.json at the repo root\",\n });\n return result;\n }\n const rootSet = new Set(rootScripts);\n\n let workspaceScripts: Set<string> | null = null;\n let manifestsChecked: string[] = [\"package.json\"];\n const loadWorkspaceScripts = async (): Promise<Set<string>> => {\n if (workspaceScripts !== null) return workspaceScripts;\n workspaceScripts = new Set<string>();\n const manifests = await fg(\"**/package.json\", {\n cwd: ctx.root,\n ignore: [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"package.json\",\n ],\n });\n manifestsChecked = [\"package.json\", ...manifests.sort()];\n for (const manifest of manifests) {\n const scripts = await scriptsOf(path.join(ctx.root, manifest));\n for (const name of scripts ?? []) workspaceScripts.add(name);\n }\n return workspaceScripts;\n };\n\n for (const { doc, claim } of commandClaims) {\n if (rootSet.has(claim.scriptName)) continue;\n const elsewhere = await loadWorkspaceScripts();\n if (elsewhere.has(claim.scriptName)) continue;\n\n result.issues.push({\n type: \"dead-command\",\n message: `\\`${claim.invocation}\\` refers to script \"${claim.scriptName}\", which exists in no package.json`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"missing-script\",\n scriptName: claim.scriptName,\n invocation: claim.invocation,\n manifestsChecked,\n availableScripts: rootScripts.slice(0, AVAILABLE_SCRIPTS_CAP),\n },\n });\n }\n\n return result;\n}\n","import { commitsTouchingSince } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MANIFEST_COMMITS_CAP = 10;\n\n/**\n * Tracked manifest files at any depth. Lockfiles are pure churn and are\n * deliberately not matched.\n */\nconst MANIFEST_PATHSPECS = [\n \":(glob)**/package.json\",\n \":(glob)**/build.gradle.kts\",\n \":(glob)**/build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \":(glob)**/Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n];\n\n/**\n * Advisory, never an issue: a manifest commit after the doc's last commit\n * proves recency ordering, not that any specific claim is false — and it can\n * never be closed by editing the doc within the same run.\n */\nexport async function checkDepsChanged(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n result.suppressedAdvisories = [];\n\n for (const doc of ctx.docs) {\n if (!doc.lastCommit) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has no commit history`,\n });\n continue;\n }\n if (doc.dirty) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has uncommitted edits – suppressed while in flight`,\n });\n }\n\n const range = await commitsTouchingSince(\n ctx.root,\n doc.lastCommit.hash,\n MANIFEST_PATHSPECS\n );\n if (range === null) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path}: commit range unreachable (shallow clone?)`,\n });\n continue;\n }\n if (range.total === 0) continue;\n\n const latest = range.commits[0];\n (doc.dirty ? result.suppressedAdvisories : result.advisories).push({\n type: \"deps-changed\",\n message: `dependency manifests touched by ${range.total} commit${range.total === 1 ? \"\" : \"s\"} since ${doc.path} was last committed (latest: ${latest.hash.slice(0, 7)} \"${latest.subject}\")`,\n anchor: { doc: doc.path, line: null, excerpt: null },\n evidence: {\n kind: \"doc-behind-manifests\",\n docLastCommit: doc.lastCommit,\n manifestCommits: range.commits.slice(0, MANIFEST_COMMITS_CAP),\n totalCommits: range.total,\n },\n });\n }\n\n return result;\n}\n","import path from \"node:path\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { loadDecisionStore } from \"./decisions.js\";\nimport type { DecisionRecord } from \"./decisions.js\";\nimport { effectiveDecision } from \"./provenance.js\";\n\n/**\n * Deliberately separate from DriftReport: mason-drift's exit codes and\n * --json shape are a CI contract, and `stale` there means MAP staleness.\n * Decision staleness is additive on top.\n */\nexport interface DecisionDriftReport {\n historyAvailable: boolean;\n freshness?: Record<string, Freshness>;\n diagnostics?: StoreDiagnostic[];\n totalDecisions: number;\n /** Decision id → anchor files changed since the record's refreshedHash. */\n staleDecisions: Record<string, string[]>;\n /** Draft anchors have their own freshness; they cannot replace accepted anchors. */\n pendingProposals?: Record<string, { freshness: Freshness; changedFiles: string[] }>;\n}\n\n/**\n * Flag active decisions whose anchor files changed since the record was\n * last verified. Anchorless decisions have unknown freshness and do not\n * contribute to committed drift.\n * Deterministic — git only, no LLM.\n */\nexport async function computeDecisionDrift(\n rootDir: string,\n decisions?: DecisionRecord[]\n): Promise<DecisionDriftReport> {\n const resolvedRoot = path.resolve(rootDir);\n const store = decisions ? { records: decisions, diagnostics: [] } : await loadDecisionStore(resolvedRoot);\n const report: DecisionDriftReport = { historyAvailable: true, totalDecisions: store.records.length, staleDecisions: {}, freshness: {}, diagnostics: store.diagnostics };\n const [head, workingTree] = await Promise.all([getCurrentGitHash(resolvedRoot), getWorkingTree(resolvedRoot)]);\n const changesByHash = new Map<string, string[] | null>();\n const inspect = async (record: DecisionRecord): Promise<{ freshness: Freshness; changedFiles: string[] }> => {\n if (record.files.length === 0) return { freshness: \"unknown\", changedFiles: [] };\n let touched = changesByHash.get(record.refreshedHash);\n if (touched === undefined) {\n const changes = record.refreshedHash === head && head !== \"unknown\" ? [] : await getChangesWithStatus(resolvedRoot, record.refreshedHash);\n touched = changes === null ? null : touchedPaths(changes);\n changesByHash.set(record.refreshedHash, touched);\n }\n if (touched === null) report.historyAvailable = false;\n const hits = touched ? matchingPaths(record.files, touched) : [];\n const localHits = matchingPaths(record.files, workingTree.changedFiles);\n return { freshness: touched === null || !workingTree.available ? \"unknown\" : hits.length || localHits.length ? \"changed\" : \"current\", changedFiles: hits };\n };\n for (const record of store.records) {\n if (record.status !== \"active\") continue;\n const effective = effectiveDecision(record);\n const state = await inspect(effective);\n report.freshness![record.id] = state.freshness;\n if (state.changedFiles.length) report.staleDecisions[record.id] = state.changedFiles;\n if (effective !== record) (report.pendingProposals ??= {})[record.id] = await inspect(record);\n }\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { readStoreJson, writeStoreJson, storePath, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { jaccard, tokenSet } from \"../context/lexical.js\";\nimport { attributionSchema, decisionSchema, decisionContent, decisionApproval, effectiveDecision, importLegacy, type DecisionSource, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nexport type { DecisionRecord } from \"./provenance.js\";\n\nexport type DecisionCategory =\n | \"decision\"\n | \"gotcha\"\n | \"deprecation\"\n | \"convention\";\nexport type DecisionStatus = \"active\" | \"superseded\" | \"retired\";\n\nexport const TITLE_MAX_CHARS = 80;\nexport const BODY_MAX_CHARS = 1500;\nexport const MAX_ACTIVE_DECISIONS = 150;\n\nconst DUPLICATE_JACCARD = 0.5;\nconst DUPLICATE_JACCARD_WITH_SHARED_FILE = 0.35;\n\nexport async function loadDecisionStore(rootDir: string): Promise<{ records: DecisionRecord[]; diagnostics: StoreDiagnostic[] }> {\n const records: DecisionRecord[] = [];\n const diagnostics: StoreDiagnostic[] = [];\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, \".mason/decisions\")); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") diagnostics.push({ path: \".mason/decisions\", message: String(error) });\n return { records, diagnostics };\n }\n for (const entry of entries.sort()) {\n if (!entry.endsWith(\".json\")) continue;\n const relative = `.mason/decisions/${entry}`;\n try {\n const record = decisionSchema.parse(await readStoreJson(rootDir, relative));\n if (entry !== `${record.id}.json`) throw new Error(\"Record id does not match its filename\");\n records.push(record);\n } catch (error) { diagnostics.push({ path: relative, message: error instanceof Error ? error.message : String(error) }); }\n }\n return { records, diagnostics };\n}\n\nexport async function loadDecisions(rootDir: string): Promise<DecisionRecord[]> {\n return (await loadDecisionStore(rootDir)).records;\n}\n\nexport async function saveDecisionRecord(rootDir: string, record: DecisionRecord): Promise<void> {\n const validated = decisionSchema.parse(record);\n await writeStoreJson(rootDir, `.mason/decisions/${validated.id}.json`, validated);\n}\n\n/**\n * Deterministic, human-readable id: kebab slug of the title, ≤60 chars.\n * A slug collision with a DIFFERENT record appends a 6-hex content suffix.\n */\nexport function decisionIdFor(\n title: string,\n body: string,\n existingIds: Set<string>\n): string {\n const slug = title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60)\n .replace(/-+$/, \"\");\n if (!existingIds.has(slug)) return slug || \"decision\";\n const suffix = createHash(\"sha1\")\n .update(title + body)\n .digest(\"hex\")\n .slice(0, 6);\n return `${slug}-${suffix}`;\n}\n\nexport function findNearDuplicate(\n candidate: { title: string; body: string; files: string[] },\n existing: DecisionRecord[]\n): { record: DecisionRecord; similarity: number } | null {\n const candidateTokens = tokenSet(`${candidate.title} ${candidate.body}`);\n const candidateFiles = new Set(candidate.files);\n let best: { record: DecisionRecord; similarity: number } | null = null;\n\n for (const record of existing) {\n if (record.status !== \"active\") continue;\n const similarity = jaccard(\n candidateTokens,\n tokenSet(`${record.title} ${record.body}`)\n );\n const sharesFile = record.files.some((f) => candidateFiles.has(f));\n const threshold = sharesFile\n ? DUPLICATE_JACCARD_WITH_SHARED_FILE\n : DUPLICATE_JACCARD;\n if (similarity >= threshold && (!best || similarity > best.similarity)) {\n best = { record, similarity };\n }\n }\n return best;\n}\n\nexport interface UpsertDecisionInput {\n title: string;\n body: string;\n category: DecisionCategory;\n files?: string[];\n owner?: string | null;\n sources?: DecisionSource[];\n /** Only supply a known identity; never infer authorship from Git configuration. */\n actor?: string;\n /** Existing id to revise. Unchanged content is a no-op; use review_decision to reaffirm. */\n id?: string;\n /** Id of a decision this one replaces; the old record is kept, marked superseded. */\n supersedes?: string;\n /** Save even when a near-duplicate was detected. */\n force?: boolean;\n}\n\nexport type UpsertDecisionResult =\n | {\n status: \"created\" | \"updated\" | \"unchanged\" | \"superseded_and_created\";\n id: string;\n totalActive: number;\n warnings: string[];\n approval?: \"unreviewed\" | \"proposed\" | \"accepted\";\n hint?: string;\n pruneCandidates?: string[];\n }\n | { status: \"duplicate_suspected\"; existing: DecisionRecord; hint: string }\n | { status: \"error\"; error: string };\n\n/** Serialize tool writes so prepared reviews cannot overwrite another decision edit. */\nexport async function withDecisionWrite<T>(root: string, operation: () => Promise<T>): Promise<T | { status: \"error\"; error: string }> {\n const lockPath = await storePath(root, \".mason/decisions/.write-lock\", true);\n let lock;\n try { lock = await fs.open(lockPath, \"wx\", 0o600); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return { status: \"error\", error: \"Decision store is locked by another write. Retry after it finishes; an abandoned .mason/decisions/.write-lock must be removed only after confirming no writer is running.\" };\n throw error;\n }\n try { return await operation(); }\n finally { await lock.close(); await fs.unlink(lockPath); }\n}\n\nexport async function upsertDecision(rootDir: string, input: UpsertDecisionInput): Promise<UpsertDecisionResult> {\n const title = input.title.trim(), body = input.body.trim();\n if (!title || !body) return { status: \"error\", error: \"title and body must be non-empty\" };\n if (title.length > TITLE_MAX_CHARS) return { status: \"error\", error: `title exceeds ${TITLE_MAX_CHARS} chars — tighten it to a specific headline` };\n if (body.length > BODY_MAX_CHARS) return { status: \"error\", error: `body exceeds ${BODY_MAX_CHARS} chars — record the decision, not the transcript` };\n const attribution = attributionSchema.safeParse(input);\n if (!attribution.success) return { status: \"error\", error: attribution.error.message };\n if (input.id && input.supersedes) return { status: \"error\", error: \"Use either id to revise or supersedes to replace a record, not both.\" };\n return withDecisionWrite(rootDir, async () => {\n const store = await loadDecisionStore(rootDir);\n if (store.diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before saving: \" + store.diagnostics.map(d => d.path).join(\", \") };\n const existing = store.records, byId = new Map(existing.map(r => [r.id, r]));\n const now = new Date().toISOString(), head = await getCurrentGitHash(rootDir);\n const warnings: string[] = [];\n const files = sanitizeRepoPaths(input.files ?? []);\n if (input.files && files.length < input.files.length) warnings.push(\"some anchor paths were outside the repo or duplicated and were dropped\");\n for (const file of files) {\n try { await fs.access(path.join(rootDir, file)); }\n catch { warnings.push(`anchor file does not exist on disk: ${file}`); }\n }\n const hint = \"Saved locally for review and commit. Proposals are not accepted constraints; an existing accepted revision remains operative while its replacement is proposed. Use review_decision to inspect evidence and record an authorized acceptance or reaffirmation.\";\n if (input.id) {\n const original = byId.get(input.id);\n if (!original) return { status: \"error\", error: `no decision with id \"${input.id}\"` };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived records cannot be revised; create a new proposal.\" };\n const record = importLegacy(original, now);\n const content = decisionContent({ ...record, title, body, category: input.category,\n files: input.files !== undefined ? files : record.files,\n owner: attribution.data.owner === undefined ? record.owner : attribution.data.owner ?? undefined,\n sources: attribution.data.sources ?? record.sources,\n });\n if (JSON.stringify(content) === JSON.stringify(decisionContent(record))) {\n return { status: \"unchanged\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: decisionApproval(original), warnings,\n hint: \"Unchanged content; no review or freshness stamp was written. Use review_decision for explicit re-verification.\" };\n }\n const revision = record.revision + 1;\n const updated: ReviewedDecisionRecord = { ...record, ...content, owner: content.owner, updatedAt: now, revision, approval: \"proposed\",\n history: [...record.history, { kind: \"revised\", at: now, actor: attribution.data.actor, revision, content, approval: \"proposed\", status: \"active\", refreshedHash: record.refreshedHash }],\n };\n await saveDecisionRecord(rootDir, updated);\n return { status: \"updated\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: \"proposed\", warnings, hint };\n }\n const old = input.supersedes ? byId.get(input.supersedes) : undefined;\n if (input.supersedes && !old) return { status: \"error\", error: `no decision with id \"${input.supersedes}\" to supersede` };\n if (old && (old.status !== \"active\" || decisionApproval(effectiveDecision(old)) === \"accepted\")) {\n return { status: \"error\", error: \"A proposal cannot supersede an accepted or archived record. Create and review the replacement separately, then explicitly retire the old decision with review_decision.\" };\n }\n if (!input.force) {\n const duplicate = findNearDuplicate({ title, body, files }, existing);\n if (duplicate) return { status: \"duplicate_suspected\", existing: duplicate.record, hint: `A similar decision exists (\"${duplicate.record.title}\"). Call save_decision with id=\"${duplicate.record.id}\" to revise it, or force:true if distinct.` };\n }\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n if (byId.has(id)) return { status: \"error\", error: `Decision id collision: ${id}. Choose a distinct title or revise the existing record.` };\n const content = decisionContent({ title, body, category: input.category, files, owner: attribution.data.owner ?? undefined, sources: attribution.data.sources ?? [] });\n const record: ReviewedDecisionRecord = { ...content, version: 2, id, createdAt: now, updatedAt: now, refreshedHash: head,\n status: \"active\", approval: \"proposed\", revision: 1,\n history: [{ kind: \"created\", at: now, actor: attribution.data.actor, revision: 1, content, approval: \"proposed\", status: \"active\", refreshedHash: head }],\n };\n // Write the replacement first: a failed second write leaves both records\n // available instead of removing the original before its replacement exists.\n await saveDecisionRecord(rootDir, record);\n if (old) {\n const imported = importLegacy(old, now);\n await saveDecisionRecord(rootDir, { ...imported, status: \"superseded\", supersededBy: id, updatedAt: now,\n history: [...imported.history, { kind: \"superseded\", at: now, actor: attribution.data.actor, note: `Replaced by proposal ${id}`,\n revision: imported.revision, content: decisionContent(imported), approval: imported.approval, status: \"superseded\", refreshedHash: imported.refreshedHash }],\n });\n }\n const totalActive = existing.filter(r => r.status === \"active\").length + (old ? 0 : 1);\n const result: UpsertDecisionResult = { status: old ? \"superseded_and_created\" : \"created\", id, totalActive, approval: \"proposed\", warnings, hint };\n if (totalActive > MAX_ACTIVE_DECISIONS) {\n result.pruneCandidates = existing.filter(r => r.status !== \"active\").map(r => r.id).slice(0, 10);\n warnings.push(`${totalActive} active decisions exceeds the soft cap of ${MAX_ACTIVE_DECISIONS} — consider a cleanup PR (archived records first)`);\n }\n return result;\n });\n}\n","import path from \"node:path\";\n\n// Question/filler words that carry no signal about which entry a task\n// touches. Domain words (\"auth\", \"drift\") are never in this list.\nconst STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"and\", \"or\", \"of\", \"to\", \"in\", \"on\", \"for\", \"with\",\n \"how\", \"does\", \"do\", \"is\", \"are\", \"was\", \"what\", \"where\", \"which\", \"why\",\n \"when\", \"who\", \"i\", \"we\", \"my\", \"our\", \"you\", \"your\", \"it\", \"its\", \"this\",\n \"that\", \"these\", \"those\", \"can\", \"could\", \"should\", \"would\", \"will\",\n \"want\", \"need\", \"please\", \"about\", \"into\", \"from\", \"when\", \"there\", \"any\",\n \"all\", \"some\", \"not\", \"but\", \"also\", \"just\", \"like\", \"get\", \"make\", \"use\",\n \"new\", \"work\", \"works\", \"working\", \"implement\", \"implemented\", \"change\",\n \"changed\", \"file\", \"files\", \"code\",\n]);\n\n/** Split camelCase/PascalCase/kebab/snake/path into lowercase word tokens. */\nexport function tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 2 && !STOPWORDS.has(t));\n}\n\n/** Crude singular/plural folding so \"flows\" matches \"flow\" etc. */\nexport function stem(token: string): string {\n return token.length > 3 && token.endsWith(\"s\") ? token.slice(0, -1) : token;\n}\n\nexport function tokenSet(text: string): Set<string> {\n return new Set(tokenize(text).map(stem));\n}\n\nexport interface Scorable {\n name: string;\n description: string;\n files: string[];\n}\n\n/**\n * Lexical relevance of one entry to the task. Name hits are the strongest\n * signal, then description, then file-path words. Each distinct task token\n * counts once at its best weight, so a token appearing everywhere doesn't\n * triple-count.\n */\nexport function scoreEntry(taskTokens: Set<string>, entry: Scorable): number {\n const nameTokens = tokenSet(entry.name);\n const descTokens = tokenSet(entry.description);\n const fileTokens = tokenSet(entry.files.map((f) => path.basename(f)).join(\" \"));\n\n let score = 0;\n for (const token of taskTokens) {\n if (nameTokens.has(token)) score += 3;\n else if (descTokens.has(token)) score += 1;\n else if (fileTokens.has(token)) score += 1;\n }\n return score;\n}\n\n/** Jaccard similarity of two token sets: |∩| / |∪|, 0 when both empty. */\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersection = 0;\n for (const token of a) if (b.has(token)) intersection++;\n return intersection / (a.size + b.size - intersection);\n}\n","import { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { assessTrust, type Freshness } from \"../context/trust.js\";\n\nconst text = (max: number) => z.string().trim().min(1).max(max);\nexport const decisionSourceSchema = z.object({\n kind: z.enum([\"pull_request\", \"issue\", \"incident\", \"discussion\", \"document\", \"other\"]),\n reference: text(1000),\n note: text(500).optional(),\n}).strict();\nexport type DecisionSource = z.infer<typeof decisionSourceSchema>;\nexport const attributionSchema = z.object({\n owner: text(200).nullable().optional(),\n sources: z.array(decisionSourceSchema).max(20).optional(),\n actor: text(200).optional(),\n});\nconst contentSchema = z.object({\n title: z.string().min(1), body: z.string().min(1),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z.array(z.string().refine(f => normalizeRepoPath(f) !== null)),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n});\nconst approvalSchema = z.enum([\"unreviewed\", \"proposed\", \"accepted\"]);\nconst statusSchema = z.enum([\"active\", \"superseded\", \"retired\"]);\nexport const reviewEvidenceSchema = z.object({\n baseHash: z.string(), headHash: z.string(), historyAvailable: z.boolean(),\n changedFiles: z.array(z.string()), localChanges: z.array(z.string()),\n});\nconst eventSchema = z.object({\n kind: z.enum([\"imported\", \"created\", \"revised\", \"accepted\", \"reaffirmed\", \"retired\", \"superseded\"]),\n at: z.string().datetime(), actor: text(200).optional(), note: text(1500).optional(),\n revision: z.number().int().positive(), content: contentSchema,\n approval: approvalSchema, status: statusSchema, refreshedHash: z.string(),\n evidence: reviewEvidenceSchema.optional(),\n});\nexport type DecisionEvent = z.infer<typeof eventSchema>;\nexport type DecisionApproval = z.infer<typeof approvalSchema>;\nexport type DecisionContent = z.infer<typeof contentSchema>;\n\nconst legacySchema = z.object({\n version: z.literal(1), id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n title: z.string().min(1), body: z.string().min(1),\n category: contentSchema.shape.category, files: contentSchema.shape.files,\n createdAt: z.string(), updatedAt: z.string(), refreshedHash: z.string(),\n status: z.enum([\"active\", \"superseded\"]), supersededBy: z.string().optional(),\n}).passthrough();\nconst currentSchema = legacySchema.extend({\n version: z.literal(2), status: statusSchema,\n approval: approvalSchema, revision: z.number().int().positive(),\n owner: text(200).optional(), sources: z.array(decisionSourceSchema).max(20),\n history: z.array(eventSchema).min(1),\n}).superRefine((record, ctx) => {\n const invalid = (message: string) => ctx.addIssue({ code: \"custom\", message });\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n let previous: DecisionEvent | undefined;\n for (const event of record.history) {\n if (!previous) {\n if (![\"created\", \"imported\"].includes(event.kind) || event.revision !== 1) invalid(\"History must begin with creation or legacy import at revision 1\");\n if (event.approval !== (event.kind === \"created\" ? \"proposed\" : \"unreviewed\")) invalid(\"Initial records cannot claim acceptance\");\n } else {\n if ([\"created\", \"imported\"].includes(event.kind)) invalid(\"History cannot restart\");\n if (previous.status !== \"active\") invalid(\"Archived decisions cannot be changed\");\n if (event.revision !== previous.revision + (event.kind === \"revised\" ? 1 : 0)) invalid(\"Invalid revision sequence\");\n if (event.kind !== \"revised\" && !same(event.content, previous.content)) invalid(\"A review cannot silently revise decision content\");\n if (event.kind === \"reaffirmed\" && previous.approval !== \"accepted\") invalid(\"Only accepted decisions can be reaffirmed\");\n if (event.kind === \"accepted\" && previous.approval === \"accepted\") invalid(\"Use reaffirmation for an accepted decision\");\n const approval = event.kind === \"revised\" ? \"proposed\" : [\"accepted\", \"reaffirmed\"].includes(event.kind) ? \"accepted\" : previous.approval;\n if (event.approval !== approval) invalid(\"Approval disagrees with review history\");\n if (![\"accepted\", \"reaffirmed\"].includes(event.kind) && event.refreshedHash !== previous.refreshedHash) invalid(\"Only a review can refresh the evidence baseline\");\n }\n if (event.kind !== \"imported\" && event.status !== (event.kind === \"retired\" ? \"retired\" : event.kind === \"superseded\" ? \"superseded\" : \"active\")) invalid(\"Lifecycle disagrees with history\");\n if ([\"accepted\", \"reaffirmed\", \"retired\"].includes(event.kind) && (!event.actor || !event.note || !event.evidence)) invalid(\"Reviews require a named reviewer, reason, and code evidence\");\n if ([\"accepted\", \"reaffirmed\"].includes(event.kind)) {\n if (!event.content.owner || !event.content.sources.length) invalid(\"Accepted decisions require an owner and source\");\n if (!event.evidence || !/^[a-f0-9]{40,64}$/.test(event.evidence.headHash) || event.refreshedHash !== event.evidence.headHash || event.evidence.localChanges.length) invalid(\"Acceptance requires a committed evidence baseline\");\n }\n previous = event;\n }\n if (!previous || !same(previous.content, decisionContent(record)) || previous.approval !== record.approval || previous.status !== record.status || previous.revision !== record.revision || previous.refreshedHash !== record.refreshedHash) invalid(\"Decision does not match the final history event\");\n});\n\nexport const decisionSchema = z.union([legacySchema, currentSchema]);\nexport type DecisionRecord = z.infer<typeof decisionSchema>;\nexport type ReviewedDecisionRecord = z.infer<typeof currentSchema>;\n\nexport function decisionContent(record: Pick<DecisionRecord, \"title\" | \"body\" | \"category\" | \"files\"> & { owner?: unknown; sources?: unknown }): DecisionContent {\n return { title: record.title, body: record.body, category: record.category, files: record.files,\n ...(typeof record.owner === \"string\" ? { owner: record.owner } : {}),\n sources: Array.isArray(record.sources) ? record.sources as DecisionSource[] : [],\n };\n}\n\n/** Reading legacy records never upgrades their approval or rewrites their files. */\nexport function decisionApproval(record: DecisionRecord): DecisionApproval {\n return record.version === 1 ? \"unreviewed\" : record.approval;\n}\n\n/** The last accepted revision remains operative while a replacement is drafted.\n * This is a read-only projection; writes and review tokens use the complete record.\n * Archived records never regain authority from their history.\n */\nexport function effectiveDecision(record: DecisionRecord): DecisionRecord {\n if (record.version !== 2 || record.status !== \"active\" || record.approval !== \"proposed\") return record;\n let index = record.history.length - 1;\n while (index >= 0 && ![\"accepted\", \"reaffirmed\"].includes(record.history[index].kind)) index--;\n if (index < 0) return record;\n const event = record.history[index];\n return { ...record, ...event.content, owner: event.content.owner, approval: \"accepted\", revision: event.revision,\n refreshedHash: event.refreshedHash, updatedAt: event.at, history: record.history.slice(0, index + 1) };\n}\n\n/** Anchors relevant to either the operative knowledge or its pending proposal. */\nexport function decisionAnchors(record: DecisionRecord): string[] {\n return [...new Set([...effectiveDecision(record).files, ...record.files])];\n}\n\nexport function importLegacy(record: DecisionRecord, now: string): ReviewedDecisionRecord {\n if (record.version === 2) return record;\n // Ignore unrecognized legacy fields: they are not evidence of authorship or approval.\n const content = decisionContent({ title: record.title, body: record.body, category: record.category, files: record.files });\n return { id: record.id, createdAt: record.createdAt, updatedAt: record.updatedAt, status: record.status, refreshedHash: record.refreshedHash, supersededBy: record.supersededBy, ...content, version: 2, approval: \"unreviewed\", revision: 1,\n history: [{ kind: \"imported\", at: now, revision: 1, content, approval: \"unreviewed\", status: record.status, refreshedHash: record.refreshedHash,\n note: \"Imported a legacy record. Prior authorship and review history are unknown.\" }],\n };\n}\n\nexport function decisionProvenance(record: DecisionRecord, freshness: Freshness = \"unknown\") {\n const approval = decisionApproval(record);\n const review = record.version === 2 ? [...record.history].reverse().find(e => [\"accepted\", \"reaffirmed\"].includes(e.kind) && e.revision === record.revision) : undefined;\n return {\n approval, revision: record.version === 2 ? record.revision : 0,\n owner: record.version === 2 ? record.owner ?? null : null,\n sources: record.version === 2 ? record.sources : [],\n guidance: record.status !== \"active\" ? \"historical\" : approval === \"accepted\" ? \"constraint\" : approval === \"proposed\" ? \"proposal\" : \"unreviewed\",\n reviewRequired: record.status === \"active\" && (approval !== \"accepted\" || freshness !== \"current\"),\n lastReview: review ? { reviewer: review.actor!, at: review.at, note: review.note!, gitHash: review.refreshedHash } : null,\n };\n}\n\nexport function decisionTrust(record: DecisionRecord, freshness: Freshness) {\n const review = decisionProvenance(record, freshness).lastReview;\n return assessTrust(review ? { verifiedAt: review.at, verifiedHash: review.gitHash } : {}, freshness);\n}\n\nfunction revisionKnowledge(record: DecisionRecord, freshness: Freshness) {\n return { ...decisionContent(record), ...decisionProvenance(record, freshness), trust: decisionTrust(record, freshness) };\n}\n\n/** Readers show accepted content first and label the unaccepted draft separately. */\nexport function decisionKnowledge(record: DecisionRecord, freshness: Freshness = \"unknown\", proposalFreshness: Freshness = \"unknown\") {\n const effective = effectiveDecision(record);\n return { ...revisionKnowledge(effective, freshness),\n ...(effective !== record ? { pendingProposal: revisionKnowledge(record, proposalFreshness) } : {}) };\n}\n\nexport function compactDecisionKnowledge(...args: Parameters<typeof decisionKnowledge>) {\n const { body, pendingProposal, ...summary } = decisionKnowledge(...args);\n if (!pendingProposal) return summary;\n const { body: proposalBody, ...proposal } = pendingProposal;\n return { ...summary, pendingProposal: proposal };\n}\n\nexport const DECISION_GUIDANCE = \"Accepted decisions are recorded team constraints, subject to freshness checks. A pendingProposal is an unaccepted replacement; the accepted revision remains operative until explicit acceptance or retirement. Proposals are suggestions; legacy unreviewed records need confirmation. Use review_decision to inspect provenance and record an authorized review; identities and sources are recorded assertions, not authenticated proof.\";\n","import { computeDecisionDrift } from \"../../decisions/drift.js\";\nimport { loadDecisionStore } from \"../../decisions/decisions.js\";\nimport { decisionProvenance, effectiveDecision } from \"../../decisions/provenance.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/**\n * Advisory only, and only when .mason/decisions/ exists (the zero-setup\n * path stays dark on bare repos). Decision records encode human knowledge —\n * they are surfaced for re-verification, never rewritten by the fix agent.\n */\nexport async function checkDecisionAnchors(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n if (!ctx.decisionsPresent) return result;\n\n const store = await loadDecisionStore(ctx.root);\n const records = store.records;\n for (const diagnostic of store.diagnostics) result.skipped.push({ check: \"decision-anchor-drift\", reason: `${diagnostic.path}: ${diagnostic.message}` });\n const drift = await computeDecisionDrift(ctx.root, records);\n if (!drift.historyAvailable) {\n result.skipped.push({\n check: \"decision-anchor-drift\",\n reason: \"some decision base commits are unreachable (shallow clone?)\",\n });\n }\n\n const changed = records.flatMap(record => [\n { record: effectiveDecision(record), changedFiles: drift.staleDecisions[record.id] ?? [], freshness: drift.freshness?.[record.id] ?? \"unknown\" },\n { record, changedFiles: drift.pendingProposals?.[record.id]?.changedFiles ?? [], freshness: drift.pendingProposals?.[record.id]?.freshness ?? \"unknown\" },\n ] as const);\n for (const { record, changedFiles, freshness } of changed) {\n if (!changedFiles.length) continue;\n const id = record.id;\n const provenance = decisionProvenance(record, freshness);\n result.advisories.push({\n type: \"decision-anchor-drift\",\n message: `decision \"${record.title}\" (${provenance.approval}) has anchor files that changed since its evidence baseline – needs human review`,\n anchor: {\n doc: `.mason/decisions/${id}.json`,\n line: null,\n excerpt: record.title,\n },\n evidence: {\n kind: \"decision-anchor\",\n provenance,\n decisionId: id,\n title: record.title,\n changedFiles,\n refreshedHash: record.refreshedHash,\n },\n });\n }\n\n return result;\n}\n","import type { FileChange } from \"../../drift/drift.js\";\nimport type { AuditAdvisory, AuditIssue, CheckName } from \"../types.js\";\nimport type { AuditDoc } from \"../docs.js\";\nimport { checkDeletedReferences } from \"./deleted-reference.js\";\nimport { checkNewModules } from \"./new-module.js\";\nimport { checkStaleCounts } from \"./stale-count.js\";\nimport { checkDeadCommands } from \"./dead-command.js\";\nimport { checkDepsChanged } from \"./deps-changed.js\";\nimport { checkDecisionAnchors } from \"./decision-anchor.js\";\n\nexport interface CheckContext {\n root: string;\n docs: AuditDoc[];\n headHash: string;\n /** Doc path → changes since the doc's last commit; null when uncomputable. */\n changesSinceDoc: Map<string, FileChange[] | null>;\n /** Whether .mason/decisions/ exists. */\n decisionsPresent: boolean;\n}\n\nexport interface CheckResult {\n issues: AuditIssue[];\n advisories: AuditAdvisory[];\n suppressedAdvisories?: AuditAdvisory[];\n skipped: Array<{ check: string; reason: string; doc?: string }>;\n}\n\nexport type CheckFn = (ctx: CheckContext) => Promise<CheckResult>;\n\nexport const CHECKS: Record<CheckName, CheckFn> = {\n \"deleted-reference\": checkDeletedReferences,\n \"new-module\": checkNewModules,\n \"stale-count\": checkStaleCounts,\n \"dead-command\": checkDeadCommands,\n \"deps-changed\": checkDepsChanged,\n \"decision-anchor-drift\": checkDecisionAnchors,\n};\n\nexport function emptyResult(): CheckResult {\n return { issues: [], advisories: [], skipped: [] };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { z } from \"zod\";\nimport { DOC_CANDIDATES } from \"../audit/docs.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 { readBoundedFile } from \"../utils/files.js\";\nimport { storePath } from \"../utils/storage.js\";\n\nconst exec = promisify(execFile);\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 (await exec(\"git\", 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 = await fs.realpath((await git(root, \"rev-parse\", \"--absolute-git-dir\")).trim());\n let branch: string;\n try { branch = (await git(root, \"symbolic-ref\", \"--quiet\", \"HEAD\")).trim(); }\n catch { branch = \"detached\"; }\n return { root, gitDir, branch, directory: \".mason/reports/automation/\" + hash([root, gitDir, branch]).slice(0, 24) };\n}\n\nasync function content(root: string, file: string): Promise<string | null> {\n try {\n const value = await readBoundedFile(await storePath(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 ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\n/** Matches audit dependencies, including ignored manifests the existing checks inspect. */\nconst manifest = /(^|\\/)(package\\.json|pnpm-workspace\\.yaml|Cargo\\.toml|settings\\.gradle(?:\\.kts)?|build\\.gradle(?:\\.kts)?|libs\\.versions\\.toml|go\\.mod|pyproject\\.toml|requirements\\.txt|Gemfile|composer\\.json)$/;\nconst internal = (file: string) => file === \".mason\" || file === \".mason/reports\" || file.startsWith(\".mason/reports/\");\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 const [headText, status, inventory, index, shallowPath, replacements] = await Promise.all([\n git(root, \"rev-parse\", \"HEAD\"),\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", \".\", \":(exclude).mason/reports\"),\n fg(\"**/*\", { cwd: root, dot: true, onlyFiles: false, followSymbolicLinks: false, objectMode: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\", \".mason/reports/**\"] }),\n git(root, \"ls-files\", \"--stage\", \"-z\", \"--\", \".\", \":(exclude).mason/reports\"),\n git(root, \"rev-parse\", \"--git-path\", \"shallow\"),\n git(root, \"for-each-ref\", \"--format=%(refname) %(objectname)\", \"refs/replace\"),\n ]);\n const entries = inventory.filter(f => !internal(f.path) && f.path !== \".git\").sort((a, b) => a.path.localeCompare(b.path));\n const files = entries.map(f => f.path);\n if (files.length > 100000) throw new Error(\"Automation input inventory exceeds 100,000 paths; use an explicit scoped audit.\");\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 claims: Array<[string, boolean, boolean]> = [];\n for (const file of DOC_CANDIDATES) {\n const text = await content(root, file);\n docs[file] = text === null ? null : hash(text);\n docContents.push([file, text]);\n for (const claim of text ? extractClaims(text).paths : []) {\n if (internal(claim.path) || claim.path.startsWith(\".mason/\")) continue;\n // Explicit claims can name ignored files, directories, or symlink targets.\n const exists = async (p: string) => fs.access(path.resolve(root, p)).then(() => true, () => false);\n claims.push([claim.path, await exists(claim.path), await exists(path.dirname(claim.path))]);\n }\n }\n const metadata: Array<[string, string | null]> = [];\n for (const file of files) {\n if (manifest.test(file) || file.startsWith(\".mason/decisions/\") && file.endsWith(\".json\") || file === \".mason/config.json\") {\n metadata.push([file, await content(root, file)]);\n }\n }\n // The existing audit follows some directory symlinks. Refuse to cache an\n // unbounded external dependency instead of claiming its targets were checked.\n if (entries.some(f => f.dirent.isSymbolicLink())) throw new Error(\"Automation inventory contains a symbolic link; use an explicit audit to inspect its scope. No cached verification was recorded.\");\n const common = [1, engineVersion, head, shallow, replacements, docContents];\n const layout = hash(entries.map(f => [f.path, f.dirent.isDirectory() ? \"directory\" : \"file\"]));\n const manifests = hash(metadata.filter(([file]) => manifest.test(file)));\n const decisions = hash(metadata.filter(([file]) => !manifest.test(file)));\n const keys: Record<CheckName, string> = {\n \"deleted-reference\": hash([common, layout, claims]),\n \"new-module\": hash([common, layout]),\n \"stale-count\": hash([common, layout, manifests]),\n \"dead-command\": hash([common, layout, manifests]),\n \"deps-changed\": hash([common, status]),\n \"decision-anchor-drift\": hash([common, layout, decisions, status, index]),\n };\n return { fingerprint: hash(keys), 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 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, serialize: () => {\n const canonical = cacheSchema.shape.entries.parse(entries);\n return { version: 1, entries: canonical, digest: hash(canonical) };\n } };\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { z } from \"zod\";\nimport { storePath } from \"../utils/storage.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});\nexport type State = z.infer<typeof stateSchema>;\n\n/** Cross-process lock: a killed writer's lock is reclaimed only after its local PID is gone. */\nexport async function withLock<T>(root: string, directory: string, run: () => Promise<T>): Promise<T> {\n const file = await storePath(root, directory + \"/lock\", true);\n const deadline = Date.now() + 5000;\n let handle;\n while (!handle) {\n try {\n handle = await fs.open(file, \"wx\", 0o600);\n await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname() }));\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 // Renaming a stale lock arbitrates reclamation without unlinking a new writer's lock.\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(\"Automation is busy or its lock needs inspection: \" + 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 { z } from \"zod\";\nimport { automate, type AutomationEvent } from \"./runtime.js\";\nimport { hostSchema, type Host } from \"./store.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; 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)$/;\n return { cwd: input.cwd, name: input.hook_event_name, event: {\n event: lifecycle[input.hook_event_name], host, sessionId: input.session_id, toolId: input.tool_use_id,\n mutating: !!input.tool_name && !readOnly.test(input.tool_name),\n stopHookActive: input.stop_hook_active || input.permission_mode === \"plan\",\n } };\n}\n\nexport async function runAutomationHook(host: Host, stdin: string): Promise<Record<string, unknown> | null> {\n let name = \"\";\n try {\n if (Buffer.byteLength(stdin) > 1024 * 1024) throw new Error(\"Hook input exceeds 1 MiB.\");\n const input = normalizeHook(host, JSON.parse(stdin));\n name = input.name;\n const result = await automate(input.cwd, input.event);\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 = \"Mason automation unavailable; evidence capture/verification was not established. \" +\n (error instanceof Error ? error.message : String(error)).replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, \" \").slice(0, 700);\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;\nexport function hookConfig(host: Host, command = \"npx --no-install --package mason-context mason-auto\") {\n const handler = { type: \"command\", command: 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 { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { workspace } from \"./evidence.js\";\nimport { HOOK_EVENTS, hookConfig } from \"./adapters.js\";\nimport { withLock, type Host } from \"./store.js\";\n\nconst groupSchema = z.object({ hooks: z.array(z.object({ type: z.string(), command: z.string().optional() }).passthrough()) }).passthrough();\nconst configSchema = z.object({ hooks: z.record(z.array(groupSchema)).optional() }).passthrough();\nconst recordSchema = z.object({ version: z.literal(1), hosts: z.record(z.object({ command: z.string() })) });\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/automation-install\", () => installLocked(ws.root, host, command));\n}\n\nasync function installLocked(root: string, host: Host, command?: string) {\n const file = configPath(host);\n const existing = configSchema.parse(await readStoreJson(root, file) ?? {});\n const record = recordSchema.parse(await readStoreJson(root, \".mason/automation.json\") ?? { version: 1, hosts: {} });\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 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 (handler.command === previous || handler.command === newCommand))),\n })).filter(group => group.hooks.length);\n hooks[event].push(...desired.hooks[event]);\n }\n record.hosts[host] = { command: newCommand };\n await writeStoreJson(root, file, { ...existing, hooks });\n await writeStoreJson(root, \".mason/automation.json\", record);\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 raw = await readStoreJson(ws.root, \".mason/automation.json\");\n if (raw === null) return {};\n const record = recordSchema.parse(raw);\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 = configSchema.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 { runAutomationCli } from \"../src/automation/cli.js\";\n\nconst argv = process.argv.slice(2);\nlet input = \"\";\nif (argv.includes(\"hook\") && !argv.some(a => a === \"--help\" || a === \"-h\") && !process.stdin.isTTY) {\n for await (const chunk of process.stdin) {\n input += chunk.toString();\n if (Buffer.byteLength(input) > 1024 * 1024) break;\n }\n}\nprocess.exitCode = await runAutomationCli(argv, input);\n"],"mappings":";;;AAAA,SAAS,iBAAiB;;;ACA1B,SAAS,cAAAA,mBAAkB;;;ACA3B,OAAOC,UAAQ;AACf,OAAOC,YAAU;AACjB,SAAS,cAAAC,aAAY,cAAAC,mBAAkB;AACvC,SAAS,KAAAC,UAAS;;;ACHlB,OAAOC,SAAQ;AACf,OAAOC,YAAU;;;ACDjB,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;;;ACH1B,OAAOC,WAAU;AACjB,SAAS,YAAAC,iBAAg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AO,QAAQ,OAAO,QAAS,OAAM,IAAI,MAAM,yDAAyD;AAC5G,QAAI,WAAW,UAAU;AACvB,SAAG,IAAI,KAAK,UAAU,EAAE,GAAG,MAAM,iBAAiB,GAAG,GAAG,YAAY,MAAM,oBAAoB,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;AAC9G,aAAO;AAAA,IACT;AACA,QAAI,WAAW,QAAS,OAAM,IAAI,MAAM,iCAAiC,MAAM;AAC/E,UAAM,EAAE,OAAO,IAAI,MAAM,SAAS,KAAK,EAAE,OAAO,WAAW,CAAC;AAC5D,OAAG,IAAI,OAAO,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,UAAU,MAAM,CAAC;AACxE,WAAO,OAAO,WAAW,aAAa,IAAI,OAAO,WAAW,kBAAkB,IAAI;AAAA,EACpF,SAAS,OAAO;AACd,UAAM,UAAU,oCAAoC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACzG,QAAIA,MAAK,SAAS,MAAM,GAAG;AAAE,SAAG,IAAI,KAAK,UAAU,EAAE,eAAe,QAAQ,CAAC,CAAC;AAAG,aAAO;AAAA,IAAG;AAC3F,OAAG,IAAI,OAAO;AACd,WAAO;AAAA,EACT;AACF;;;A8BzDA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAI,QAAQ;AACZ,IAAI,KAAK,SAAS,MAAM,KAAK,CAAC,KAAK,KAAK,OAAK,MAAM,YAAY,MAAM,IAAI,KAAK,CAAC,QAAQ,MAAM,OAAO;AAClG,mBAAiB,SAAS,QAAQ,OAAO;AACvC,aAAS,MAAM,SAAS;AACxB,QAAI,OAAO,WAAW,KAAK,IAAI,OAAO,KAAM;AAAA,EAC9C;AACF;AACA,QAAQ,WAAW,MAAM,iBAAiB,MAAM,KAAK;","names":["randomUUID","fs","path","createHash","randomUUID","z","fs","path","fs","path","execFile","promisify","path","execFile","promisify","path","fs","path","fs","path","path","exec","promisify","execFile","exec","exec","promisify","execFile","exec","fs","path","execFile","promisify","hash","content","execFile","promisify","exec","exec","promisify","execFile","content","fs","path","fs","path","fs","path","fg","path","text","fg","path","count","fs","path","fg","fs","content","path","fg","fs","path","fg","fs","path","fg","manifest","path","fs","path","path","z","z","fs","path","path","fs","z","createHash","content","fs","randomUUID","path","fs","path","createHash","execFile","promisify","fg","z","exec","promisify","execFile","createHash","fs","fg","path","text","exists","z","fs","z","z","z","fs","text","report","randomUUID","notify","z","z","input","z","z","argv"]}
1
+ {"version":3,"sources":["../src/utils/paths.ts","../src/utils/files.ts","../src/utils/storage.ts","../src/automation/execution.ts","../src/test-map.ts","../src/snapshot/snapshot.ts","../src/drift/drift.ts","../src/audit/tree.ts","../src/audit/claims.ts","../src/audit/git.ts","../src/audit/docs.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/audit.ts","../src/audit/repair.ts","../src/automation/evidence.ts","../src/automation/store.ts","../src/automation/runtime.ts","../src/setup/model.ts","../src/setup/observations.ts","../src/automation/adapters.ts","../src/automation/install.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.ts","../src/review/review.ts","../src/mcp/onboarding.ts","../src/setup/files.ts","../src/setup/launcher.ts","../src/setup/config.ts","../src/setup/runtime.ts","../src/setup/status.ts","../src/setup/setup.ts","../src/automation/cli.ts","../bin/mason-auto.ts"],"sourcesContent":["import path from \"node:path\";\n\n/** One canonical representation for stored paths and decision anchors. */\nexport function normalizeRepoPath(value: string): string | null {\n const slash = value.replace(/\\\\/g, \"/\");\n if (!slash || slash.includes(\"\\0\") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;\n if (slash.split(\"/\").includes(\"..\")) return null;\n const normalized = path.posix.normalize(slash).replace(/\\/$/, \"\");\n return normalized === \".\" ? null : normalized;\n}\n\nexport function sanitizeRepoPaths(files: string[]): string[] {\n return [...new Set(files.map(normalizeRepoPath).filter((p): p is string => p !== null))];\n}\n\nexport function isWithinRoot(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nexport function anchorMatches(anchor: string, file: string): boolean {\n const a = normalizeRepoPath(anchor);\n const f = normalizeRepoPath(file);\n return a !== null && f !== null && (a === f || f.startsWith(`${a}/`));\n}\n\nexport function matchingPaths(anchors: string[], files: Iterable<string>): string[] {\n return [...new Set(files)].filter(file => anchors.some(anchor => anchorMatches(anchor, file)));\n}\n","import fs from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\nconst exec = promisify(execFile);\nexport const SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\", \"vue\", \"svelte\", \"kt\", \"kts\", \"java\", \"py\", \"go\", \"rs\", \"swift\", \"rb\", \"cs\", \"cpp\", \"c\", \"h\", \"hpp\", \"dart\", \"php\"];\nexport const SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(\",\")}}`;\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/.mason/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\", \"**/*.lock\",\n \"**/generated/**\", \"**/*.generated.*\", \"**/R.java\", \"**/BuildConfig.java\",\n \"**/package-lock.json\", \"**/yarn.lock\", \"**/pnpm-lock.yaml\",\n];\nexport const MAX_SOURCE_BYTES = 1024 * 1024;\nexport interface ProjectConfig { patterns?: string[]; alwaysInclude?: string[]; ignore?: string[] }\nexport interface SourceFile { path: string; content: string; totalLines: number }\n\nexport function isSensitiveFile(file: string): boolean {\n return file.split(/[\\\\/]/).some(part =>\n /^(?:\\.env(?:\\..*)?|id_rsa.*|id_ed25519.*)$|\\.(?:pem|key|p12|pfx|jks|keystore)$|credentials\\.|secret|^local\\.properties$/i.test(part)\n );\n}\n\n/** Bound reads even if a file grows after stat. Only read regular files. */\nexport async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {\n // Do not block on a FIFO or follow a symlink substituted after resolution.\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > maxBytes) return null;\n const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));\n let bytes = 0;\n while (bytes < buffer.length) {\n const result = await handle.read(buffer, bytes, buffer.length - bytes, null);\n if (result.bytesRead === 0) break;\n bytes += result.bytesRead;\n }\n return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString(\"utf8\");\n } finally { await handle.close(); }\n}\n\nexport async function loadProjectConfig(root: string): Promise<ProjectConfig> {\n try {\n const canonicalRoot = await fs.realpath(root);\n const configPath = await fs.realpath(path.join(root, \".mason/config.json\"));\n if (!isWithinRoot(canonicalRoot, configPath)) throw new Error(\"Project configuration resolves outside the repository\");\n const raw = await readBoundedFile(configPath, 64 * 1024);\n if (raw === null) throw new Error(\"Project configuration is not a regular file or exceeds 64 KiB\");\n const value = JSON.parse(raw);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Expected a configuration object\");\n const config: ProjectConfig = {};\n for (const key of [\"patterns\", \"alwaysInclude\", \"ignore\"] as const) {\n if (value[key] === undefined) continue;\n if (!Array.isArray(value[key]) || !value[key].every((s: unknown) => typeof s === \"string\")) {\n throw new Error(`Configuration ${key} must be an array of strings`);\n }\n config[key] = value[key];\n }\n return config;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new Error(`Cannot apply project file policy: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/** Scoped to one operation, so a later tool call sees newly edited files/ignores. */\nexport async function createFileAccess(rootDir: string) {\n const root = path.resolve(rootDir);\n const canonicalRoot = await fs.realpath(root).catch(() => root);\n const config = await loadProjectConfig(root);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n let gitFiles: Set<string> | null = null;\n try {\n const { stdout } = await exec(\"git\", [\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n gitFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch {\n // File-system projects are supported. Fail closed if this IS a Git repo.\n let inGit = false;\n try { await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: root }); inGit = true; } catch { /* no Git */ }\n if (inGit) throw new Error(\"Cannot enumerate Git files safely\");\n }\n\n async function resolve(file: string): Promise<string | null> {\n const relative = normalizeRepoPath(file);\n if (!relative || isSensitiveFile(relative) || (gitFiles && !gitFiles.has(relative))) return null;\n const candidate = path.join(root, relative);\n try {\n const real = await fs.realpath(candidate);\n if (!isWithinRoot(canonicalRoot, real) || isSensitiveFile(path.relative(canonicalRoot, real))) return null;\n const stat = await fs.stat(real);\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) return null;\n // A symlink must not bypass the target's ignore policy either.\n if (gitFiles && !gitFiles.has(path.relative(canonicalRoot, real).split(path.sep).join(\"/\"))) return null;\n return real;\n } catch { return null; }\n }\n\n async function list(patterns: string | string[] = SOURCE_GLOB, options: { deep?: number; dot?: boolean } = {}): Promise<string[]> {\n const found = await fg(patterns, { cwd: root, ignore, followSymbolicLinks: false, ...options });\n const safe = await Promise.all(found.map(async f => (await resolve(f)) ? f : null));\n return safe.filter((f): f is string => f !== null).sort();\n }\n\n async function read(file: string): Promise<SourceFile | null> {\n const relative = normalizeRepoPath(file);\n if (!relative) return null;\n const real = await resolve(relative);\n if (!real) return null;\n // Apply the same glob exclusions to explicit reads and symlink targets.\n for (const rel of new Set([relative, path.relative(canonicalRoot, real).split(path.sep).join(\"/\")])) {\n if (!(await fg(fg.escapePath(rel), { cwd: root, ignore, dot: true })).length) return null;\n }\n try {\n const content = await readBoundedFile(real, MAX_SOURCE_BYTES);\n return content === null ? null : { path: relative, content, totalLines: content.split(\"\\n\").length };\n } catch { return null; }\n }\n return { root, config, list, read };\n}\n","import 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 os from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson } 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(), 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(32), 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\n/** Called under the workspace lock. Keep a bounded history without storing tool input. */\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 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 // The lock has been acquired: an earlier unfinished receipt cannot still own it.\n for (const attempt of log.attempts) if (attempt.status === \"running\") attempt.status = \"unknown\";\n log.discardedAttempts += Math.max(0, log.attempts.length - 31);\n log.attempts = log.attempts.slice(-31);\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\",\n };\n log.attempts.push(attempt);\n await writeStoreJson(root, file, log);\n try {\n const result = await run();\n Object.assign(attempt, { status: \"completed\", finishedAt: new Date().toISOString(), durationMs: performance.now() - started,\n verificationStatus: result.report.status, reportPath: result.report.reportPath });\n await writeStoreJson(root, file, log);\n return result;\n } catch (error) {\n const failure = automationFailure(error);\n Object.assign(attempt, { status: \"failed\", finishedAt: new Date().toISOString(), durationMs: performance.now() - started, failure });\n delete attempt.verificationStatus;\n delete attempt.reportPath;\n try {\n await writeStoreJson(root, file, { ...log, attempts: log.attempts.map(a => a === attempt\n ? { ...a, failure: { ...failure, receiptRecorded: true } } : a) });\n failure.receiptRecorded = true;\n } catch { /* Storage exhaustion can also prevent recording its own failure. */ }\n throw Object.assign(new Error(failure.message, { cause: error }), { failure });\n }\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 let lock: { pid?: unknown; host?: unknown } | null = null;\n if (log.attempts.some(attempt => attempt.status === \"running\")) {\n try { lock = await readStoreJson(root, directory + \"/lock\") as { pid?: unknown; host?: unknown } | null; }\n catch { /* An absent/unreadable owner cannot establish an active execution. */ }\n }\n for (const attempt of log.attempts) {\n if (attempt.status !== \"running\") continue;\n let alive = false;\n if (attempt.host === os.hostname() && lock?.pid === attempt.pid && lock.host === attempt.host) {\n try { process.kill(attempt.pid, 0); alive = true; }\n catch (error) { alive = (error as NodeJS.ErrnoException).code === \"EPERM\"; }\n }\n if (!alive) attempt.status = \"unknown\";\n }\n return { status: log.attempts.at(-1)?.status ?? \"not-observed\", attempts: log.attempts, discardedAttempts: log.discardedAttempts };\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 path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess } from \"../utils/files.js\";\nexport { SOURCE_GLOB, SOURCE_IGNORE } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { z } from \"zod\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\nimport { buildTestMap } from \"../test-map.js\";\n\nconst exec = promisify(execFile);\n\nexport interface FeatureEntry {\n description: string;\n files: string[];\n tests?: string[];\n /**\n * Commit this entry was last verified against. Entries updated by an\n * incremental save carry HEAD here; untouched entries keep the hash the\n * map had before the save, so drift stays visible per entry. Absent means\n * \"as of the snapshot's top-level gitHash\".\n */\n refreshedHash?: string;\n /**\n * Whether this is a user-facing capability or internal infrastructure\n * (DI wiring, config loading, logging, provider/transport plumbing).\n * Capabilities are published to product-facing docs (Confluence);\n * infrastructure stays in the AI concept map only. Defaults to \"capability\"\n * when absent (older snapshots) — see normalizeFeatureType.\n */\n type?: \"capability\" | \"infrastructure\";\n /**\n * When an assistant last confirmed this entry's files actually implement\n * the claimed feature (verify_snapshot flow). Absent on older snapshots\n * and never-verified entries. Drift checks freshness against git; this\n * checks the map was CORRECT in the first place.\n */\n verifiedAt?: string;\n verifiedHash?: string;\n /** Set when verification judged the entry wrong — re-map it. */\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport type FeatureType = \"capability\" | \"infrastructure\";\n\n/**\n * Coerce an arbitrary type value to a known classification. Anything that\n * isn't explicitly \"infrastructure\" defaults to \"capability\" — so older\n * snapshots and unclassified entries are treated as user-facing (published),\n * never silently hidden.\n */\nexport function normalizeFeatureType(value: unknown): FeatureType {\n return value === \"infrastructure\" ? \"infrastructure\" : \"capability\";\n}\n\nexport interface FlowEntry {\n description: string;\n chain: string[];\n /** See FeatureEntry.refreshedHash. */\n refreshedHash?: string;\n /** See FeatureEntry.verifiedAt / verificationFailed. */\n verifiedAt?: string;\n verifiedHash?: string;\n verificationFailed?: boolean;\n verificationNote?: string;\n}\n\nexport interface Snapshot {\n version: 2;\n createdAt: string;\n updatedAt: string;\n gitHash: string;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nconst repoPath = z.string().refine(value => normalizeRepoPath(value) !== null, \"Expected a relative repository path\");\nconst verificationFields = {\n refreshedHash: z.string().optional(), verifiedAt: z.string().optional(),\n verifiedHash: z.string().optional(), verificationFailed: z.boolean().optional(),\n verificationNote: z.string().optional(),\n};\nexport const featureSchema = z.object({\n description: z.string(), files: z.array(repoPath), tests: z.array(repoPath).optional(),\n type: z.enum([\"capability\", \"infrastructure\"]).optional(), ...verificationFields,\n}).passthrough();\nexport const flowSchema = z.object({ description: z.string(), chain: z.array(repoPath), ...verificationFields }).passthrough();\nconst snapshotSchema = z.object({\n version: z.literal(2), createdAt: z.string(), updatedAt: z.string(), gitHash: z.string(),\n features: z.record(featureSchema), flows: z.record(flowSchema),\n}).passthrough();\n\nexport async function loadSnapshot(rootDir: string): Promise<Snapshot | null> {\n const parsed = await readStoreJson(rootDir, \".mason/snapshot.json\");\n if (parsed === null || (parsed as { version?: number }).version === 1) return null;\n const result = snapshotSchema.safeParse(parsed);\n if (!result.success) throw new Error(`Invalid Mason snapshot: ${result.error.message}`);\n return result.data;\n}\n\n/** Context and onboarding can use decisions even when the optional map is broken. */\nexport async function inspectSnapshot(rootDir: string): Promise<{\n status: \"available\" | \"missing\" | \"invalid\";\n snapshot: Snapshot | null;\n diagnostics: StoreDiagnostic[];\n}> {\n try {\n const raw = await readStoreJson(rootDir, \".mason/snapshot.json\");\n const snapshot = raw === null ? null : snapshotSchema.parse(raw);\n return { status: snapshot ? \"available\" : \"missing\", snapshot, diagnostics: [] };\n } catch (error) {\n return { status: \"invalid\", snapshot: null, diagnostics: [{\n path: \".mason/snapshot.json\", message: error instanceof Error ? error.message : String(error),\n }] };\n }\n}\n\nexport async function saveSnapshot(rootDir: string, snapshot: Snapshot): Promise<void> {\n await writeStoreJson(rootDir, \".mason/snapshot.json\", snapshotSchema.parse(snapshot));\n}\n\nexport async function getCurrentGitHash(rootDir: string): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"rev-parse\", \"HEAD\"], {\n cwd: rootDir,\n });\n return stdout.trim();\n } catch {\n return \"unknown\";\n }\n}\n\nexport const DEFAULT_BATCH_SIZE = 50;\nconst SKELETON_CHARS = 500;\nconst DEEP_SAMPLE_CHARS = 1500;\nconst DEEP_SAMPLES_PER_BATCH = 3;\n\nexport interface SnapshotBatch {\n offset: number;\n batchSize: number;\n nextOffset: number | null;\n totalFiles: number;\n skeletons: Array<{ path: string; content: string }>;\n samples: Array<{ path: string; content: string }>;\n testPairs: Array<{ test: string; source: string; confidence: string }>;\n}\n\nexport async function listSourceFiles(resolvedRoot: string): Promise<string[]> {\n return (await createFileAccess(resolvedRoot)).list();\n}\n\nexport async function prepareSnapshotBatch(\n rootDir: string,\n offset: number,\n batchSize: number = DEFAULT_BATCH_SIZE,\n scopeFiles?: string[]\n): Promise<SnapshotBatch> {\n const resolvedRoot = path.resolve(rootDir);\n const access = await createFileAccess(resolvedRoot);\n let allFiles = await access.list();\n if (scopeFiles) {\n // Intersect with the real source list: keeps ignore rules and path safety,\n // and silently drops scope entries that no longer exist on disk. An empty\n // scope stays empty — it must not fall back to walking the whole project.\n const scopeSet = new Set(scopeFiles);\n allFiles = allFiles.filter((f) => scopeSet.has(f));\n }\n const totalFiles = allFiles.length;\n const safeOffset = Math.max(0, Math.min(offset, totalFiles));\n const batchPaths = allFiles.slice(safeOffset, safeOffset + batchSize);\n\n const skeletons: Array<{ path: string; content: string }> = [];\n for (const filePath of batchPaths) {\n const full = await access.read(filePath);\n if (full) {\n skeletons.push({\n path: full.path,\n content: full.content.slice(0, SKELETON_CHARS),\n });\n }\n }\n\n // Pick a few files from this batch to read deeply for grounding. Spread\n // evenly across the batch so the deep samples represent the batch's range.\n const samples: Array<{ path: string; content: string }> = [];\n if (skeletons.length > 0) {\n const step = Math.max(1, Math.floor(skeletons.length / DEEP_SAMPLES_PER_BATCH));\n for (let i = 0; i < skeletons.length && samples.length < DEEP_SAMPLES_PER_BATCH; i += step) {\n const full = await access.read(skeletons[i].path);\n if (full) {\n samples.push({\n path: full.path,\n content: full.content.slice(0, DEEP_SAMPLE_CHARS),\n });\n }\n }\n }\n\n // Only include test pairs that involve files in this batch — keeps the\n // appendix relevant and small.\n const batchPathSet = new Set(batchPaths);\n const allTestPairs = (await buildTestMap(resolvedRoot)).paired;\n const testPairs = allTestPairs.filter(\n (p) => batchPathSet.has(p.test) || batchPathSet.has(p.source)\n );\n\n const nextOffset =\n safeOffset + batchSize >= totalFiles ? null : safeOffset + batchSize;\n\n return {\n offset: safeOffset,\n batchSize,\n nextOffset,\n totalFiles,\n skeletons,\n samples,\n testPairs,\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport {\n loadSnapshot,\n getCurrentGitHash,\n listSourceFiles,\n} from \"../snapshot/snapshot.js\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { Freshness } from \"../context/trust.js\";\nimport { matchingPaths } from \"../utils/paths.js\";\n\nconst exec = promisify(execFile);\n\n// Incremental refresh stops paying off once a large share of the map is\n// touched — but small absolute counts are always cheap to refresh in place,\n// so both thresholds must be exceeded before recommending a full rebuild.\nconst FULL_REBUILD_FRACTION = 0.4;\nconst FULL_REBUILD_MIN_CHANGED_MAPPED_FILES = 10;\n\nexport type ChangeStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\nexport interface FileChange {\n status: ChangeStatus;\n /** Current path (the new path for renames). */\n path: string;\n /** Pre-rename path, only present for renames. */\n previousPath?: string;\n}\n\nexport type DriftRecommendation = \"up-to-date\" | \"incremental\" | \"full-rebuild\";\n\nexport interface WorkingTreeReport {\n available: boolean;\n changedFiles: string[];\n untrackedFiles: string[];\n}\n\nexport interface DriftReport {\n /** Live entry state; committed drift alone continues to drive CLI exit codes. */\n featureFreshness?: Record<string, Freshness>;\n flowFreshness?: Record<string, Freshness>;\n workingTree?: WorkingTreeReport;\n verification?: { neverVerified: number; failed: string[] };\n stale: boolean;\n snapshotHash: string;\n headHash: string;\n /** Commits between the snapshot and HEAD; null when history is unavailable. */\n commitsBehind: number | null;\n /**\n * False when the snapshot commit is unreachable (shallow clone, rewritten\n * history) — staleFeatures/unmappedFiles/renames cannot be computed then.\n */\n historyAvailable: boolean;\n /** Current paths of every file changed since the snapshot. */\n changedFiles: string[];\n /** Stale feature name → the mapped files that changed under it. */\n staleFeatures: Record<string, string[]>;\n /** Stale flow name → the chain files that changed under it. */\n staleFlows: Record<string, string[]>;\n totalFeatures: number;\n totalFlows: number;\n /** New source files not referenced by any feature or flow. */\n unmappedFiles: string[];\n /** Files referenced by the map that no longer exist on disk. */\n ghostFiles: string[];\n renames: Array<{ from: string; to: string }>;\n recommendation: DriftRecommendation;\n}\n\nfunction parseChanges(output: string): FileChange[] {\n const fields = output.split(\"\\0\");\n const changes: FileChange[] = [];\n for (let i = 0; i < fields.length && fields[i];) {\n const code = fields[i++];\n const first = fields[i++];\n if (!first) break;\n const second = /^[RC]/.test(code) ? fields[i++] : undefined;\n const change: FileChange = second\n ? code.startsWith(\"R\") ? { status: \"renamed\", path: second, previousPath: first } : { status: \"added\", path: second }\n : { status: code === \"A\" ? \"added\" : code === \"D\" ? \"deleted\" : \"modified\", path: first };\n if (change.path.startsWith(\".mason/\") && (!change.previousPath || change.previousPath.startsWith(\".mason/\"))) continue;\n changes.push(change);\n }\n return changes;\n}\n\nexport function touchedPaths(changes: FileChange[]): string[] {\n return [...new Set(changes.flatMap(c => c.previousPath ? [c.previousPath, c.path] : [c.path]))].sort();\n}\n\nexport async function getChangesWithStatus(resolvedRoot: string, fromHash: string, toHash = \"HEAD\"): Promise<FileChange[] | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\") || !toHash || toHash === \"unknown\" || toHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", fromHash, toHash, \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 });\n return parseChanges(stdout);\n } catch { return null; }\n}\n\nexport async function getWorkingTree(resolvedRoot: string): Promise<WorkingTreeReport> {\n try {\n const [diff, untracked] = await Promise.all([\n exec(\"git\", [\"diff\", \"--name-status\", \"-z\", \"-M\", \"HEAD\", \"--\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n exec(\"git\", [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }),\n ]);\n const untrackedFiles = untracked.stdout.split(\"\\0\").filter(f => f && !f.startsWith(\".mason/\"));\n return { available: true, changedFiles: [...new Set([...touchedPaths(parseChanges(diff.stdout)), ...untrackedFiles])].sort(), untrackedFiles };\n } catch { return { available: false, changedFiles: [], untrackedFiles: [] }; }\n}\n\nasync function countCommitsBehind(\n resolvedRoot: string,\n fromHash: string\n): Promise<number | null> {\n if (!fromHash || fromHash === \"unknown\" || fromHash.startsWith(\"-\")) return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\"rev-list\", \"--count\", `${fromHash}..HEAD`],\n { cwd: resolvedRoot }\n );\n const count = Number.parseInt(stdout.trim(), 10);\n return Number.isNaN(count) ? null : count;\n } catch {\n return null;\n }\n}\n\nfunction collectMappedFiles(snapshot: Snapshot): Set<string> {\n const mappedFiles = new Set<string>();\n for (const feature of Object.values(snapshot.features)) {\n for (const f of feature.files) mappedFiles.add(f);\n for (const t of feature.tests ?? []) mappedFiles.add(t);\n }\n for (const flow of Object.values(snapshot.flows)) {\n for (const f of flow.chain) mappedFiles.add(f);\n }\n return mappedFiles;\n}\n\nasync function findGhostFiles(\n resolvedRoot: string,\n mappedFiles: Set<string>\n): Promise<string[]> {\n const ghosts: string[] = [];\n for (const file of mappedFiles) {\n try {\n await fs.access(path.join(resolvedRoot, file));\n } catch {\n ghosts.push(file);\n }\n }\n return ghosts.sort();\n}\n\n/**\n * Compare the concept map against HEAD and report feature-level drift.\n * Fully deterministic — git + filesystem only, no LLM involved.\n * Returns null when no snapshot exists.\n */\nexport async function computeDrift(rootDir: string): Promise<DriftReport | null> {\n const root = path.resolve(rootDir);\n const snapshot = await loadSnapshot(root);\n if (!snapshot) return null;\n const [headHash, workingTree] = await Promise.all([getCurrentGitHash(root), getWorkingTree(root)]);\n const hashFor = (entry: { refreshedHash?: string }) => entry.refreshedHash ?? snapshot.gitHash;\n const entries = [...Object.values(snapshot.features), ...Object.values(snapshot.flows)];\n const hashes = new Set([snapshot.gitHash, ...entries.map(hashFor)]);\n const changesByHash = new Map<string, FileChange[] | null>();\n await Promise.all([...hashes].map(async hash => {\n changesByHash.set(hash, hash === headHash && headHash !== \"unknown\" ? [] : await getChangesWithStatus(root, hash));\n }));\n const historyAvailable = headHash !== \"unknown\" && [...changesByHash.values()].every(changes => changes !== null);\n const mappedFiles = collectMappedFiles(snapshot);\n const report: DriftReport = {\n stale: !historyAvailable,\n snapshotHash: snapshot.gitHash, headHash,\n commitsBehind: 0, historyAvailable,\n changedFiles: [], staleFeatures: {}, staleFlows: {},\n totalFeatures: Object.keys(snapshot.features).length,\n totalFlows: Object.keys(snapshot.flows).length,\n unmappedFiles: [], ghostFiles: await findGhostFiles(root, mappedFiles), renames: [],\n recommendation: historyAvailable ? \"up-to-date\" : \"full-rebuild\",\n featureFreshness: {}, flowFreshness: {}, workingTree,\n verification: {\n neverVerified: entries.filter(e => !e.verifiedAt).length,\n failed: [...Object.entries(snapshot.features), ...Object.entries(snapshot.flows)].filter(([, e]) => e.verificationFailed).map(([name]) => name),\n },\n };\n const counts = await Promise.all([...hashes].map(hash => hash === headHash ? 0 : countCommitsBehind(root, hash)));\n const knownCounts = counts.filter((n): n is number => n !== null);\n report.commitsBehind = knownCounts.length ? Math.max(...knownCounts) : null;\n\n const check = (name: string, files: string[], hash: string, staleEntries: Record<string, string[]>, freshness: Record<string, Freshness>) => {\n const changes = changesByHash.get(hash);\n const committedHits = changes ? matchingPaths(files, touchedPaths(changes)) : [];\n if (committedHits.length) staleEntries[name] = committedHits;\n const localHits = matchingPaths(files, workingTree.changedFiles);\n freshness[name] = files.length === 0 || changes === null || changes === undefined || !workingTree.available ? \"unknown\"\n : committedHits.length || localHits.length || files.some(f => report.ghostFiles.includes(f)) ? \"changed\" : \"current\";\n };\n for (const [name, feature] of Object.entries(snapshot.features)) {\n check(name, [...feature.files, ...(feature.tests ?? [])], hashFor(feature), report.staleFeatures, report.featureFreshness!);\n }\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n check(name, flow.chain, hashFor(flow), report.staleFlows, report.flowFreshness!);\n }\n\n const allChanges = [...changesByHash.values()].flatMap(changes => changes ?? []);\n report.changedFiles = [...new Set(allChanges.map(c => c.path))].sort();\n // Complete coverage, including omissions from a map saved at HEAD. Untracked\n // files remain in workingTree and never change the committed-drift exit code.\n const sourceFiles = new Set(await listSourceFiles(root));\n let committedFiles: Set<string> = new Set();\n try {\n const { stdout } = await exec(\"git\", [\"ls-tree\", \"-r\", \"--name-only\", \"-z\", \"HEAD\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n committedFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch { report.historyAvailable = false; report.stale = true; }\n report.unmappedFiles = [...sourceFiles].filter(f => committedFiles.has(f) && !mappedFiles.has(f)).sort();\n const renames = new Map<string, { from: string; to: string }>();\n for (const change of allChanges) {\n if (change.status === \"renamed\" && change.previousPath) renames.set(`${change.previousPath}\\0${change.path}`, { from: change.previousPath, to: change.path });\n }\n report.renames = [...renames.values()];\n const changedMapped = new Set([...Object.values(report.staleFeatures).flat(), ...Object.values(report.staleFlows).flat()]);\n // A locally deleted file is a live-edit warning, not committed map drift.\n const committedGhosts = report.ghostFiles.filter(f => !workingTree.changedFiles.includes(f));\n report.stale ||= changedMapped.size > 0 || report.unmappedFiles.length > 0 || committedGhosts.length > 0;\n if (!report.historyAvailable) report.recommendation = \"full-rebuild\";\n else if (!report.stale) report.recommendation = \"up-to-date\";\n else report.recommendation = changedMapped.size >= FULL_REBUILD_MIN_CHANGED_MAPPED_FILES && changedMapped.size / Math.max(1, mappedFiles.size) > FULL_REBUILD_FRACTION ? \"full-rebuild\" : \"incremental\";\n return report;\n}\n","import type { PathClaim } from \"./types.js\";\n\n/**\n * A fenced block is treated as a directory tree only when it clearly is one —\n * below this many branch-glyph lines it's more likely an ASCII sketch.\n */\nconst MIN_GLYPH_LINES = 3;\n\nconst GLYPHS = [\"├──\", \"└──\"] as const;\n\nfunction glyphIndex(line: string): number {\n for (const glyph of GLYPHS) {\n const idx = line.indexOf(glyph);\n if (idx !== -1) return idx;\n }\n return -1;\n}\n\n/** Tree furniture: blank, or only vertical bars and whitespace. */\nfunction isSpacerLine(line: string): boolean {\n return /^[\\s│|]*$/.test(line);\n}\n\n/**\n * Strip an inline comment/annotation from a tree entry. Entries commonly\n * carry `# comment` or column-aligned notes after two or more spaces.\n */\nfunction entryName(afterGlyph: string): string | null {\n let name = afterGlyph.replace(/^\\s+/, \"\");\n const hash = name.search(/\\s+#/);\n if (hash !== -1) name = name.slice(0, hash);\n const columns = name.search(/\\s{2,}/);\n if (columns !== -1) name = name.slice(0, columns);\n name = name.trim();\n // A name with remaining internal whitespace is not a path — treat the\n // line as malformed rather than guessing.\n if (!name || /\\s/.test(name)) return null;\n return name;\n}\n\n/**\n * Reconstruct full paths from an ASCII directory tree inside a fenced block.\n *\n * The failure mode must always be a missed claim, never an invented path: a\n * line that doesn't parse cleanly aborts reconstruction below it, and every\n * emitted path still passes the deleted-reference provability gate later.\n *\n * `blockLines` are the fence's content lines; `blockStartLine` is the 1-based\n * doc line number of the first content line.\n */\nexport function extractTreeClaims(\n blockLines: string[],\n blockStartLine: number\n): PathClaim[] {\n const glyphLines = blockLines.filter((l) => glyphIndex(l) !== -1).length;\n if (glyphLines < MIN_GLYPH_LINES) return [];\n\n const claims: PathClaim[] = [];\n // Directories on the path from the root to the current entry, keyed by the\n // column their branch glyph appeared at.\n const stack: Array<{ col: number; name: string }> = [];\n let rootPrefix = \"\";\n let started = false;\n\n for (let i = 0; i < blockLines.length; i++) {\n const line = blockLines[i];\n const col = glyphIndex(line);\n\n if (col === -1) {\n if (isSpacerLine(line)) continue;\n if (!started) {\n // A bare `src/` line above the first glyph names the tree's root.\n const candidate = line.trim();\n if (candidate.endsWith(\"/\") && !/\\s/.test(candidate)) {\n rootPrefix = candidate.replace(/\\/+$/, \"\");\n claims.push({\n path: rootPrefix,\n line: blockStartLine + i,\n excerpt: candidate,\n });\n }\n continue;\n }\n // Unparseable line after the tree began: stop here, keep what we have.\n return claims;\n }\n\n started = true;\n const name = entryName(line.slice(col + GLYPHS[0].length));\n if (name === null) return claims;\n\n while (stack.length > 0 && stack[stack.length - 1].col >= col) {\n stack.pop();\n }\n\n const isDir = name.endsWith(\"/\");\n const cleanName = name.replace(/\\/+$/, \"\");\n const segments = [\n ...(rootPrefix ? [rootPrefix] : []),\n ...stack.map((s) => s.name),\n cleanName,\n ];\n claims.push({\n path: segments.join(\"/\"),\n line: blockStartLine + i,\n excerpt: name,\n });\n\n if (isDir) stack.push({ col, name: cleanName });\n }\n\n return claims;\n}\n","import type {\n CommandClaim,\n CountClaim,\n DocClaims,\n PathClaim,\n} from \"./types.js\";\nimport { extractTreeClaims } from \"./tree.js\";\n\n/**\n * Single-segment names that count as path claims without containing a \"/\".\n * Anything else without a slash is prose (\"name your file `config.ts`\"), not\n * a claim about this repo.\n */\nconst ROOT_FILE_NAMES = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-workspace.yaml\",\n \"tsconfig.json\",\n \"tsup.config.ts\",\n \"vitest.config.ts\",\n \"Makefile\",\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"go.sum\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"manifest.json\",\n \"server.json\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\",\n \"CLAUDE.md\",\n \"AGENTS.md\",\n \".gitignore\",\n \".env.example\",\n]);\n\nconst SHELL_FENCE_INFOS = new Set([\"\", \"bash\", \"sh\", \"shell\", \"console\", \"zsh\"]);\n\nconst COMMAND_RE = /\\b(npm|pnpm|yarn)\\s+run\\s+([A-Za-z0-9:_.-]+)/g;\nconst COUNT_RE = /(\\d+)\\s+(modules?|packages?|workspaces?|crates?)\\b/gi;\n/** \"3 package managers\" is not a package count. */\nconst COUNT_DENYLIST_RE = /^\\s*(manager|registr|lock|json)/i;\n\nconst IGNORE_LINE = \"<!-- mason:ignore -->\";\nconst IGNORE_START = \"<!-- mason:ignore-start -->\";\nconst IGNORE_END = \"<!-- mason:ignore-end -->\";\n\n/**\n * Normalize a candidate token into a repo-relative path claim, or return\n * null when the token is not a claim about this repo (URL, glob,\n * placeholder, relative import example, bare word).\n */\nexport function normalizePathToken(token: string): string | null {\n let t = token.trim();\n if (!t) return null;\n if (/\\s/.test(t)) return null;\n if (t.includes(\"://\") || t.includes(\"\\\\\")) return null;\n if (/[*?[\\]{}<>$`]/.test(t)) return null;\n if (t.startsWith(\"/\") || t.startsWith(\"~\") || t.startsWith(\"./\") || t.startsWith(\"../\")) {\n return null;\n }\n // `src/mcp/tools.ts:189` claims the file, not the line.\n t = t.replace(/:\\d+(?:-\\d+)?$/, \"\");\n if (t.includes(\":\")) return null;\n const normalized = t.replace(/\\/+$/, \"\");\n if (!normalized) return null;\n // `server/src/test/kotlin/...` — a dots-only segment is an \"and so on\"\n // placeholder, not a claim.\n if (normalized.split(\"/\").some((seg) => /^\\.+$/.test(seg))) return null;\n if (normalized.includes(\"/\")) return normalized;\n return ROOT_FILE_NAMES.has(normalized) ? normalized : null;\n}\n\n/** A fence line that is exactly one path-shaped token is a file-list claim. */\nfunction exactTokenPath(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed || /\\s/.test(trimmed) || !trimmed.includes(\"/\")) return null;\n return normalizePathToken(trimmed);\n}\n\nfunction computeIgnoredLines(lines: string[]): boolean[] {\n const ignored = new Array<boolean>(lines.length).fill(false);\n let inRegion = false;\n let ignoreNext = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.includes(IGNORE_START)) {\n inRegion = true;\n ignored[i] = true;\n continue;\n }\n if (line.includes(IGNORE_END)) {\n inRegion = false;\n ignored[i] = true;\n continue;\n }\n if (inRegion) {\n ignored[i] = true;\n continue;\n }\n if (ignoreNext) {\n if (line.trim().length === 0) continue; // skip blanks to the next real line\n ignored[i] = true;\n ignoreNext = false;\n continue;\n }\n if (line.includes(IGNORE_LINE)) {\n ignored[i] = true;\n const rest = line.replace(IGNORE_LINE, \"\").trim();\n if (rest.length === 0) ignoreNext = true;\n }\n }\n return ignored;\n}\n\n/**\n * Extract every checkable claim from a context-file's markdown. Deterministic\n * and purely lexical — precision comes from the checks' provability gates,\n * not from clever parsing here.\n */\nexport function extractClaims(content: string): DocClaims {\n const lines = content.split(\"\\n\");\n const ignored = computeIgnoredLines(lines);\n\n const paths = new Map<string, PathClaim>();\n const counts: CountClaim[] = [];\n const commands = new Map<string, CommandClaim>();\n\n const addPath = (claim: PathClaim): void => {\n if (!paths.has(claim.path)) paths.set(claim.path, claim);\n };\n const addCommand = (claim: CommandClaim): void => {\n if (!commands.has(claim.scriptName)) commands.set(claim.scriptName, claim);\n };\n\n let inFence = false;\n let fenceInfo = \"\";\n let fenceMarker = \"\";\n let blockLines: string[] = [];\n let blockStartLine = 0;\n\n const processBlock = (): void => {\n for (const claim of extractTreeClaims(blockLines, blockStartLine)) {\n addPath(claim);\n }\n for (let i = 0; i < blockLines.length; i++) {\n const exact = exactTokenPath(blockLines[i]);\n if (exact) {\n addPath({\n path: exact,\n line: blockStartLine + i,\n excerpt: blockLines[i].trim(),\n });\n }\n }\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNo = i + 1;\n const fenceMatch = line.match(/^\\s*(```+|~~~+)(.*)$/);\n\n if (fenceMatch) {\n if (!inFence) {\n inFence = true;\n fenceMarker = fenceMatch[1][0];\n fenceInfo = fenceMatch[2].trim().toLowerCase();\n blockLines = [];\n blockStartLine = lineNo + 1;\n } else if (fenceMatch[1][0] === fenceMarker) {\n inFence = false;\n processBlock();\n }\n continue;\n }\n\n if (inFence) {\n // Ignored lines become spacers so the rest of a tree still parses.\n blockLines.push(ignored[i] ? \"\" : line);\n if (!ignored[i] && SHELL_FENCE_INFOS.has(fenceInfo)) {\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n continue;\n }\n\n if (ignored[i]) continue;\n\n for (const m of line.matchAll(/`([^`]+)`/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(/\"([A-Za-z][\\w.@-]*(?:\\/[\\w.@-]+)+\\/?)\"/g)) {\n const normalized = normalizePathToken(m[1]);\n if (normalized) {\n addPath({ path: normalized, line: lineNo, excerpt: m[1] });\n }\n }\n for (const m of line.matchAll(COUNT_RE)) {\n const rest = line.slice((m.index ?? 0) + m[0].length);\n if (COUNT_DENYLIST_RE.test(rest)) continue;\n counts.push({\n count: Number.parseInt(m[1], 10),\n unit: m[2].toLowerCase(),\n line: lineNo,\n excerpt: m[0],\n });\n }\n for (const m of line.matchAll(COMMAND_RE)) {\n addCommand({\n scriptName: m[2],\n invocation: m[0],\n line: lineNo,\n excerpt: m[0],\n });\n }\n }\n\n // An unclosed fence still gets its block processed — trees at the end of a\n // truncated doc are claims too.\n if (inFence) processBlock();\n\n return {\n paths: [...paths.values()],\n counts,\n commands: [...commands.values()],\n };\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CommitRef } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\nconst COMMIT_FORMAT = \"%H%x09%cI%x09%s\";\n\nfunction parseCommitLine(line: string): CommitRef | null {\n const parts = line.split(\"\\t\");\n if (parts.length < 3 || !parts[0]) return null;\n return { hash: parts[0], date: parts[1], subject: parts.slice(2).join(\"\\t\") };\n}\n\n/** Most recent commit touching a path, or null if the path was never tracked. */\nexport async function lastCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"-1\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** The commit that deleted a path, or null if none did. */\nexport async function deletingCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n \"-1\",\n \"--diff-filter=D\",\n `--format=${COMMIT_FORMAT}`,\n \"--\",\n relPath,\n ],\n { cwd: resolvedRoot }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\n/** Oldest commit touching a path (used to date a directory's appearance). */\nexport async function firstCommitOf(\n resolvedRoot: string,\n relPath: string\n): Promise<CommitRef | null> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--reverse\", `--format=${COMMIT_FORMAT}`, \"--\", relPath],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n const line = stdout.trim().split(\"\\n\")[0];\n return line ? parseCommitLine(line) : null;\n } catch {\n return null;\n }\n}\n\nexport interface RangeCommits {\n commits: Array<CommitRef & { files: string[] }>;\n total: number;\n}\n\n/**\n * Commits in fromHash..HEAD touching any of the pathspecs, newest first, with\n * the touched files per commit. Rev-range, not --since: immune to rebase date\n * skew and CI checkout mtimes. Returns null when the range is uncomputable\n * (unreachable base commit, shallow clone, no git).\n */\nexport async function commitsTouchingSince(\n resolvedRoot: string,\n fromHash: string,\n pathspecs: string[]\n): Promise<RangeCommits | null> {\n if (!fromHash || fromHash === \"unknown\") return null;\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `${fromHash}..HEAD`,\n `--format=%x01${COMMIT_FORMAT}`,\n \"--name-only\",\n \"--\",\n ...pathspecs,\n ],\n { cwd: resolvedRoot, maxBuffer: 10 * 1024 * 1024 }\n );\n\n const commits: Array<CommitRef & { files: string[] }> = [];\n // \\x01 marks each commit header so name-only file lists can't be\n // mistaken for headers.\n for (const block of stdout.split(\"\\x01\")) {\n if (!block.trim()) continue;\n const lines = block.split(\"\\n\").filter((l) => l.trim().length > 0);\n const ref = parseCommitLine(lines[0]);\n if (!ref) continue;\n commits.push({ ...ref, files: lines.slice(1).map((l) => l.trim()) });\n }\n return { commits, total: commits.length };\n } catch {\n return null;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { extractClaims } from \"./claims.js\";\nimport { lastCommitOf } from \"./git.js\";\nimport type { CommitRef, DocClaims } from \"./types.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * All context files audited in v1, in the precedence order the setup\n * playbook uses. Every candidate that exists is audited — a repo can\n * legitimately carry both AGENTS.md and CLAUDE.md, and drift can live in\n * either.\n */\nexport const DOC_CANDIDATES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \".claude/CLAUDE.md\",\n] as const;\n\nexport interface AuditDoc {\n /** Repo-relative posix path. */\n path: string;\n content: string;\n lineCount: number;\n /** Null when the doc is untracked. */\n lastCommit: CommitRef | null;\n /** Uncommitted edits present. */\n dirty: boolean;\n claims: DocClaims;\n}\n\nasync function isDirty(resolvedRoot: string, relPath: string): Promise<boolean> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"status\", \"--porcelain\", \"--\", relPath],\n { cwd: resolvedRoot }\n );\n return stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport async function discoverDocs(resolvedRoot: string): Promise<AuditDoc[]> {\n const docs = await Promise.all(DOC_CANDIDATES.map(async (candidate): Promise<AuditDoc | null> => {\n let content: string;\n try {\n content = await fs.readFile(path.join(resolvedRoot, candidate), \"utf-8\");\n } catch {\n return null;\n }\n const [lastCommit, dirty] = await Promise.all([lastCommitOf(resolvedRoot, candidate), isDirty(resolvedRoot, candidate)]);\n return {\n path: candidate,\n content,\n lineCount: content.split(\"\\n\").length,\n lastCommit,\n dirty,\n claims: extractClaims(content),\n };\n }));\n return docs.filter((doc): doc is AuditDoc => doc !== null);\n}\n","import type { decisionProvenance } from \"../decisions/provenance.js\";\n\nexport type IssueType =\n | \"deleted-reference\"\n | \"new-module\"\n | \"stale-count\"\n | \"dead-command\";\n\nexport type AdvisoryType = \"deps-changed\" | \"decision-anchor-drift\";\n\nexport type CheckName = IssueType | AdvisoryType;\n\nexport const ALL_CHECKS: CheckName[] = [\n \"deleted-reference\",\n \"new-module\",\n \"stale-count\",\n \"dead-command\",\n \"deps-changed\",\n \"decision-anchor-drift\",\n];\n\n/**\n * \"certain\" — the claim is provably false (a tracked path is gone, a computed\n * count differs, a script exists in no manifest). \"likely\" — evidence-backed\n * but heuristic (an unmentioned directory; a never-tracked path whose parent\n * exists). Certain-class issues are safe to auto-fix; likely-class issues\n * deserve a look.\n */\nexport type Confidence = \"certain\" | \"likely\";\n\nexport interface CommitRef {\n hash: string;\n date: string;\n subject: string;\n}\n\nexport interface DocAnchor {\n /** Repo-relative doc path, e.g. \"CLAUDE.md\" or \".claude/CLAUDE.md\". */\n doc: string;\n /** 1-based line of the claim; null for doc-level issues (new-module). */\n line: number | null;\n /** The claim exactly as written, e.g. \"src/utils/logger.ts\". */\n excerpt: string | null;\n}\n\nexport type Evidence =\n | {\n kind: \"missing-path\";\n claimed: string;\n renamedTo: string | null;\n deletedInCommit: CommitRef | null;\n everTracked: boolean;\n parentDirExists: boolean;\n }\n | {\n kind: \"unmentioned-dir\";\n dir: string;\n sourceFileCount: number;\n firstCommit: CommitRef | null;\n checkedDocs: string[];\n }\n | {\n kind: \"count-mismatch\";\n claimed: number;\n actual: number;\n unit: string;\n /** Where the actual count came from, e.g. \"package.json workspaces\". */\n countedFrom: string;\n members: string[];\n }\n | {\n kind: \"missing-script\";\n scriptName: string;\n invocation: string;\n manifestsChecked: string[];\n availableScripts: string[];\n }\n | {\n kind: \"doc-behind-manifests\";\n docLastCommit: CommitRef;\n manifestCommits: Array<CommitRef & { files: string[] }>;\n totalCommits: number;\n }\n | {\n kind: \"decision-anchor\";\n provenance?: ReturnType<typeof decisionProvenance>;\n decisionId: string;\n title: string;\n changedFiles: string[];\n refreshedHash: string;\n };\n\nexport interface AuditIssue {\n type: IssueType;\n message: string;\n anchor: DocAnchor;\n confidence: Confidence;\n evidence: Evidence;\n}\n\n/**\n * Advisories are facts the fixing agent cannot close by editing the doc (a\n * manifest commit after the doc's commit stays true forever; decision records\n * must be re-verified by humans). They NEVER affect the exit code — same\n * precedent as decision staleness in mason-drift.\n */\nexport interface AuditAdvisory {\n type: AdvisoryType;\n message: string;\n anchor: DocAnchor;\n evidence: Evidence;\n}\n\nexport interface AuditDocInfo {\n path: string;\n lastCommit: CommitRef | null;\n /** Uncommitted edits present — deps-changed is suppressed for dirty docs. */\n dirty: boolean;\n lineCount: number;\n}\n\nexport interface AuditReport {\n /** Additive-only schema — this output is a CI contract. */\n version: 1;\n root: string;\n gitAvailable: boolean;\n /** Commit and exact check scope used by this run. */\n headHash?: string;\n checksRun?: CheckName[];\n docs: AuditDocInfo[];\n /** Whether .mason/decisions/ existed and was checked. */\n decisionsChecked: boolean;\n /** Drive exit code 1. */\n issues: AuditIssue[];\n /** Never drive the exit code. */\n advisories: AuditAdvisory[];\n /** Original committed evidence retained while local doc edits suppress reporting. */\n suppressedAdvisories?: AuditAdvisory[];\n skippedChecks: Array<{ check: string; reason: string; doc?: string }>;\n clean: boolean;\n}\n\nexport interface PathClaim {\n path: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CountClaim {\n count: number;\n unit: string;\n line: number;\n excerpt: string;\n}\n\nexport interface CommandClaim {\n scriptName: string;\n invocation: string;\n line: number;\n excerpt: string;\n}\n\nexport interface DocClaims {\n paths: PathClaim[];\n counts: CountClaim[];\n commands: CommandClaim[];\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { deletingCommitOf, lastCommitOf } from \"../git.js\";\nimport type { AuditIssue } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nasync function exists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A claimed path that is missing on disk is only flagged when the repo can\n * prove it was ever real: a rename since the doc's last commit, or git\n * history for the path, or at least an existing parent directory. Paths with\n * none of those are illustrative examples and are dropped silently.\n */\nexport async function checkDeletedReferences(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n const changes = ctx.changesSinceDoc.get(doc.path);\n const renames = new Map<string, string>();\n for (const change of changes ?? []) {\n if (change.status === \"renamed\" && change.previousPath) {\n renames.set(change.previousPath, change.path);\n }\n }\n\n for (const claim of doc.claims.paths) {\n // Mason's own metadata is optional state, not repo structure — docs\n // legitimately describe .mason/ files that a given repo doesn't have.\n if (claim.path === \".mason\" || claim.path.startsWith(\".mason/\")) {\n continue;\n }\n if (await exists(path.join(ctx.root, claim.path))) continue;\n\n const anchor = { doc: doc.path, line: claim.line, excerpt: claim.excerpt };\n const renamedTo = renames.get(claim.path) ?? null;\n\n if (renamedTo) {\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` was renamed to \\`${renamedTo}\\``,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo,\n deletedInCommit: null,\n everTracked: true,\n parentDirExists: true,\n },\n });\n continue;\n }\n\n const tracked = await lastCommitOf(ctx.root, claim.path);\n if (tracked) {\n const deleted = await deletingCommitOf(ctx.root, claim.path);\n const detail = deleted\n ? ` – deleted in ${deleted.hash.slice(0, 7)} \"${deleted.subject}\" (${deleted.date.slice(0, 10)})`\n : \"\";\n result.issues.push({\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` no longer exists${detail}`,\n anchor,\n confidence: \"certain\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: deleted,\n everTracked: true,\n parentDirExists: await exists(\n path.join(ctx.root, path.dirname(claim.path))\n ),\n },\n });\n continue;\n }\n\n const parentDirExists = await exists(\n path.join(ctx.root, path.dirname(claim.path))\n );\n if (!parentDirExists) continue;\n\n const issue: AuditIssue = {\n type: \"deleted-reference\",\n message: `\\`${claim.path}\\` does not exist (never tracked in git – possible typo or invented path)`,\n anchor,\n confidence: \"likely\",\n evidence: {\n kind: \"missing-path\",\n claimed: claim.path,\n renamedTo: null,\n deletedInCommit: null,\n everTracked: false,\n parentDirExists: true,\n },\n };\n result.issues.push(issue);\n }\n }\n\n return result;\n}\n","import fg from \"fast-glob\";\nimport path from \"node:path\";\nimport { SOURCE_GLOB, SOURCE_IGNORE } from \"../../snapshot/snapshot.js\";\nimport { firstCommitOf } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\n/** Directories that are never \"modules\" worth documenting. */\nconst DIR_DENYLIST = new Set([\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \"coverage\",\n \"target\",\n \"vendor\",\n \"__pycache__\",\n \"venv\",\n \".venv\",\n \".git\",\n \".gradle\",\n \".mason\",\n \".claude\",\n \".github\",\n \".vscode\",\n \".idea\",\n]);\n\n/** Second-level dirs need a bit more substance before they count. */\nconst SECOND_LEVEL_MIN_SOURCE_FILES = 2;\n/**\n * Descend into a top-level dir only when the docs evidently enumerate its\n * children — at least this many of its subdirs already mentioned.\n */\nconst ENUMERATION_THRESHOLD = 2;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Word-boundary mention check across the union of all docs — `app` must not\n * match \"application\", and a dir mentioned only in AGENTS.md must not be\n * flagged against CLAUDE.md.\n */\nfunction isMentioned(combinedDocs: string, name: string): boolean {\n const re = new RegExp(\n `(^|[^A-Za-z0-9_-])${escapeRegExp(name)}(/|[^A-Za-z0-9_-]|$)`,\n \"im\"\n );\n return re.test(combinedDocs);\n}\n\nasync function listSubdirs(absDir: string): Promise<string[]> {\n const dirs = await fg(\"*\", {\n cwd: absDir,\n onlyDirectories: true,\n suppressErrors: true,\n });\n return dirs.filter((d) => !DIR_DENYLIST.has(d)).sort();\n}\n\nasync function countSourceFiles(absDir: string): Promise<number> {\n const files = await fg(SOURCE_GLOB, {\n cwd: absDir,\n ignore: SOURCE_IGNORE,\n suppressErrors: true,\n });\n return files.length;\n}\n\nexport async function checkNewModules(ctx: CheckContext): Promise<CheckResult> {\n const result = emptyResult();\n if (ctx.docs.length === 0) return result;\n\n const combinedDocs = ctx.docs.map((d) => d.content).join(\"\\n\");\n const primaryDoc = ctx.docs[0].path;\n const checkedDocs = ctx.docs.map((d) => d.path);\n\n const flag = async (dir: string, sourceFileCount: number): Promise<void> => {\n result.issues.push({\n type: \"new-module\",\n message: `directory \\`${dir}/\\` contains ${sourceFileCount} source file${sourceFileCount === 1 ? \"\" : \"s\"} but is not mentioned in any context file`,\n anchor: { doc: primaryDoc, line: null, excerpt: dir },\n confidence: \"likely\",\n evidence: {\n kind: \"unmentioned-dir\",\n dir,\n sourceFileCount,\n firstCommit: await firstCommitOf(ctx.root, dir),\n checkedDocs,\n },\n });\n };\n\n for (const candidate of await moduleCandidates(ctx.root, combinedDocs)) {\n await flag(candidate.dir, candidate.sourceFileCount);\n }\n\n return result;\n}\n\n/** Shared dependency witness: cache exactly the module candidates the audit observes. */\nexport async function moduleCandidates(root: string, combinedDocs: string) {\n const candidates: Array<{ dir: string; sourceFileCount: number }> = [];\n for (const topDir of await listSubdirs(root)) {\n const absTop = path.join(root, topDir);\n const topMentioned = isMentioned(combinedDocs, topDir);\n\n if (!topMentioned) {\n const count = await countSourceFiles(absTop);\n if (count >= 1) candidates.push({ dir: topDir, sourceFileCount: count });\n continue;\n }\n\n // The docs know this dir. If they enumerate its children (several\n // subdirs already mentioned), an unmentioned sibling is drift — this is\n // how a freshly added module under src/ gets caught.\n const subdirs = await listSubdirs(absTop);\n const mentioned = subdirs.filter((s) => isMentioned(combinedDocs, s));\n if (mentioned.length < ENUMERATION_THRESHOLD) continue;\n\n for (const sub of subdirs) {\n if (isMentioned(combinedDocs, sub)) continue;\n const count = await countSourceFiles(path.join(absTop, sub));\n if (count >= SECOND_LEVEL_MIN_SOURCE_FILES) {\n candidates.push({ dir: `${topDir}/${sub}`, sourceFileCount: count });\n }\n }\n }\n\n return candidates;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CountClaim } from \"../types.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MEMBERS_CAP = 50;\n\ninterface CountSource {\n actual: number;\n countedFrom: string;\n members: string[];\n}\n\nasync function readIfExists(absPath: string): Promise<string | null> {\n try {\n return await fs.readFile(absPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nasync function countGradleModules(root: string): Promise<CountSource | null> {\n for (const name of [\"settings.gradle.kts\", \"settings.gradle\"]) {\n const content = await readIfExists(path.join(root, name));\n if (content === null) continue;\n // include(\":a\", \":b\") — count quoted project strings, not include() calls.\n const members: string[] = [];\n for (const call of content.matchAll(/include\\s*\\(([^)]*)\\)/g)) {\n for (const proj of call[1].matchAll(/[\"']([^\"']+)[\"']/g)) {\n members.push(proj[1]);\n }\n }\n if (members.length === 0) return null;\n return { actual: members.length, countedFrom: name, members };\n }\n return null;\n}\n\nasync function countNpmWorkspaces(root: string): Promise<CountSource | null> {\n const pkgRaw = await readIfExists(path.join(root, \"package.json\"));\n if (pkgRaw !== null) {\n try {\n const pkg = JSON.parse(pkgRaw);\n const globs: string[] = Array.isArray(pkg.workspaces)\n ? pkg.workspaces\n : Array.isArray(pkg.workspaces?.packages)\n ? pkg.workspaces.packages\n : [];\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"package.json workspaces\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n } catch {\n // Malformed package.json — nothing provable here.\n }\n }\n\n const pnpmRaw = await readIfExists(path.join(root, \"pnpm-workspace.yaml\"));\n if (pnpmRaw !== null) {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of pnpmRaw.split(\"\\n\")) {\n if (/^packages\\s*:/.test(line)) {\n inPackages = true;\n continue;\n }\n if (inPackages) {\n const entry = line.match(/^\\s*-\\s*[\"']?([^\"'#\\s]+)/);\n if (entry) {\n if (!entry[1].startsWith(\"!\")) globs.push(entry[1]);\n } else if (line.trim().length > 0 && !line.startsWith(\" \")) {\n inPackages = false;\n }\n }\n }\n if (globs.length > 0) {\n const matched = await fg(\n globs.map((g) => `${g.replace(/\\/+$/, \"\")}/package.json`),\n { cwd: root, ignore: [\"**/node_modules/**\"] }\n );\n return {\n actual: matched.length,\n countedFrom: \"pnpm-workspace.yaml\",\n members: matched.map((m) => path.dirname(m)).sort(),\n };\n }\n }\n return null;\n}\n\nasync function countCargoCrates(root: string): Promise<CountSource | null> {\n const content = await readIfExists(path.join(root, \"Cargo.toml\"));\n if (content === null) return null;\n const membersBlock = content.match(/members\\s*=\\s*\\[([\\s\\S]*?)\\]/);\n if (!membersBlock) return null;\n const entries = [...membersBlock[1].matchAll(/[\"']([^\"']+)[\"']/g)].map(\n (m) => m[1]\n );\n if (entries.length === 0) return null;\n\n // Workspace members may be globs (\"crates/*\") — resolve them against\n // directories that actually contain a Cargo.toml.\n const members = new Set<string>();\n for (const entry of entries) {\n if (/[*?[\\]{}]/.test(entry)) {\n const matched = await fg(`${entry.replace(/\\/+$/, \"\")}/Cargo.toml`, {\n cwd: root,\n ignore: [\"**/target/**\"],\n });\n for (const m of matched) members.add(path.dirname(m));\n } else if (\n (await readIfExists(path.join(root, entry, \"Cargo.toml\"))) !== null\n ) {\n members.add(entry);\n }\n }\n if (members.size === 0) return null;\n return {\n actual: members.size,\n countedFrom: \"Cargo.toml workspace members\",\n members: [...members].sort(),\n };\n}\n\n/**\n * Map a claim's unit to the ecosystem that can prove it. When the mapped\n * ecosystem has no workspace manifest in this repo, the claim is skipped —\n * \"12 packages\" in a Gradle repo proves nothing either way.\n */\nexport async function resolveCountSource(\n root: string,\n claim: CountClaim\n): Promise<CountSource | null> {\n const unit = claim.unit.replace(/s$/, \"\");\n if (unit === \"module\") return countGradleModules(root);\n if (unit === \"workspace\") return countNpmWorkspaces(root);\n if (unit === \"crate\") return countCargoCrates(root);\n // \"packages\" is ecosystem-ambiguous — first manifest that resolves wins.\n return (\n (await countNpmWorkspaces(root)) ??\n (await countCargoCrates(root)) ??\n (await countGradleModules(root))\n );\n}\n\nexport async function checkStaleCounts(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n for (const doc of ctx.docs) {\n for (const claim of doc.claims.counts) {\n const source = await resolveCountSource(ctx.root, claim);\n if (source === null) {\n result.skipped.push({ check: \"stale-count\", doc: doc.path,\n reason: `${doc.path}: cannot resolve a workspace manifest for \"${claim.excerpt}\"` });\n continue;\n }\n if (source.actual === claim.count) continue;\n result.issues.push({\n type: \"stale-count\",\n message: `says \"${claim.excerpt}\" but ${source.countedFrom} resolves to ${source.actual}`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"count-mismatch\",\n claimed: claim.count,\n actual: source.actual,\n unit: claim.unit,\n countedFrom: source.countedFrom,\n members: source.members.slice(0, MEMBERS_CAP),\n },\n });\n }\n }\n\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst AVAILABLE_SCRIPTS_CAP = 30;\n\nasync function scriptsOf(absManifest: string): Promise<string[] | null> {\n try {\n const pkg = JSON.parse(await fs.readFile(absManifest, \"utf-8\"));\n return pkg && typeof pkg.scripts === \"object\" && pkg.scripts !== null\n ? Object.keys(pkg.scripts)\n : [];\n } catch {\n return null;\n }\n}\n\n/**\n * `npm run <script>` claims checked against package.json scripts — the one\n * ecosystem where task discovery is a single JSON parse. A script missing\n * from the root manifest is searched in every workspace manifest before\n * being flagged; docs legitimately say \"in packages/foo run `npm run build`\".\n */\nexport async function checkDeadCommands(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n\n const commandClaims = ctx.docs.flatMap((doc) =>\n doc.claims.commands.map((claim) => ({ doc, claim }))\n );\n if (commandClaims.length === 0) return result;\n\n const rootScripts = await scriptsOf(path.join(ctx.root, \"package.json\"));\n if (rootScripts === null) {\n result.skipped.push({\n check: \"dead-command\",\n reason: \"no package.json at the repo root\",\n });\n return result;\n }\n const rootSet = new Set(rootScripts);\n\n let workspaceScripts: Set<string> | null = null;\n let manifestsChecked: string[] = [\"package.json\"];\n const loadWorkspaceScripts = async (): Promise<Set<string>> => {\n if (workspaceScripts !== null) return workspaceScripts;\n workspaceScripts = new Set<string>();\n const manifests = await commandManifests(ctx.root);\n manifestsChecked = [\"package.json\", ...manifests.sort()];\n for (const manifest of manifests) {\n const scripts = await scriptsOf(path.join(ctx.root, manifest));\n for (const name of scripts ?? []) workspaceScripts.add(name);\n }\n return workspaceScripts;\n };\n\n for (const { doc, claim } of commandClaims) {\n if (rootSet.has(claim.scriptName)) continue;\n const elsewhere = await loadWorkspaceScripts();\n if (elsewhere.has(claim.scriptName)) continue;\n\n result.issues.push({\n type: \"dead-command\",\n message: `\\`${claim.invocation}\\` refers to script \"${claim.scriptName}\", which exists in no package.json`,\n anchor: { doc: doc.path, line: claim.line, excerpt: claim.excerpt },\n confidence: \"certain\",\n evidence: {\n kind: \"missing-script\",\n scriptName: claim.scriptName,\n invocation: claim.invocation,\n manifestsChecked,\n availableScripts: rootScripts.slice(0, AVAILABLE_SCRIPTS_CAP),\n },\n });\n }\n\n return result;\n}\n\n/** Shared with automation so ignored workspace manifests remain cache dependencies. */\nexport function commandManifests(root: string): Promise<string[]> {\n return fg(\"**/package.json\", { cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \".mason/reports/**\", \"package.json\"] });\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { RangeCommits } from \"./git.js\";\n\nconst exec = promisify(execFile);\nasync function git(root: string, args: string[]) {\n return (await exec(\"git\", args, { cwd: root, timeout: 10000, maxBuffer: 2 * 1024 * 1024 })).stdout;\n}\n\n/** A deliberately narrow recognizer, not a Gradle evaluator. Unknown syntax stays advisory. */\nfunction withoutAndroidReleaseValues(text: string): string | null {\n if (/\\/\\*|\"\"\"|'''/.test(text) || !/id\\s*\\(?\\s*[\"']com\\.android\\.(application|library)[\"']/.test(text)) return null;\n const scopes: string[] = [];\n const normalized: string[] = [];\n let assignments = 0;\n for (const line of text.split(\"\\n\")) {\n // Remove ordinary quoted strings and line comments solely for brace tracking.\n const code = line.replace(/\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|\\/\\/.*$/g, token => token.startsWith(\"//\") ? \"\" : '\"\"');\n const assignment = line.match(/^(\\s*)(versionName|versionCode)(\\s*(?:=\\s*|\\s+))(\"[A-Za-z0-9._+-]+\"|'[A-Za-z0-9._+-]+'|\\d+)(\\s*)$/);\n if (assignment && scopes.join(\"/\") === \"android/defaultConfig\" &&\n (assignment[2] === \"versionCode\" ? /^\\d+$/.test(assignment[4]) : /^[\"']/.test(assignment[4]))) {\n normalized.push(assignment[1] + assignment[2] + assignment[3] + \"<release-value>\" + assignment[5]);\n assignments++;\n } else {\n // References can feed dependency coordinates or other executable configuration.\n if (/\\bversion(?:Name|Code)\\b/.test(line)) return null;\n normalized.push(line);\n }\n const named = code.match(/^\\s*(android|defaultConfig)\\s*\\{\\s*$/)?.[1];\n for (const brace of code.matchAll(/[{}]/g)) {\n if (brace[0] === \"{\") scopes.push(named ?? \"unknown\");\n else if (!scopes.length) return null;\n else scopes.pop();\n }\n }\n return assignments && !scopes.length ? normalized.join(\"\\n\") : null;\n}\n\n/** Only omit single-parent commits whose every touched manifest is proven release metadata. */\nexport async function releaseMetadataOnly(root: string, commit: RangeCommits[\"commits\"][number]): Promise<boolean> {\n if (!commit.files.length || !commit.files.every(file => /(^|\\/)build\\.gradle(?:\\.kts)?$/.test(file))) return false;\n try {\n const parents = (await git(root, [\"rev-list\", \"--parents\", \"-n\", \"1\", commit.hash])).trim().split(/\\s+/);\n if (parents.length !== 2) return false;\n for (const file of commit.files) {\n const raw = await git(root, [\"diff\", \"--raw\", \"-z\", \"--no-renames\", \"--no-ext-diff\", \"--no-textconv\", parents[1], commit.hash, \"--\", file]);\n if (!/^:(100644|100755) \\1 [a-f0-9]+ [a-f0-9]+ M\\0/.test(raw)) return false;\n const [before, after] = await Promise.all([\n git(root, [\"show\", parents[1] + \":\" + file]), git(root, [\"show\", commit.hash + \":\" + file]),\n ]);\n const previous = withoutAndroidReleaseValues(before);\n if (previous === null || previous !== withoutAndroidReleaseValues(after)) return false;\n }\n return true;\n } catch { return false; }\n}\n","import { releaseMetadataOnly } from \"../release-metadata.js\";\nimport { commitsTouchingSince } from \"../git.js\";\nimport type { CheckContext, CheckResult } from \"./index.js\";\nimport { emptyResult } from \"./index.js\";\n\nconst MANIFEST_COMMITS_CAP = 10;\n\n/**\n * Tracked manifest files at any depth. Lockfiles are pure churn and are\n * deliberately not matched.\n */\nconst MANIFEST_PATHSPECS = [\n \":(glob)**/package.json\",\n \":(glob)**/build.gradle.kts\",\n \":(glob)**/build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \":(glob)**/Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"requirements.txt\",\n \"Gemfile\",\n \"composer.json\",\n];\n\n/**\n * Advisory, never an issue: a manifest commit after the doc's last commit\n * proves recency ordering, not that any specific claim is false — and it can\n * never be closed by editing the doc within the same run.\n */\nexport async function checkDepsChanged(\n ctx: CheckContext\n): Promise<CheckResult> {\n const result = emptyResult();\n result.suppressedAdvisories = [];\n const releaseOnly = new Map<string, boolean>();\n\n for (const doc of ctx.docs) {\n if (!doc.lastCommit) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has no commit history`,\n });\n continue;\n }\n if (doc.dirty) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path} has uncommitted edits – suppressed while in flight`,\n });\n }\n\n const range = await commitsTouchingSince(\n ctx.root,\n doc.lastCommit.hash,\n MANIFEST_PATHSPECS\n );\n if (range === null) {\n result.skipped.push({\n check: \"deps-changed\",\n doc: doc.path,\n reason: `${doc.path}: commit range unreachable (shallow clone?)`,\n });\n continue;\n }\n // Bound extra history reads. Older/ambiguous commits remain advisory.\n const relevant = [];\n for (const commit of range.commits) {\n if (!releaseOnly.has(commit.hash) && releaseOnly.size < 100) {\n releaseOnly.set(commit.hash, await releaseMetadataOnly(ctx.root, commit));\n }\n if (!releaseOnly.get(commit.hash)) relevant.push(commit);\n }\n range.commits = relevant;\n range.total = relevant.length;\n if (range.total === 0) continue;\n\n const latest = range.commits[0];\n (doc.dirty ? result.suppressedAdvisories : result.advisories).push({\n type: \"deps-changed\",\n message: `dependency manifests touched by ${range.total} commit${range.total === 1 ? \"\" : \"s\"} since ${doc.path} was last committed (latest: ${latest.hash.slice(0, 7)} \"${latest.subject}\")`,\n anchor: { doc: doc.path, line: null, excerpt: null },\n evidence: {\n kind: \"doc-behind-manifests\",\n docLastCommit: doc.lastCommit,\n manifestCommits: range.commits.slice(0, MANIFEST_COMMITS_CAP),\n totalCommits: range.total,\n },\n });\n }\n\n return result;\n}\n","import path from \"node:path\";\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\";\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\")) parts.push(\"Verification failed for returned entries; do not rely on those descriptions until corrected.\");\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 { readStoreJson, writeStoreJson, storePath, type StoreDiagnostic } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { jaccard, tokenSet } from \"../context/lexical.js\";\nimport { attributionSchema, decisionSchema, decisionContent, decisionApproval, effectiveDecision, importLegacy, type DecisionSource, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nexport type { DecisionRecord } from \"./provenance.js\";\n\nexport type DecisionCategory =\n | \"decision\"\n | \"gotcha\"\n | \"deprecation\"\n | \"convention\";\nexport type DecisionStatus = \"active\" | \"superseded\" | \"retired\";\n\nexport const TITLE_MAX_CHARS = 80;\nexport const BODY_MAX_CHARS = 1500;\nexport const MAX_ACTIVE_DECISIONS = 150;\n\nconst DUPLICATE_JACCARD = 0.5;\nconst DUPLICATE_JACCARD_WITH_SHARED_FILE = 0.35;\n\nexport async function loadDecisionStore(rootDir: string): Promise<{ records: DecisionRecord[]; diagnostics: StoreDiagnostic[] }> {\n const records: DecisionRecord[] = [];\n const diagnostics: StoreDiagnostic[] = [];\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, \".mason/decisions\")); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") diagnostics.push({ path: \".mason/decisions\", message: String(error) });\n return { records, diagnostics };\n }\n for (const entry of entries.sort()) {\n if (!entry.endsWith(\".json\")) continue;\n const relative = `.mason/decisions/${entry}`;\n try {\n const record = decisionSchema.parse(await readStoreJson(rootDir, relative));\n if (entry !== `${record.id}.json`) throw new Error(\"Record id does not match its filename\");\n records.push(record);\n } catch (error) { diagnostics.push({ path: relative, message: error instanceof Error ? error.message : String(error) }); }\n }\n return { records, diagnostics };\n}\n\nexport async function loadDecisions(rootDir: string): Promise<DecisionRecord[]> {\n return (await loadDecisionStore(rootDir)).records;\n}\n\nexport async function saveDecisionRecord(rootDir: string, record: DecisionRecord): Promise<void> {\n const validated = decisionSchema.parse(record);\n await writeStoreJson(rootDir, `.mason/decisions/${validated.id}.json`, validated);\n}\n\n/**\n * Deterministic, human-readable id: kebab slug of the title, ≤60 chars.\n * A slug collision with a DIFFERENT record appends a 6-hex content suffix.\n */\nexport function decisionIdFor(\n title: string,\n body: string,\n existingIds: Set<string>\n): string {\n const slug = title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60)\n .replace(/-+$/, \"\");\n if (!existingIds.has(slug)) return slug || \"decision\";\n const suffix = createHash(\"sha1\")\n .update(title + body)\n .digest(\"hex\")\n .slice(0, 6);\n return `${slug}-${suffix}`;\n}\n\nexport function findNearDuplicate(\n candidate: { title: string; body: string; files: string[] },\n existing: DecisionRecord[]\n): { record: DecisionRecord; similarity: number } | null {\n const candidateTokens = tokenSet(`${candidate.title} ${candidate.body}`);\n const candidateFiles = new Set(candidate.files);\n let best: { record: DecisionRecord; similarity: number } | null = null;\n\n for (const record of existing) {\n if (record.status !== \"active\") continue;\n const similarity = jaccard(\n candidateTokens,\n tokenSet(`${record.title} ${record.body}`)\n );\n const sharesFile = record.files.some((f) => candidateFiles.has(f));\n const threshold = sharesFile\n ? DUPLICATE_JACCARD_WITH_SHARED_FILE\n : DUPLICATE_JACCARD;\n if (similarity >= threshold && (!best || similarity > best.similarity)) {\n best = { record, similarity };\n }\n }\n return best;\n}\n\nexport interface UpsertDecisionInput {\n title: string;\n body: string;\n category: DecisionCategory;\n files?: string[];\n owner?: string | null;\n sources?: DecisionSource[];\n /** Only supply a known identity; never infer authorship from Git configuration. */\n actor?: string;\n /** Existing id to revise. Unchanged content is a no-op; use review_decision to reaffirm. */\n id?: string;\n /** Id of a decision this one replaces; the old record is kept, marked superseded. */\n supersedes?: string;\n /** Save even when a near-duplicate was detected. */\n force?: boolean;\n}\n\nexport type UpsertDecisionResult =\n | {\n status: \"created\" | \"updated\" | \"unchanged\" | \"superseded_and_created\";\n id: string;\n totalActive: number;\n warnings: string[];\n approval?: \"unreviewed\" | \"proposed\" | \"accepted\";\n hint?: string;\n pruneCandidates?: string[];\n }\n | { status: \"duplicate_suspected\"; existing: DecisionRecord; hint: string }\n | { status: \"error\"; error: string };\n\n/** Serialize tool writes so prepared reviews cannot overwrite another decision edit. */\nexport async function withDecisionWrite<T>(root: string, operation: () => Promise<T>): Promise<T | { status: \"error\"; error: string }> {\n const lockPath = await storePath(root, \".mason/decisions/.write-lock\", true);\n let lock;\n try { lock = await fs.open(lockPath, \"wx\", 0o600); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return { status: \"error\", error: \"Decision store is locked by another write. Retry after it finishes; an abandoned .mason/decisions/.write-lock must be removed only after confirming no writer is running.\" };\n throw error;\n }\n try { return await operation(); }\n finally { await lock.close(); await fs.unlink(lockPath); }\n}\n\nexport async function upsertDecision(rootDir: string, input: UpsertDecisionInput): Promise<UpsertDecisionResult> {\n const title = input.title.trim(), body = input.body.trim();\n if (!title || !body) return { status: \"error\", error: \"title and body must be non-empty\" };\n if (title.length > TITLE_MAX_CHARS) return { status: \"error\", error: `title exceeds ${TITLE_MAX_CHARS} chars — tighten it to a specific headline` };\n if (body.length > BODY_MAX_CHARS) return { status: \"error\", error: `body exceeds ${BODY_MAX_CHARS} chars — record the decision, not the transcript` };\n const attribution = attributionSchema.safeParse(input);\n if (!attribution.success) return { status: \"error\", error: attribution.error.message };\n if (input.id && input.supersedes) return { status: \"error\", error: \"Use either id to revise or supersedes to replace a record, not both.\" };\n return withDecisionWrite(rootDir, async () => {\n const store = await loadDecisionStore(rootDir);\n if (store.diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before saving: \" + store.diagnostics.map(d => d.path).join(\", \") };\n const existing = store.records, byId = new Map(existing.map(r => [r.id, r]));\n const now = new Date().toISOString(), head = await getCurrentGitHash(rootDir);\n const warnings: string[] = [];\n const files = sanitizeRepoPaths(input.files ?? []);\n if (input.files && files.length < input.files.length) warnings.push(\"some anchor paths were outside the repo or duplicated and were dropped\");\n for (const file of files) {\n try { await fs.access(path.join(rootDir, file)); }\n catch { warnings.push(`anchor file does not exist on disk: ${file}`); }\n }\n const hint = \"Saved locally for review and commit. Proposals are not accepted constraints; an existing accepted revision remains operative while its replacement is proposed. Use review_decision to inspect evidence and record an authorized acceptance or reaffirmation.\";\n if (input.id) {\n const original = byId.get(input.id);\n if (!original) return { status: \"error\", error: `no decision with id \"${input.id}\"` };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived records cannot be revised; create a new proposal.\" };\n const record = importLegacy(original, now);\n const content = decisionContent({ ...record, title, body, category: input.category,\n files: input.files !== undefined ? files : record.files,\n owner: attribution.data.owner === undefined ? record.owner : attribution.data.owner ?? undefined,\n sources: attribution.data.sources ?? record.sources,\n });\n if (JSON.stringify(content) === JSON.stringify(decisionContent(record))) {\n return { status: \"unchanged\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: decisionApproval(original), warnings,\n hint: \"Unchanged content; no review or freshness stamp was written. Use review_decision for explicit re-verification.\" };\n }\n const revision = record.revision + 1;\n const updated: ReviewedDecisionRecord = { ...record, ...content, owner: content.owner, updatedAt: now, revision, approval: \"proposed\",\n history: [...record.history, { kind: \"revised\", at: now, actor: attribution.data.actor, revision, content, approval: \"proposed\", status: \"active\", refreshedHash: record.refreshedHash }],\n };\n await saveDecisionRecord(rootDir, updated);\n return { status: \"updated\", id: record.id, totalActive: existing.filter(r => r.status === \"active\").length, approval: \"proposed\", warnings, hint };\n }\n const old = input.supersedes ? byId.get(input.supersedes) : undefined;\n if (input.supersedes && !old) return { status: \"error\", error: `no decision with id \"${input.supersedes}\" to supersede` };\n if (old && (old.status !== \"active\" || decisionApproval(effectiveDecision(old)) === \"accepted\")) {\n return { status: \"error\", error: \"A proposal cannot supersede an accepted or archived record. Create and review the replacement separately, then explicitly retire the old decision with review_decision.\" };\n }\n if (!input.force) {\n const duplicate = findNearDuplicate({ title, body, files }, existing);\n if (duplicate) return { status: \"duplicate_suspected\", existing: duplicate.record, hint: `A similar decision exists (\"${duplicate.record.title}\"). Call save_decision with id=\"${duplicate.record.id}\" to revise it, or force:true if distinct.` };\n }\n const id = decisionIdFor(title, body, new Set(byId.keys()));\n if (byId.has(id)) return { status: \"error\", error: `Decision id collision: ${id}. Choose a distinct title or revise the existing record.` };\n const content = decisionContent({ title, body, category: input.category, files, owner: attribution.data.owner ?? undefined, sources: attribution.data.sources ?? [] });\n const record: ReviewedDecisionRecord = { ...content, version: 2, id, createdAt: now, updatedAt: now, refreshedHash: head,\n status: \"active\", approval: \"proposed\", revision: 1,\n history: [{ kind: \"created\", at: now, actor: attribution.data.actor, revision: 1, content, approval: \"proposed\", status: \"active\", refreshedHash: head }],\n };\n // Write the replacement first: a failed second write leaves both records\n // available instead of removing the original before its replacement exists.\n await saveDecisionRecord(rootDir, record);\n if (old) {\n const imported = importLegacy(old, now);\n await saveDecisionRecord(rootDir, { ...imported, status: \"superseded\", supersededBy: id, updatedAt: now,\n history: [...imported.history, { kind: \"superseded\", at: now, actor: attribution.data.actor, note: `Replaced by proposal ${id}`,\n revision: imported.revision, content: decisionContent(imported), approval: imported.approval, status: \"superseded\", refreshedHash: imported.refreshedHash }],\n });\n }\n const totalActive = existing.filter(r => r.status === \"active\").length + (old ? 0 : 1);\n const result: UpsertDecisionResult = { status: old ? \"superseded_and_created\" : \"created\", id, totalActive, approval: \"proposed\", warnings, hint };\n if (totalActive > MAX_ACTIVE_DECISIONS) {\n result.pruneCandidates = existing.filter(r => r.status !== \"active\").map(r => r.id).slice(0, 10);\n warnings.push(`${totalActive} active decisions exceeds the soft cap of ${MAX_ACTIVE_DECISIONS} — consider a cleanup PR (archived records first)`);\n }\n return result;\n });\n}\n","import path from \"node:path\";\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 fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport type { FileChange } from \"../drift/drift.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { discoverDocs } from \"./docs.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditReport, CheckName } from \"./types.js\";\nimport { CHECKS } from \"./checks/index.js\";\nimport type { CheckContext, CheckResult } from \"./checks/index.js\";\n\nexport interface AuditOptions {\n /** Subset of checks to run; defaults to all. */\n checks?: CheckName[];\n /** Internal execution boundary used by the automation dependency cache. */\n runCheck?: (name: CheckName, context: CheckContext) => Promise<CheckResult>;\n}\n\n/**\n * Audit the repo's context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\n * against repo reality. Fully deterministic — git, filesystem, and lexical\n * extraction only; no LLM, no network. Returns null when no context file\n * exists.\n */\nexport async function computeAudit(\n rootDir: string,\n options: AuditOptions = {}\n): Promise<AuditReport | null> {\n const resolvedRoot = path.resolve(rootDir);\n const [docs, headHash] = await Promise.all([discoverDocs(resolvedRoot), getCurrentGitHash(resolvedRoot)]);\n if (docs.length === 0) return null;\n\n const report: AuditReport = {\n version: 1,\n root: resolvedRoot,\n gitAvailable: headHash !== \"unknown\",\n headHash,\n checksRun: [],\n docs: docs.map((d) => ({\n path: d.path,\n lastCommit: d.lastCommit,\n dirty: d.dirty,\n lineCount: d.lineCount,\n })),\n decisionsChecked: false,\n issues: [],\n advisories: [],\n suppressedAdvisories: [],\n skippedChecks: [],\n clean: true,\n };\n\n // Without git the provability gates cannot run — the caller treats this\n // as an error rather than silently degrading precision.\n if (!report.gitAvailable) return report;\n\n const changesSinceDoc = new Map<string, FileChange[] | null>();\n for (const doc of docs) {\n changesSinceDoc.set(\n doc.path,\n doc.lastCommit\n ? await getChangesWithStatus(resolvedRoot, doc.lastCommit.hash)\n : null\n );\n }\n\n let decisionsPresent = false;\n try {\n await fs.access(path.join(resolvedRoot, \".mason\", \"decisions\"));\n decisionsPresent = true;\n } catch {\n // No decision store — the check stays dark (zero-setup path).\n }\n report.decisionsChecked = decisionsPresent;\n\n const ctx: CheckContext = {\n root: resolvedRoot,\n docs,\n headHash,\n changesSinceDoc,\n decisionsPresent,\n };\n\n const selected = options.checks ?? ALL_CHECKS;\n for (const name of ALL_CHECKS) {\n if (!selected.includes(name)) continue;\n const { issues, advisories, suppressedAdvisories, skipped } = await (options.runCheck\n ? options.runCheck(name, ctx) : CHECKS[name](ctx));\n report.checksRun!.push(name);\n report.issues.push(...issues);\n report.advisories.push(...advisories);\n report.suppressedAdvisories!.push(...(suppressedAdvisories ?? []));\n report.skippedChecks.push(...skipped);\n }\n\n report.clean = report.issues.length === 0;\n return report;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { computeAudit, type AuditOptions } from \"./audit.js\";\nimport { DOC_CANDIDATES } from \"./docs.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus } from \"../drift/drift.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readBoundedFile } from \"../utils/files.js\";\nimport { isWithinRoot } from \"../utils/paths.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport type { AuditAdvisory, AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nconst checkSchema = z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]);\nconst commitSchema = z.object({ hash: z.string().regex(/^[a-f0-9]{40,64}$/), date: z.string(), subject: z.string() });\nconst anchorSchema = z.object({ doc: z.string(), line: z.number().int().positive().nullable(), excerpt: z.string().nullable() });\nconst count = z.number().int().nonnegative();\nconst evidenceSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"missing-path\"), claimed: z.string(), renamedTo: z.string().nullable(),\n deletedInCommit: commitSchema.nullable(), everTracked: z.boolean(), parentDirExists: z.boolean() }),\n z.object({ kind: z.literal(\"unmentioned-dir\"), dir: z.string(), sourceFileCount: count,\n firstCommit: commitSchema.nullable(), checkedDocs: z.array(z.string()) }),\n z.object({ kind: z.literal(\"count-mismatch\"), claimed: count, actual: count, unit: z.string(),\n countedFrom: z.string(), members: z.array(z.string()) }),\n z.object({ kind: z.literal(\"missing-script\"), scriptName: z.string(), invocation: z.string(),\n manifestsChecked: z.array(z.string()), availableScripts: z.array(z.string()) }),\n z.object({ kind: z.literal(\"doc-behind-manifests\"), docLastCommit: commitSchema,\n manifestCommits: z.array(commitSchema.extend({ files: z.array(z.string()) })), totalCommits: count }),\n z.object({ kind: z.literal(\"decision-anchor\"), decisionId: z.string(), title: z.string(),\n changedFiles: z.array(z.string()), refreshedHash: z.string(),\n provenance: z.object({}).passthrough().optional() }),\n]);\nconst findingSchema = z.object({ message: z.string(), anchor: anchorSchema, evidence: evidenceSchema });\nconst issueSchema = findingSchema.extend({\n type: z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\"]),\n confidence: z.enum([\"certain\", \"likely\"]),\n});\nconst advisorySchema = findingSchema.extend({ type: z.enum([\"deps-changed\", \"decision-anchor-drift\"]) });\nexport const checkResultSchema = z.object({\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skipped: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst reportSchema = z.object({\n version: z.literal(1), root: z.string(), gitAvailable: z.literal(true),\n headHash: commitSchema.shape.hash, checksRun: z.array(checkSchema).nonempty(),\n docs: z.array(z.object({ path: z.enum(DOC_CANDIDATES), lastCommit: commitSchema.nullable(),\n dirty: z.boolean(), lineCount: count })).nonempty(),\n decisionsChecked: z.boolean(), clean: z.boolean(),\n issues: z.array(issueSchema), advisories: z.array(advisorySchema),\n suppressedAdvisories: z.array(advisorySchema).optional(),\n skippedChecks: z.array(z.object({ check: z.string(), reason: z.string(), doc: z.string().optional() })),\n});\nconst baselineSchema = z.object({\n kind: z.literal(\"mason-audit-repair\"), version: z.literal(1),\n createdAt: z.string().datetime(), report: reportSchema, digest: z.string().regex(/^[a-f0-9]{64}$/),\n});\nconst digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n\nexport type RepairStatus = \"resolved\" | \"unresolved\" | \"review-required\" | \"unverified\";\ntype Finding = AuditIssue | AuditAdvisory;\nexport interface RepairFinding {\n id: string;\n original: Finding;\n status: RepairStatus;\n reason: string;\n current?: Finding;\n}\nexport interface RepairVerification {\n version: 1;\n action: \"verify\";\n baselinePath: string;\n baselineHead: string;\n currentHead: string | null;\n status: \"verified\" | \"issues-remain\" | \"incomplete\";\n findings: RepairFinding[];\n newFindings: Finding[];\n diagnostics: string[];\n currentAudit: AuditReport | null;\n counts: Record<RepairStatus, number>;\n scope: string;\n}\n\n/** Lines and wording can change without changing the underlying claim. */\nexport function findingId(finding: Finding): string {\n const e = finding.evidence;\n let key: unknown;\n switch (e.kind) {\n case \"missing-path\": key = e.claimed; break;\n case \"unmentioned-dir\": key = e.dir; break;\n case \"count-mismatch\": key = [e.unit.replace(/s$/, \"\"), e.countedFrom]; break;\n case \"missing-script\": key = e.scriptName; break;\n case \"doc-behind-manifests\": key = null; break;\n case \"decision-anchor\": key = [e.decisionId, e.provenance?.revision, e.provenance?.approval]; break;\n }\n return digest([finding.type, finding.anchor.doc, key]);\n}\nfunction allFindings(report: AuditReport): Finding[] {\n return [...report.issues, ...report.advisories, ...(report.suppressedAdvisories ?? [])];\n}\n\nasync function docState(root: string): Promise<string> {\n const docs = [];\n for (const doc of DOC_CANDIDATES) {\n try {\n const content = await readBoundedFile(await storePath(root, doc), 10 * 1024 * 1024);\n if (content === null) throw new Error(\"Context file is not regular or exceeds 10 MiB: \" + doc);\n docs.push([doc, digest(content)]);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n docs.push([doc, null]);\n }\n }\n return digest(docs);\n}\n\n/** Refuse a verification assembled across a commit or instruction-file edit. */\nasync function stableAudit(root: string, checks: CheckName[], options: AuditOptions = {}) {\n const head = await getCurrentGitHash(root);\n const before = await docState(root);\n const report = await computeAudit(root, { ...options, checks });\n if (head !== await getCurrentGitHash(root) || before !== await docState(root) ||\n (report && report.headHash !== head)) {\n throw new Error(\"HEAD or context files changed during the audit; retry against a stable checkout.\");\n }\n return report;\n}\n\nexport async function prepareRepair(rootDir: string, checks: CheckName[] = ALL_CHECKS, options: AuditOptions = {}) {\n const root = await fs.realpath(rootDir);\n const selected = z.array(checkSchema).nonempty().parse(checks);\n const report = await stableAudit(root, selected, options);\n if (!report) throw new Error(\"No context files found to prepare a repair.\");\n if (!report.gitAvailable) throw new Error(\"Readable Git history is required to prepare a repair.\");\n // Canonicalize before hashing; validation on read must yield the same bytes.\n const storedReport = reportSchema.parse(report);\n const payload = { kind: \"mason-audit-repair\" as const, version: 1 as const,\n createdAt: new Date().toISOString(), report: storedReport };\n const baselinePath = \".mason/reports/repairs/\" + randomUUID() + \".json\";\n await writeStoreJson(root, baselinePath, { ...payload, digest: digest(payload) });\n return { version: 1 as const, action: \"prepare\" as const, baselinePath, report };\n}\n\nexport async function verifyRepair(rootDir: string, baselinePath: string, options: AuditOptions = {}): Promise<RepairVerification> {\n const root = await fs.realpath(rootDir);\n const declaredRoot = path.resolve(rootDir);\n const relative = path.isAbsolute(baselinePath)\n ? path.relative(isWithinRoot(declaredRoot, baselinePath) ? declaredRoot : root, baselinePath)\n : baselinePath;\n const stored = baselineSchema.parse(await readStoreJson(root, relative));\n const { digest: savedDigest, ...payload } = stored;\n if (digest(payload) !== savedDigest) throw new Error(\"Repair baseline was modified; use the original baseline.\");\n if (stored.report.root !== root) throw new Error(\"Repair baseline belongs to a different repository.\");\n const original = stored.report as AuditReport;\n const diagnostics: string[] = [];\n let current: AuditReport | null = null;\n try {\n current = await stableAudit(root, original.checksRun!, options);\n if (!current) diagnostics.push(\"No context files remain available to audit.\");\n else if (!current.gitAvailable) diagnostics.push(\"Git history is unavailable.\");\n for (const doc of original.docs) {\n if (!original.issues.some(f => f.anchor.doc === doc.path) || !current?.docs.some(d => d.path === doc.path)) continue;\n const content = await readBoundedFile(await storePath(root, doc.path), 10 * 1024 * 1024);\n if (content === null || !content.trim()) {\n diagnostics.push(\"Original context file \" + doc.path + \" is empty or unreadable; losing its claims does not verify a repair.\");\n }\n }\n if (await getChangesWithStatus(root, original.headHash!) === null) {\n diagnostics.push(\"The original audit commit is unavailable; repair history cannot be verified.\");\n }\n } catch (error) {\n diagnostics.push(error instanceof Error ? error.message : String(error));\n }\n const currentById = new Map((current ? allFindings(current) : []).map(f => [findingId(f), f]));\n const originalFindings = allFindings(original);\n const originalIds = new Set(originalFindings.map(findingId));\n const missingDocs = original.docs.filter(doc => !current?.docs.some(d => d.path === doc.path));\n for (const doc of missingDocs) diagnostics.push(\"Original context file \" + doc.path + \" is unavailable; removing it does not verify a repair.\");\n const findings = originalFindings.map((finding): RepairFinding => {\n const id = findingId(finding);\n const now = currentById.get(id);\n const base = { id, original: finding, ...(now ? { current: now } : {}) };\n if (diagnostics.length || !current) {\n return { ...base, status: \"unverified\", reason: \"The original audit scope could not be verified. See diagnostics.\" };\n }\n if (\"confidence\" in finding && now) {\n return { ...base, status: \"unresolved\", reason: \"The original check still reports this claim.\" };\n }\n const skipped = current.skippedChecks.filter(s => s.check === finding.type && (!s.doc || s.doc === finding.anchor.doc));\n if (!current.checksRun?.includes(finding.type) || skipped.length) {\n return { ...base, status: \"unverified\", reason: skipped.map(s => s.reason).join(\"; \") || \"The original check did not run.\" };\n }\n if (!(\"confidence\" in finding)) {\n return { ...base, status: \"review-required\",\n reason: \"An audit cannot establish that this advisory was reviewed. Retain its original evidence and report a separate assessment; editing or committing the doc is not approval.\" };\n }\n return { ...base, status: \"resolved\", reason: \"The original check ran and no longer reports this claim. Inspect the edit for semantic correctness.\" };\n });\n const newFindings = [...currentById].filter(([id]) => !originalIds.has(id)).map(([, f]) => f);\n const counts: Record<RepairStatus, number> = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const f of findings) counts[f.status]++;\n const incomplete = diagnostics.length > 0 || counts.unverified > 0 || counts[\"review-required\"] > 0 ||\n (current?.skippedChecks.length ?? 0) > 0 || newFindings.some(f => !(\"confidence\" in f));\n const issuesRemain = counts.unresolved > 0 || newFindings.some(f => \"confidence\" in f);\n return {\n version: 1, action: \"verify\", baselinePath: relative, baselineHead: original.headHash!,\n currentHead: current?.gitAvailable ? current.headHash! : null,\n status: incomplete ? \"incomplete\" : issuesRemain ? \"issues-remain\" : \"verified\",\n findings, newFindings, diagnostics, currentAudit: current, counts,\n scope: \"Original audit checks over current context files and repository evidence. Resolved means no longer detected by that check. Advisories require separate review; this is not a certification of documentation or application correctness.\",\n };\n}\n\nexport function repairExitCode(report: RepairVerification): number {\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n}\n\nexport function formatRepairSummary(report: RepairVerification): string {\n return [\n \"Repair verification: \" + report.status + \". Baseline: \" + report.baselinePath,\n ...report.findings.map(f => \" [\" + f.status + \"] \" + f.original.type + \" \" + f.original.anchor.doc + \": \" + f.original.message + \"\\n \" + f.reason),\n ...report.newFindings.map(f => \" [new] \" + f.type + \" \" + f.anchor.doc + \": \" + f.message),\n ...report.diagnostics.map(d => \" [unverified] \" + d),\n ...(report.currentAudit?.skippedChecks ?? []).map(s => \" [skipped] \" + s.check + \": \" + s.reason),\n report.scope,\n ].join(\"\\n\");\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport fg from \"fast-glob\";\nimport { z } from \"zod\";\nimport { DOC_CANDIDATES } from \"../audit/docs.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 { readBoundedFile, SOURCE_IGNORE } from \"../utils/files.js\";\nimport { moduleCandidates } from \"../audit/checks/new-module.js\";\nimport { resolveCountSource } from \"../audit/checks/stale-count.js\";\nimport { commandManifests } from \"../audit/checks/dead-command.js\";\nimport { storePath } from \"../utils/storage.js\";\n\nconst exec = promisify(execFile);\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 (await exec(\"git\", 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 = await fs.realpath((await git(root, \"rev-parse\", \"--absolute-git-dir\")).trim());\n let branch: string;\n try { branch = (await git(root, \"symbolic-ref\", \"--quiet\", \"HEAD\")).trim(); }\n catch { branch = \"detached\"; }\n return { root, gitDir, branch, directory: \".mason/reports/automation/\" + hash([root, gitDir, branch]).slice(0, 24) };\n}\n\nasync function content(root: string, file: string): Promise<string | null> {\n try {\n const value = await readBoundedFile(await storePath(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 ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nconst internal = (file: string) => file === \".mason\" || file === \".mason/reports\" || file.startsWith(\".mason/reports/\");\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 const [headText, docStatus, inventory, shallowPath, replacements] = await Promise.all([\n git(root, \"rev-parse\", \"HEAD\"),\n git(root, \"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--\", ...DOC_CANDIDATES),\n fg(\"**/*\", { cwd: root, dot: true, onlyFiles: false, followSymbolicLinks: false, objectMode: true,\n ignore: SOURCE_IGNORE }),\n git(root, \"rev-parse\", \"--git-path\", \"shallow\"),\n git(root, \"for-each-ref\", \"--format=%(refname) %(objectname)\", \"refs/replace\"),\n ]);\n const entries = inventory.filter(f => !internal(f.path) && f.path !== \".git\").sort((a, b) => a.path.localeCompare(b.path));\n const files = entries.map(f => f.path);\n if (files.length > 100000) throw new Error(\"Automation input inventory exceeds 100,000 paths; use an explicit scoped audit.\");\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 claims: Array<[string, boolean, boolean]> = [];\n for (const file of DOC_CANDIDATES) {\n const text = await content(root, file);\n docs[file] = text === null ? null : hash(text);\n docContents.push([file, text]);\n for (const claim of text ? extractClaims(text).paths : []) {\n if (internal(claim.path) || claim.path.startsWith(\".mason/\")) continue;\n // Explicit claims can name ignored files, directories, or symlink targets.\n const exists = async (p: string) => fs.access(path.resolve(root, p)).then(() => true, () => false);\n claims.push([claim.path, await exists(claim.path), await exists(path.dirname(claim.path))]);\n }\n }\n // The existing audit follows some directory symlinks. Refuse to cache an\n // unbounded external dependency instead of claiming its targets were checked.\n if (entries.some(f => f.dirent.isSymbolicLink())) throw new Error(\"Automation inventory contains a symbolic link; use an explicit audit to inspect its scope. No cached verification was recorded.\");\n const combinedDocs = docContents.map(([, text]) => text ?? \"\").join(\"\\n\");\n const countClaims = docContents.flatMap(([, text]) => text ? extractClaims(text).counts : []);\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, manifests, decisionFiles] = await Promise.all([\n combinedDocs ? moduleCandidates(root, combinedDocs) : [],\n Promise.all(countClaims.map(claim => resolveCountSource(root, claim))),\n commandManifests(root),\n fg(\".mason/decisions/*.json\", { cwd: root, dot: true, onlyFiles: false, followSymbolicLinks: false }),\n ]);\n const packages = await Promise.all([\"package.json\", ...manifests.sort()].map(async file => [file, await content(root, file)]));\n const decisions = await Promise.all(decisionFiles.sort().map(async file => [file, await content(root, file)]));\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 = [2, 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, packages]),\n \"deps-changed\": hash([common, docStatus]),\n \"decision-anchor-drift\": hash([common, decisionPresence, decisions, status, index]),\n };\n return { fingerprint: hash(keys), 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 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, serialize: () => {\n const canonical = cacheSchema.shape.entries.parse(entries);\n return { version: 1, entries: canonical, digest: hash(canonical) };\n } };\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { z } from \"zod\";\nimport { storePath } from \"../utils/storage.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});\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/** Cross-process lock: a killed writer's lock is reclaimed only after its local PID is gone. */\nexport async function withLock<T>(root: string, directory: string, run: () => Promise<T>): Promise<T> {\n const file = await storePath(root, directory + \"/lock\", true);\n const deadline = Date.now() + 5000;\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 // Renaming a stale lock arbitrates reclamation without unlinking a new writer's lock.\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(\"Automation is busy or its lock needs inspection: \" + 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 { recordExecution, executionStatus } from \"./execution.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { prepareRepair, verifyRepair, findingId, 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 } 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\"] };\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 claims no longer fail their checks; advisories need separate review. Repair 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\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\n/** Durable, host-neutral lifecycle. Only evidence/cache/receipts are written. */\nexport async function automate(dir: string, event: AutomationEvent) {\n const ws = await workspace(dir);\n return withLock(ws.root, ws.directory, () => recordExecution(ws.root, ws.directory, event.event, async () => {\n const inputs = await readInputs(ws.root);\n const statePath = ws.directory + \"/state.json\";\n const raw = await readStoreJson(ws.root, statePath);\n const now = new Date().toISOString();\n const state: State = raw === null ? {\n version: 1, root: ws.root, gitDir: ws.gitDir, branch: ws.branch, baselines: [], sessions: {},\n updatedAt: now, 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 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 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 // Receipts and notification dedupe are bounded; baselines are never evicted.\n const keys = Object.keys(state.sessions).sort((a, b) => state.sessions[a].lastUsed.localeCompare(state.sessions[b].lastUsed));\n for (const expired of keys.slice(0, Math.max(0, keys.length - 31))) delete state.sessions[expired];\n state.sessions[key] = { host: event.host!, seen: null, continued: false, initialIssues: [], 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 }\n if (!state.baselines.length && Object.values(inputs.docs).every(value => value === null)) {\n const report: AutomationReport = { version: 1, status: \"unavailable\", root: ws.root, branch: ws.branch, head: inputs.head,\n baselinePaths: [], reportPath: ws.directory + \"/checks/\" + randomUUID() + \".json\", findings: [],\n diagnostics: [\"No AGENTS.md, CLAUDE.md, or .claude/CLAUDE.md exists. 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 const notify = !session || session.seen !== \"no-docs\";\n if (session) session.seen = \"no-docs\";\n state.fingerprint = inputs.fingerprint; state.latest = report.reportPath; state.updatedAt = now;\n await writeStoreJson(ws.root, report.reportPath, report);\n await writeStoreJson(ws.root, statePath, state);\n return { report, message: notify ? summarize(report) : null, continueOnce: false };\n }\n let cached: unknown = null;\n const diagnostics: string[] = [];\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 const saveBaseline = async () => {\n if (state.baselines.length >= 128) throw new Error(\"128 retained baselines need review; automatic capture stopped without discarding original evidence.\");\n const prepared = await prepareRepair(ws.root, ALL_CHECKS, cache.options);\n state.baselines.push({ path: prepared.baselinePath, at: now, event: event.event, fingerprint: inputs.fingerprint });\n };\n if (!state.baselines.length) await saveBaseline();\n const verifications: RepairVerification[] = [];\n for (const baseline of state.baselines) verifications.push(await verifyRepair(ws.root, baseline.path, cache.options));\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 verifyRepair(ws.root, state.baselines.at(-1)!.path, cache.options));\n }\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 if (newSession && session) session.initialIssues = [...merged.values()].filter(f => f.status === \"unresolved\").map(f => f.id);\n const current = verifications.at(-1)!.currentAudit;\n const counts = { resolved: 0, unresolved: 0, \"review-required\": 0, unverified: 0 };\n for (const finding of merged.values()) counts[finding.status]++;\n if (session) diagnostics.push(...session.coverageGaps);\n const capture = session && !session.coverageGaps.length && (session.events.session_start || session.events.before_tool) ? \"observed\" : \"unknown\";\n const after = await readInputs(ws.root);\n const currentWs = await 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 const report: AutomationReport = {\n version: 1,\n 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: state.baselines.map(b => b.path),\n reportPath: ws.directory + \"/checks/\" + randomUUID() + \".json\",\n findings: [...merged.values()], diagnostics: [...new Set(diagnostics)],\n checks: { ran: [...cache.ran], reused: [...cache.reused].filter(name => !cache.ran.has(name)), skipped: current?.skippedChecks ?? [] },\n counts, capture, scope: SCOPE,\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 &&\n !session.continued && !event.stopHookActive;\n const notify = !session || newSession || signature !== session.seen || continueOnce;\n if (session) {\n session.seen = signature;\n if (continueOnce) session.continued = true;\n }\n // Repeated tools with identical evidence need receipts, not another full report artifact.\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;\n state.fingerprint = inputs.fingerprint;\n state.latest = report.reportPath;\n // Publish complete evidence before publishing the pointer that refers to it.\n if (persistReport) await writeStoreJson(ws.root, report.reportPath, report);\n if (cache.ran.size || cached === null || cache.diagnostic) await writeStoreJson(ws.root, ws.directory + \"/cache.json\", cache.serialize());\n await writeStoreJson(ws.root, statePath, state);\n return { report, message: notify ? summarize(report) : null, continueOnce };\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 workspace(dir);\n const execution = await executionStatus(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 };\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,\n note: \"Observed events do not prove all tool paths are intercepted. Run check to verify the retained evidence.\" };\n}\n","import { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\n\nexport const runtimeSchema = z.object({\n id: z.string().regex(/^[a-f0-9]{24}$/), version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/),\n hashes: z.record(z.string().regex(/^[a-f0-9]{64}$/)),\n});\nexport type Runtime = z.infer<typeof runtimeSchema>;\nexport const setupHostSchema = z.object({\n runtime: runtimeSchema, 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(1), hosts: z.object({\n codex: setupHostSchema.optional(), claude: setupHostSchema.optional(),\n}) });\nexport type SetupConfig = z.infer<typeof setupSchema>;\nexport async function loadSetup(root: string): Promise<SetupConfig | null> {\n const raw = await readStoreJson(root, \".mason/setup.json\");\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 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\";\n\nconst observationSchema = z.object({ version: z.literal(1), 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) { return `${directory}/activation/${host}-${revision}.json`; }\n\nexport async function readObservation(root: string, directory: string, host: Host, revision: string): Promise<Observation | null> {\n const raw = await readStoreJson(root, observationPath(directory, host, revision));\n if (raw === null) return null;\n const record = observationSchema.parse(raw);\n if (record.root !== root || record.host !== host || record.revision !== revision) throw new Error(\"Activation receipt belongs to another installation.\");\n return record;\n}\n\n/** Only the configured launcher 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;\n} = {}): Promise<string | null> {\n const host = process.env.MASON_SETUP_HOST, revision = process.env.MASON_SETUP_REVISION;\n if ((host !== \"codex\" && host !== \"claude\") || !revision || !process.env.MASON_SETUP_ROOT) return null;\n try {\n const capturedDirectory = 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, 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 { failureMessage } from \"./execution.js\";\nimport { z } from \"zod\";\nimport { automate, type AutomationEvent } from \"./runtime.js\";\nimport { hostSchema, type Host } from \"./store.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; 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)$/;\n return { cwd: input.cwd, name: input.hook_event_name, event: {\n event: lifecycle[input.hook_event_name], host, sessionId: input.session_id, toolId: input.tool_use_id,\n mutating: !!input.tool_name && !readOnly.test(input.tool_name),\n stopHookActive: input.stop_hook_active || input.permission_mode === \"plan\",\n } };\n}\n\nexport async function runAutomationHook(host: Host, stdin: string): Promise<Record<string, unknown> | null> {\n let name = \"\";\n try {\n if (Buffer.byteLength(stdin) > 1024 * 1024) throw new Error(\"Hook input exceeds 1 MiB.\");\n const input = normalizeHook(host, JSON.parse(stdin));\n name = input.name;\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 = failureMessage(error);\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;\nexport function hookConfig(host: Host, command = \"npx --no-install --package mason-context mason-auto\") {\n const handler = { type: \"command\", command: 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 { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { workspace } from \"./evidence.js\";\nimport { HOOK_EVENTS, hookConfig } from \"./adapters.js\";\nimport { withLock, type Host } from \"./store.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();\nconst recordSchema = z.object({ version: z.literal(1), hosts: z.record(z.object({ command: z.string() })) });\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/automation-install\", () => installLocked(ws.root, host, command));\n}\n\nexport async function planAutomationInstall(root: string, host: Host, command?: string) {\n const file = configPath(host);\n const existing = automationConfigSchema.parse(await readStoreJson(root, file) ?? {});\n const record = recordSchema.parse(await readStoreJson(root, \".mason/automation.json\") ?? { version: 1, hosts: {} });\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 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 (handler.command === previous || handler.command === newCommand))),\n })).filter(group => group.hooks.length);\n hooks[event].push(...desired.hooks[event]);\n }\n record.hosts[host] = { command: newCommand };\n return { file, config: { ...existing, hooks }, record, newCommand };\n}\n\nasync function installLocked(root: string, host: Host, command?: string) {\n const { file, config, record, newCommand } = await planAutomationInstall(root, host, command);\n await writeStoreJson(root, file, config);\n await writeStoreJson(root, \".mason/automation.json\", record);\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 raw = await readStoreJson(ws.root, \".mason/automation.json\");\n if (raw === null) return {};\n const record = recordSchema.parse(raw);\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 { z } from \"zod\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.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() }).optional(),\n}).passthrough();\n\nexport async function loadProjectMarker(rootDir: string): Promise<ProjectMarker | null> {\n const raw = await readStoreJson(rootDir, \".mason/project.json\");\n return raw === null ? null : markerSchema.parse(raw);\n}\n\nexport async function saveProjectMarker(rootDir: string, marker: ProjectMarker): Promise<void> {\n await writeStoreJson(rootDir, \".mason/project.json\", markerSchema.parse(marker));\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, or change request → \\`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- Learned something the code cannot explain (a failed approach, an incident's cause, a workaround's reason, a review-settled convention) → \\`save_decision\\` with rationale, anchors, and any known owner, sources, and recorder. It creates a proposal immediately without setup or a map. Never invent attribution or record code-derivable facts, session trivia, or secrets.\n- Consult trust metadata before relying on entries: unknown or changed freshness requires inspection, and failed verification 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\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, install a pinned private runtime, 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 the Mason runtime, 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, call \\`save_decision\\` with title, body, category, anchors, and known owner/source/actor information. 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 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 { 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\"]),\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 report: z.object({ format: z.enum([\"vitest-json\", \"sarif\"]), 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}\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 };\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.kind === \"tests\") !== (check.report.format === \"vitest-json\")) throw new Error(\"Test checks require vitest-json; analysis checks require sarif.\");\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) : 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.report.format === \"vitest-json\" && 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 AGENTS.md, CLAUDE.md, or .claude/CLAUDE.md 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 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 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: a resumed setup cannot overwrite a user's concurrent edit. */\nexport async function applyEdit(root: string, edit: FileEdit): 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(\"Setup input changed during installation: \" + edit.path + \". Rerun setup to resume.\");\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(\"Setup input changed during installation: \" + edit.path);\n await fs.rename(temporary, file);\n return true;\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import type { Host } from \"../automation/store.js\";\n\n// Keep configuration portable across clones and subdirectory launches. Arguments\n// are fixed strings, never interpolated repository paths or user tool input.\nexport const BOOTSTRAP = \"require(require('node:path').join(require('node:child_process').execFileSync('git',['rev-parse','--show-toplevel'],{encoding:'utf8'}).trim(),'.mason','run.cjs'))\";\nexport const mcpCommand = (host: Host) => ({ command: \"node\", args: [\"-e\", BOOTSTRAP, \"--\", host, \"mcp\"] });\nexport const hookCommand = (host: Host) => `node -e \"${BOOTSTRAP}\" -- ${host} auto`;\n\nexport const LAUNCHER = `// Managed by mason-auto setup. Rerun setup to install this checkout's pinned runtime.\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst {pathToFileURL} = require('node:url');\nconst launchArgs = process.argv.slice(1);\n(async () => {\n const root = path.dirname(__dirname);\n const args = launchArgs;\n const [host, command, ...rest] = args;\n if (!['codex','claude'].includes(host) || !['auto','mcp'].includes(command)) throw new Error('Invalid Mason launcher arguments.');\n const setup = JSON.parse(fs.readFileSync(path.join(__dirname, 'setup.json'), 'utf8'));\n const entry = setup.hosts?.[host];\n if (setup.version !== 1 || !entry || !/^[a-f0-9]{24}$/.test(entry.runtime?.id)) throw new Error('Mason is not configured for this host. Rerun mason-auto setup.');\n const binary = path.join(__dirname, 'runtime', entry.runtime.id, 'node_modules', 'mason-context', 'dist', 'mason-' + command + '.js');\n if (!fs.existsSync(binary)) throw new Error('The pinned Mason runtime is missing in this checkout. Rerun mason-auto setup --host ' + host + '.');\n process.env.MASON_SETUP_ROOT = root;\n process.env.MASON_SETUP_HOST = host;\n process.env.MASON_SETUP_REVISION = entry.revision;\n process.argv = [process.execPath, binary, ...rest];\n await import(pathToFileURL(binary).href);\n})().catch(error => {\n const message = 'Mason setup unavailable: ' + error.message;\n if (launchArgs[1] === 'auto' && launchArgs[2] === 'hook') { console.log(JSON.stringify({systemMessage: message})); process.exitCode = 0; }\n else { console.error(message); process.exitCode = 2; }\n});\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 } from \"../automation/adapters.js\";\nimport { configPath, automationConfigSchema } from \"../automation/install.js\";\nimport type { Host } from \"../automation/store.js\";\nimport { readText, managedBlock, type FileEdit } from \"./files.js\";\nimport { hookCommand, LAUNCHER, 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, ...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: \".mason/automation.json\", before: await readText(root, \".mason/automation.json\"), 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 { git } = await import(\"../automation/evidence.js\");\n let parentIgnored = false;\n try { parentIgnored = !!(await git(root, \"check-ignore\", \"--no-index\", \".mason\")).trim(); }\n catch (error) { if ((error as { code?: number }).code !== 1) throw error; }\n const retainParentRule = parentIgnored || !!ignore?.replace(/\\r\\n/g, \"\\n\").includes(\"# mason:ignore:start\\n!/.mason/\\n/.mason/*\");\n const rules = [...(retainParentRule ? [\"!/.mason/\", \"/.mason/*\"] : []), \"!/.mason/decisions/\", \"!/.mason/decisions/**\", \"!/.mason/setup.json\", \"!/.mason/automation.json\", \"!/.mason/project.json\", \"!/.mason/run.cjs\", \"/.mason/reports/\", \"/.mason/runtime/\"].join(\"\\n\");\n return [{ path: \".gitignore\", before: ignore, after: managedBlock(ignore ?? \"\", \"# mason:ignore:start\", \"# mason:ignore:end\", rules) },\n { path: \".mason/run.cjs\", before: await readText(root, \".mason/run.cjs\"), after: LAUNCHER }];\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 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 => handler.command === expected.hooks.SessionStart[0].hooks[0].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 fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { randomUUID, createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { runtimeSchema, type Runtime } from \"./model.js\";\nimport { readStoreJson, storePath } from \"../utils/storage.js\";\nimport { hash } from \"../automation/evidence.js\";\n\nconst exec = promisify(execFile);\nconst checksum = (bytes: Buffer) => createHash(\"sha256\").update(bytes).digest(\"hex\");\nconst BINARIES = [\"dist/mason-auto.js\", \"dist/mason-mcp.js\"];\nasync function packageRoot() {\n let directory = path.dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 8; i++) {\n try {\n const pkg = JSON.parse(await fs.readFile(path.join(directory, \"package.json\"), \"utf8\"));\n if (pkg.name === \"mason-context\") return directory;\n } catch { /* Locate the executing distribution, never the target project's package. */ }\n directory = path.dirname(directory);\n }\n throw new Error(\"Cannot locate the executing Mason distribution. Reinstall Mason and rerun setup.\");\n}\nexport async function sourceRuntime(): Promise<{ source: string; runtime: Runtime }> {\n const source = await packageRoot();\n const pkg = JSON.parse(await fs.readFile(path.join(source, \"package.json\"), \"utf8\"));\n const hashes = Object.fromEntries(await Promise.all(BINARIES.map(async file => [file, checksum(await fs.readFile(path.join(source, file)))])));\n return { source, runtime: runtimeSchema.parse({ id: hash([pkg.version, pkg.dependencies, hashes]).slice(0, 24), version: pkg.version, hashes }) };\n}\nexport async function verifyRuntime(root: string, runtime: Runtime): Promise<boolean> {\n try {\n const saved = await readStoreJson(root, `.mason/runtime/${runtime.id}/receipt.json`);\n if (JSON.stringify(saved) !== JSON.stringify(runtime)) return false;\n const base = `.mason/runtime/${runtime.id}/node_modules/mason-context/`;\n const pkg = await readStoreJson(root, base + \"package.json\") as { name?: string; version?: string } | null;\n if (pkg?.name !== \"mason-context\" || pkg.version !== runtime.version) return false;\n for (const file of BINARIES) {\n if (checksum(await fs.readFile(await storePath(root, base + file))) !== runtime.hashes[file]) return false;\n }\n return true;\n } catch { return false; }\n}\n\n/** Install the executing distribution, including unpublished local builds, outside the app's manifest. */\nexport async function installRuntime(root: string, selected: Awaited<ReturnType<typeof sourceRuntime>>) {\n const { runtime, source } = selected;\n if (await verifyRuntime(root, runtime)) return runtime;\n const relative = `.mason/runtime/${runtime.id}`;\n const target = await storePath(root, relative, true);\n const stage = await storePath(root, \".mason/runtime/.install-\" + randomUUID(), true);\n await fs.mkdir(stage);\n try {\n const npm = process.platform === \"win32\" ? \"npm.cmd\" : \"npm\";\n const options = { timeout: 120000, maxBuffer: 2 * 1024 * 1024, windowsHide: true };\n const packed = JSON.parse((await exec(npm, [\"pack\", \"--ignore-scripts\", \"--json\", \"--pack-destination\", stage], { ...options, cwd: source })).stdout);\n const filename = packed[0]?.filename;\n if (typeof filename !== \"string\" || path.basename(filename) !== filename) throw new Error(\"npm did not produce a Mason package archive.\");\n await fs.rename(path.join(stage, filename), path.join(stage, \"mason.tgz\"));\n await fs.writeFile(path.join(stage, \"package.json\"), JSON.stringify({ name: \"mason-project-runtime\", private: true, version: \"1.0.0\" }));\n await exec(npm, [\"install\", \"--ignore-scripts\", \"--omit=dev\", \"--no-audit\", \"--no-fund\", \"--save-exact\", \"./mason.tgz\"], { ...options, cwd: stage });\n for (const file of BINARIES) {\n if (checksum(await fs.readFile(path.join(stage, \"node_modules/mason-context\", file))) !== runtime.hashes[file]) throw new Error(\"Installed Mason binary differs from the selected distribution.\");\n }\n await fs.writeFile(path.join(stage, \"receipt.json\"), JSON.stringify(runtime, null, 2) + \"\\n\");\n // Keep a damaged prior runtime available for inspection; never merge partial installs.\n try { await fs.rename(target, target + \".previous-\" + randomUUID()); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n await fs.rename(stage, target);\n if (!await verifyRuntime(root, runtime)) throw new Error(\"The installed Mason runtime could not be verified.\");\n return runtime;\n } finally { await fs.rm(stage, { recursive: true, force: true }); }\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 { verifyRuntime } from \"./runtime.js\";\nimport { inspectHostConfig, instructionEdits } from \"./config.js\";\nimport { LAUNCHER, hookCommand, mcpCommand } from \"./launcher.js\";\nimport { readText } from \"./files.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 : \"Run mason-auto 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[] }> = {};\n const launcherCurrent = await readText(ws.root, \".mason/run.cjs\") === LAUNCHER;\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 installed = await verifyRuntime(ws.root, entry.runtime);\n const config = await inspectHostConfig(ws.root, host);\n const mcp = !config.mcpDisabled && hash(config.mcp) === entry.mcpFingerprint &&\n isDeepStrictEqual({ command: config.mcp?.command, args: config.mcp?.args }, mcpCommand(host));\n const hooks = isDeepStrictEqual(config.hooks, hookConfig(host, hookCommand(host)).hooks) && !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);\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 || !launcherCurrent) pending.push(\"Install this checkout's pinned runtime by rerunning setup.\");\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 && launcherCurrent && mcp && hooks && instructionsCurrent && configured && automation.status !== \"unavailable\";\n hosts[host] = { status: healthy ? complete && observation?.contextCalls ? \"active\" : \"pending\" : \"attention\",\n runtime: installed && launcherCurrent ? \"installed\" : \"missing-or-changed\", mcp: mcp ? \"configured\" : \"changed\",\n instructions: instructionsCurrent ? \"current\" : \"changed\", hookConfiguration: hooks ? \"configured\" : \"disabled-or-changed\",\n observedEvents, contextCalls: observation?.contextCalls ?? 0,\n verificationStatus: automation.status === \"current\" ? automation.verificationStatus ?? \"unavailable\" : \"unavailable\", pending };\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 }\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 { loadProjectMarker, saveProjectMarker } from \"../mcp/init.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 { LAUNCHER, hookCommand } from \"./launcher.js\";\nimport { hookConfig } from \"../automation/adapters.js\";\nimport { loadSetup, loadSetupReceipt, type SetupConfig } from \"./model.js\";\nimport { installRuntime, sourceRuntime } from \"./runtime.js\";\nimport { setupStatus } from \"./status.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[] } = {}) {\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 marker = await loadProjectMarker(ws.root);\n // Preflight every edit before npm runs or shared project files are changed.\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, \".mason/setup.json\");\n const selected = await sourceRuntime();\n const mcpFingerprint = hash((await inspectHostConfig(ws.root, host, mcp.after)).mcp);\n const desiredHooks = hookConfig(host, hookCommand(host)).hooks;\n const fingerprint = hash({ runtime: selected.runtime, launcher: LAUNCHER,\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: 1, hosts: {} };\n setup.hosts[host] = { runtime: selected.runtime, 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 const initial = await automate(ws.root, { event: \"turn_start\" });\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 await writeStoreJson(ws.root, receiptPath, { version: 1, host, status: \"installing\", initialReportPath,\n initialBaselinePaths, root: ws.root, revision });\n await installRuntime(ws.root, selected);\n const changedFiles: string[] = [];\n for (const edit of edits) if (await applyEdit(ws.root, edit)) changedFiles.push(edit.path);\n if (await applyEdit(ws.root, { path: \".mason/setup.json\", before: setupBefore, after: JSON.stringify(setup, null, 2) + \"\\n\" })) changedFiles.push(\".mason/setup.json\");\n if (!marker) {\n await saveProjectMarker(ws.root, { version: 1, initializedAt: new Date().toISOString() });\n changedFiles.push(\".mason/project.json\");\n }\n // Ensure a repo that initially had no instructions now has a baseline too.\n const checked = await automate(ws.root, { event: \"turn_start\" });\n const configured = await inspectHostConfig(ws.root, host);\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: selected.runtime, 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 \" Runtime installed; MCP server and lifecycle hooks configured.\",\n \" Project instructions updated; original audit evidence retained.\",\n ` ${result.changedFiles.length} shared 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 \"After the task finishes, run mason-auto status. Configuration alone does not establish activation.\",\n ].join(\"\\n\");\n}\n","import { automationFailure, failureMessage } from \"./execution.js\";\nimport { parseArgs } from \"node:util\";\nimport { automate, automationStatus, summarize } from \"./runtime.js\";\nimport { runAutomationHook, hookConfig } from \"./adapters.js\";\nimport { installAutomation, installedAutomation } from \"./install.js\";\nimport { hostSchema } from \"./store.js\";\n\nconst USAGE = `Usage: mason-auto <setup|install|config|status|check|hook> [options]\n\n setup [--host claude|codex] Install a pinned runtime, MCP, instructions and hooks; retain the initial audit\n install --host claude|codex Merge lifecycle hooks into this project's host config\n config --host claude|codex Print the host config without writing\n status Read configured hooks and observed runtime events\n check Capture/resume and verify retained audit evidence\n hook --host claude|codex Handle host JSON on stdin\n\n --dir <path> Project directory (defaults to cwd)\n --command <prefix> Installed executable prefix for install/config\n --json Machine-readable output (status also uses JSON when piped)\n\ncheck exits 0 for verified checks, 1 for issues, 2 for incomplete/unavailable.\nHooks are advisory and exit 0; a failed capture is reported explicitly.\nLocal evidence is written under .mason/reports/. No LLM calls or source edits.`;\n\nconst parseCli = (argv: string[]) => parseArgs({ args: argv, allowPositionals: true, options: {\n dir: { type: \"string\" }, host: { type: \"string\" }, command: { type: \"string\" }, json: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n } });\nexport function isHookCommand(argv: string[]): boolean {\n try { const parsed = parseCli(argv); return parsed.positionals[0] === \"hook\" && !parsed.values.help; }\n catch { return false; }\n}\n\nexport async function runAutomationCli(argv: string[], stdin = \"\", io = {\n out: (s: string) => process.stdout.write(s + \"\\n\"), err: (s: string) => process.stderr.write(s + \"\\n\"),\n}): Promise<number> {\n let action = \"\";\n try {\n const { values, positionals } = parseCli(argv);\n if (values.help || !positionals.length) { io.out(USAGE); return 0; }\n if (positionals.length !== 1) throw new Error(\"Expected one command.\");\n [action] = positionals;\n const dir = values.dir ?? process.cwd();\n if (action === \"hook\") {\n const output = await runAutomationHook(hostSchema.parse(values.host), stdin);\n if (output) io.out(JSON.stringify(output));\n return 0;\n }\n if (action === \"setup\") {\n if (values.command) throw new Error(\"--command applies to install/config, not managed setup.\");\n const { setupProject, summarizeSetup } = await import(\"../setup/setup.js\");\n const result = await setupProject(dir, { host: values.host ? hostSchema.parse(values.host) : undefined });\n io.out(values.json ? JSON.stringify(result, null, 2) : summarizeSetup(result));\n return 0;\n }\n if (action === \"install\" || action === \"config\") {\n const host = hostSchema.parse(values.host);\n io.out(JSON.stringify(action === \"install\" ? await installAutomation(dir, host, values.command) : hookConfig(host, values.command), null, 2));\n return 0;\n }\n if (values.host || values.command) throw new Error(\"--host and --command apply only to install/config/hook.\");\n if (action === \"status\") {\n const { setupStatus, summarizeActivation } = await import(\"../setup/status.js\");\n const setup = await setupStatus(dir);\n const result = { ...await automationStatus(dir), configured: await installedAutomation(dir), setup };\n io.out(values.json || !process.stdout.isTTY ? JSON.stringify(result, null, 2) : summarizeActivation(setup));\n return 0;\n }\n if (action !== \"check\") throw new Error(\"Unknown automation command: \" + action);\n const { report } = await automate(dir, { event: \"task_end\" });\n io.out(values.json ? JSON.stringify(report, null, 2) : summarize(report));\n return report.status === \"verified\" ? 0 : report.status === \"issues-remain\" ? 1 : 2;\n } catch (error) {\n const message = action === \"setup\" ? \"Mason setup incomplete: \" + automationFailure(error).message + \". Rerun the same setup command to resume; retained audit evidence is preserved.\"\n : failureMessage(error);\n if (action === \"hook\" || isHookCommand(argv)) { io.out(JSON.stringify({ systemMessage: message })); return 0; }\n if (argv.includes(\"--json\")) io.out(JSON.stringify({ version: 1, ...(action === \"setup\" ? { action, status: \"incomplete\", next: \"Rerun the same setup command to resume.\" } : { status: \"unavailable\" }), failure: automationFailure(error) }));\n else io.err(message);\n return 2;\n }\n}\n","import { runAutomationCli, isHookCommand } from \"../src/automation/cli.js\";\n\nconst argv = process.argv.slice(2);\nlet input = \"\";\nif (isHookCommand(argv) && !process.stdin.isTTY) {\n for await (const chunk of process.stdin) {\n input += chunk.toString();\n if (Buffer.byteLength(input) > 1024 * 1024) break;\n }\n}\nprocess.exitCode = await runAutomationCli(argv, input);\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,UAAU;AAGV,SAAS,kBAAkB,OAA8B;AAC9D,QAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG;AACtC,MAAI,CAAC,SAAS,MAAM,SAAS,IAAI,KAAK,KAAK,MAAM,WAAW,KAAK,KAAK,aAAa,KAAK,KAAK,EAAG,QAAO;AACvG,MAAI,MAAM,MAAM,GAAG,EAAE,SAAS,IAAI,EAAG,QAAO;AAC5C,QAAM,aAAa,KAAK,MAAM,UAAU,KAAK,EAAE,QAAQ,OAAO,EAAE;AAChE,SAAO,eAAe,MAAM,OAAO;AACrC;AAMO,SAAS,aAAa,MAAc,WAA4B;AACrE,QAAM,WAAW,KAAK,SAAS,MAAM,SAAS;AAC9C,SAAO,aAAa,QAAQ,CAAC,SAAS,WAAW,KAAK,KAAK,GAAG,EAAE,KAAK,CAAC,KAAK,WAAW,QAAQ;AAChG;AAEO,SAAS,cAAc,QAAgB,MAAuB;AACnE,QAAM,IAAI,kBAAkB,MAAM;AAClC,QAAM,IAAI,kBAAkB,IAAI;AAChC,SAAO,MAAM,QAAQ,MAAM,SAAS,MAAM,KAAK,EAAE,WAAW,GAAG,CAAC,GAAG;AACrE;AAEO,SAAS,cAAc,SAAmB,OAAmC;AAClF,SAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,EAAE,OAAO,UAAQ,QAAQ,KAAK,YAAU,cAAc,QAAQ,IAAI,CAAC,CAAC;AAC/F;AA5BA;AAAA;AAAA;AAAA;AAAA;;;ACAA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A,EACT;AACF;;;AC9EA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAI,QAAQ;AACZ,IAAI,cAAc,IAAI,KAAK,CAAC,QAAQ,MAAM,OAAO;AAC/C,mBAAiB,SAAS,QAAQ,OAAO;AACvC,aAAS,MAAM,SAAS;AACxB,QAAI,OAAO,WAAW,KAAK,IAAI,OAAO,KAAM;AAAA,EAC9C;AACF;AACA,QAAQ,WAAW,MAAM,iBAAiB,MAAM,KAAK;","names":["path","configPath","content","fs","path","randomUUID","message","attempt","path","count","path","execFile","promisify","z","exec","fs","path","execFile","promisify","exec","hash","content","execFile","promisify","exec","fs","path","execFile","promisify","exec","content","fs","path","fg","path","text","count","fs","path","fg","content","fs","path","fg","execFile","promisify","exec","text","path","z","index","message","fs","path","path","init_drift","init_drift","fs","path","fs","path","createHash","randomUUID","z","content","git","fs","path","createHash","execFile","promisify","fg","z","exec","text","exists","index","fs","os","z","randomUUID","git","report","notify","text","z","fs","z","z","input","observeActivation","message","z","z","execFile","promisify","exec","index","init_paths","message","init_types","z","index","count","init_paths","init_types","z","schema","rule","init_paths","init_types","path","z","index","input","checkSchema","init_evidence","init_types","fs","path","execFile","promisify","exec","init_drift","init_evidence","MAX_FINDINGS","init_evidence","fs","path","randomUUID","text","init_files","z","text","config","servers","index","planAutomationInstall","git","init_files","fs","path","randomUUID","createHash","execFile","promisify","exec","init_runtime","isDeepStrictEqual","message","init_runtime","init_files","randomUUID","init_files","init_runtime","argv","setupProject","summarizeSetup","setupStatus","summarizeActivation","message"]}